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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Viewer.get_command | (self, file, **options) |
Returns the command used to display the file.
Not implemented in the base class.
|
Returns the command used to display the file.
Not implemented in the base class.
| def get_command(self, file, **options):
"""
Returns the command used to display the file.
Not implemented in the base class.
"""
raise NotImplementedError | [
"def",
"get_command",
"(",
"self",
",",
"file",
",",
"*",
"*",
"options",
")",
":",
"raise",
"NotImplementedError"
] | [
93,
4
] | [
98,
33
] | python | en | ['en', 'error', 'th'] | False |
Viewer.save_image | (self, image) | Save to temporary file and return filename. | Save to temporary file and return filename. | def save_image(self, image):
"""Save to temporary file and return filename."""
return image._dump(format=self.get_format(image), **self.options) | [
"def",
"save_image",
"(",
"self",
",",
"image",
")",
":",
"return",
"image",
".",
"_dump",
"(",
"format",
"=",
"self",
".",
"get_format",
"(",
"image",
")",
",",
"*",
"*",
"self",
".",
"options",
")"
] | [
100,
4
] | [
102,
73
] | python | en | ['en', 'en', 'en'] | True |
Viewer.show_image | (self, image, **options) | Display the given image. | Display the given image. | def show_image(self, image, **options):
"""Display the given image."""
return self.show_file(self.save_image(image), **options) | [
"def",
"show_image",
"(",
"self",
",",
"image",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"show_file",
"(",
"self",
".",
"save_image",
"(",
"image",
")",
",",
"*",
"*",
"options",
")"
] | [
104,
4
] | [
106,
64
] | python | en | ['en', 'en', 'en'] | True |
Viewer.show_file | (self, file, **options) | Display the given file. | Display the given file. | def show_file(self, file, **options):
"""Display the given file."""
os.system(self.get_command(file, **options))
return 1 | [
"def",
"show_file",
"(",
"self",
",",
"file",
",",
"*",
"*",
"options",
")",
":",
"os",
".",
"system",
"(",
"self",
".",
"get_command",
"(",
"file",
",",
"*",
"*",
"options",
")",
")",
"return",
"1"
] | [
108,
4
] | [
111,
16
] | python | en | ['en', 'en', 'en'] | True |
MacViewer.show_file | (self, file, **options) | Display given file | Display given file | def show_file(self, file, **options):
"""Display given file"""
fd, path = tempfile.mkstemp()
with os.fdopen(fd, "w") as f:
f.write(file)
with open(path, "r") as f:
subprocess.Popen(
["im=$(cat); open -a Preview.app $im; sleep 20; rm -f $im"],
... | [
"def",
"show_file",
"(",
"self",
",",
"file",
",",
"*",
"*",
"options",
")",
":",
"fd",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"with",
"os",
".",
"fdopen",
"(",
"fd",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
... | [
150,
4
] | [
162,
16
] | python | en | ['en', 'en', 'en'] | True |
UnixViewer.show_file | (self, file, **options) | Display given file | Display given file | def show_file(self, file, **options):
"""Display given file"""
fd, path = tempfile.mkstemp()
with os.fdopen(fd, "w") as f:
f.write(file)
with open(path, "r") as f:
command = self.get_command_ex(file, **options)[0]
subprocess.Popen(
["im... | [
"def",
"show_file",
"(",
"self",
",",
"file",
",",
"*",
"*",
"options",
")",
":",
"fd",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"with",
"os",
".",
"fdopen",
"(",
"fd",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
... | [
177,
4
] | [
188,
16
] | python | en | ['en', 'en', 'en'] | True |
get_subset | (dataset, num_trainimages) |
reduce the size of the trainingset. Make sure that half of the images belongs to each class
trainimages: size of new dataset
|
reduce the size of the trainingset. Make sure that half of the images belongs to each class
trainimages: size of new dataset
| def get_subset(dataset, num_trainimages):
'''
reduce the size of the trainingset. Make sure that half of the images belongs to each class
trainimages: size of new dataset
'''
size_dataset = len(dataset.samples)
if num_trainimages > size_dataset:
raise ValueError("num_trainimages is large... | [
"def",
"get_subset",
"(",
"dataset",
",",
"num_trainimages",
")",
":",
"size_dataset",
"=",
"len",
"(",
"dataset",
".",
"samples",
")",
"if",
"num_trainimages",
">",
"size_dataset",
":",
"raise",
"ValueError",
"(",
"\"num_trainimages is larger than available dataset\"... | [
52,
0
] | [
74,
17
] | python | en | ['en', 'error', 'th'] | False |
eval_perf | (outputs, labels) | evaluate model performance | evaluate model performance | def eval_perf(outputs, labels):
"""evaluate model performance"""
sigm = torch.nn.Sigmoid()(outputs)
predicted = (sigm > 0.5).float()
# if predicted.sum().item()!=64:
# print(predicted.sum().item())
#print('number of images classified as class1: ', predicted.sum().item(), ' / ', labels.sum()... | [
"def",
"eval_perf",
"(",
"outputs",
",",
"labels",
")",
":",
"sigm",
"=",
"torch",
".",
"nn",
".",
"Sigmoid",
"(",
")",
"(",
"outputs",
")",
"predicted",
"=",
"(",
"sigm",
">",
"0.5",
")",
".",
"float",
"(",
")",
"# if predicted.sum().item()!=64:",
"# ... | [
77,
0
] | [
84,
64
] | python | en | ['es', 'en', 'en'] | True |
adjust_learning_rate | (optimizer, epoch, init_lr, epoch_decay) | Sets the learning rate to the initial LR decayed by 10 every epoch_decay epochs | Sets the learning rate to the initial LR decayed by 10 every epoch_decay epochs | def adjust_learning_rate(optimizer, epoch, init_lr, epoch_decay):
"""Sets the learning rate to the initial LR decayed by 10 every epoch_decay epochs"""
lr = init_lr * (0.1 ** (epoch // epoch_decay))
for param_group in optimizer.param_groups:
param_group['lr'] = lr | [
"def",
"adjust_learning_rate",
"(",
"optimizer",
",",
"epoch",
",",
"init_lr",
",",
"epoch_decay",
")",
":",
"lr",
"=",
"init_lr",
"*",
"(",
"0.1",
"**",
"(",
"epoch",
"//",
"epoch_decay",
")",
")",
"for",
"param_group",
"in",
"optimizer",
".",
"param_grou... | [
87,
0
] | [
91,
30
] | python | en | ['en', 'en', 'en'] | True |
adjust_learning_rate_plateau | (optimizer, epoch, init_lr, counter_lr_adjust) | Sets the learning rate to the initial LR decayed by 10
when there is a plateau in the validation loss | Sets the learning rate to the initial LR decayed by 10
when there is a plateau in the validation loss | def adjust_learning_rate_plateau(optimizer, epoch, init_lr, counter_lr_adjust):
"""Sets the learning rate to the initial LR decayed by 10
when there is a plateau in the validation loss"""
lr = init_lr * (0.1 ** counter_lr_adjust)
for param_group in optimizer.param_groups:
param_group['lr'] = lr | [
"def",
"adjust_learning_rate_plateau",
"(",
"optimizer",
",",
"epoch",
",",
"init_lr",
",",
"counter_lr_adjust",
")",
":",
"lr",
"=",
"init_lr",
"*",
"(",
"0.1",
"**",
"counter_lr_adjust",
")",
"for",
"param_group",
"in",
"optimizer",
".",
"param_groups",
":",
... | [
94,
0
] | [
99,
30
] | python | en | ['en', 'en', 'en'] | True |
train | (
net,
model,
regularization,
trainloader,
optimizer,
criterion,
writer,
epoch,
checkpointdir,
step) | train the net
| train the net
| def train(
net,
model,
regularization,
trainloader,
optimizer,
criterion,
writer,
epoch,
checkpointdir,
step):
"""train the net
"""
model.train()
# save memory and computation cost by not calculating the grad
torch.set_... | [
"def",
"train",
"(",
"net",
",",
"model",
",",
"regularization",
",",
"trainloader",
",",
"optimizer",
",",
"criterion",
",",
"writer",
",",
"epoch",
",",
"checkpointdir",
",",
"step",
")",
":",
"model",
".",
"train",
"(",
")",
"# save memory and computation... | [
121,
0
] | [
218,
26
] | python | en | ['en', 'fy', 'en'] | True |
validate | (
net,
model,
regularization,
valloader,
criterion,
writer,
epoch,
step) | validate the model
| validate the model
| def validate(
net,
model,
regularization,
valloader,
criterion,
writer,
epoch,
step):
"""validate the model
"""
model.eval()
# save memory and computation cost by not calculating the grad
torch.set_grad_enabled(False)
losses = Ave... | [
"def",
"validate",
"(",
"net",
",",
"model",
",",
"regularization",
",",
"valloader",
",",
"criterion",
",",
"writer",
",",
"epoch",
",",
"step",
")",
":",
"model",
".",
"eval",
"(",
")",
"# save memory and computation cost by not calculating the grad",
"torch",
... | [
221,
0
] | [
294,
46
] | python | en | ['en', 'en', 'en'] | True |
StaticLiveServerView.test_collectstatic_emulation | (self) |
Test that StaticLiveServerTestCase use of staticfiles' serve() allows it
to discover app's static assets without having to collectstatic first.
|
Test that StaticLiveServerTestCase use of staticfiles' serve() allows it
to discover app's static assets without having to collectstatic first.
| def test_collectstatic_emulation(self):
"""
Test that StaticLiveServerTestCase use of staticfiles' serve() allows it
to discover app's static assets without having to collectstatic first.
"""
f = self.urlopen('/static/test/file.txt')
self.assertEqual(f.read().rstrip(b'\r\... | [
"def",
"test_collectstatic_emulation",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"urlopen",
"(",
"'/static/test/file.txt'",
")",
"self",
".",
"assertEqual",
"(",
"f",
".",
"read",
"(",
")",
".",
"rstrip",
"(",
"b'\\r\\n'",
")",
",",
"b'In app media direc... | [
93,
4
] | [
99,
78
] | python | en | ['en', 'error', 'th'] | False |
arg_byref | (args, offset=-1) | Return the pointer argument's by-reference value. | Return the pointer argument's by-reference value. | def arg_byref(args, offset=-1):
"Return the pointer argument's by-reference value."
return args[offset]._obj.value | [
"def",
"arg_byref",
"(",
"args",
",",
"offset",
"=",
"-",
"1",
")",
":",
"return",
"args",
"[",
"offset",
"]",
".",
"_obj",
".",
"value"
] | [
14,
0
] | [
16,
34
] | python | en | ['en', 'en', 'en'] | True |
ptr_byref | (args, offset=-1) | Return the pointer argument passed in by-reference. | Return the pointer argument passed in by-reference. | def ptr_byref(args, offset=-1):
"Return the pointer argument passed in by-reference."
return args[offset]._obj | [
"def",
"ptr_byref",
"(",
"args",
",",
"offset",
"=",
"-",
"1",
")",
":",
"return",
"args",
"[",
"offset",
"]",
".",
"_obj"
] | [
19,
0
] | [
21,
28
] | python | en | ['en', 'en', 'en'] | True |
check_const_string | (result, func, cargs, offset=None, cpl=False) |
Similar functionality to `check_string`, but does not free the pointer.
|
Similar functionality to `check_string`, but does not free the pointer.
| def check_const_string(result, func, cargs, offset=None, cpl=False):
"""
Similar functionality to `check_string`, but does not free the pointer.
"""
if offset:
check_err(result, cpl=cpl)
ptr = ptr_byref(cargs, offset)
return ptr.value
else:
return result | [
"def",
"check_const_string",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
"=",
"None",
",",
"cpl",
"=",
"False",
")",
":",
"if",
"offset",
":",
"check_err",
"(",
"result",
",",
"cpl",
"=",
"cpl",
")",
"ptr",
"=",
"ptr_byref",
"(",
"cargs"... | [
25,
0
] | [
34,
21
] | python | en | ['en', 'error', 'th'] | False |
check_string | (result, func, cargs, offset=-1, str_result=False) |
Check the string output returned from the given function, and free
the string pointer allocated by OGR. The `str_result` keyword
may be used when the result is the string pointer, otherwise
the OGR error code is assumed. The `offset` keyword may be used
to extract the string pointer passed in by-... |
Check the string output returned from the given function, and free
the string pointer allocated by OGR. The `str_result` keyword
may be used when the result is the string pointer, otherwise
the OGR error code is assumed. The `offset` keyword may be used
to extract the string pointer passed in by-... | def check_string(result, func, cargs, offset=-1, str_result=False):
"""
Check the string output returned from the given function, and free
the string pointer allocated by OGR. The `str_result` keyword
may be used when the result is the string pointer, otherwise
the OGR error code is assumed. The `... | [
"def",
"check_string",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
"=",
"-",
"1",
",",
"str_result",
"=",
"False",
")",
":",
"if",
"str_result",
":",
"# For routines that return a string.",
"ptr",
"=",
"result",
"if",
"not",
"ptr",
":",
"s",
... | [
37,
0
] | [
63,
12
] | python | en | ['en', 'error', 'th'] | False |
check_envelope | (result, func, cargs, offset=-1) | Check a function that returns an OGR Envelope by reference. | Check a function that returns an OGR Envelope by reference. | def check_envelope(result, func, cargs, offset=-1):
"Check a function that returns an OGR Envelope by reference."
return ptr_byref(cargs, offset) | [
"def",
"check_envelope",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
"=",
"-",
"1",
")",
":",
"return",
"ptr_byref",
"(",
"cargs",
",",
"offset",
")"
] | [
69,
0
] | [
71,
35
] | python | en | ['en', 'en', 'en'] | True |
check_geom | (result, func, cargs) | Check a function that returns a geometry. | Check a function that returns a geometry. | def check_geom(result, func, cargs):
"Check a function that returns a geometry."
# OGR_G_Clone may return an integer, even though the
# restype is set to c_void_p
if isinstance(result, int):
result = c_void_p(result)
if not result:
raise GDALException('Invalid geometry pointer return... | [
"def",
"check_geom",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"# OGR_G_Clone may return an integer, even though the",
"# restype is set to c_void_p",
"if",
"isinstance",
"(",
"result",
",",
"int",
")",
":",
"result",
"=",
"c_void_p",
"(",
"result",
")",
... | [
75,
0
] | [
83,
17
] | python | en | ['en', 'en', 'en'] | True |
check_geom_offset | (result, func, cargs, offset=-1) | Check the geometry at the given offset in the C parameter list. | Check the geometry at the given offset in the C parameter list. | def check_geom_offset(result, func, cargs, offset=-1):
"Check the geometry at the given offset in the C parameter list."
check_err(result)
geom = ptr_byref(cargs, offset=offset)
return check_geom(geom, func, cargs) | [
"def",
"check_geom_offset",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
"=",
"-",
"1",
")",
":",
"check_err",
"(",
"result",
")",
"geom",
"=",
"ptr_byref",
"(",
"cargs",
",",
"offset",
"=",
"offset",
")",
"return",
"check_geom",
"(",
"geom... | [
86,
0
] | [
90,
40
] | python | en | ['en', 'en', 'en'] | True |
check_arg_errcode | (result, func, cargs, cpl=False) |
The error code is returned in the last argument, by reference.
Check its value with `check_err` before returning the result.
|
The error code is returned in the last argument, by reference.
Check its value with `check_err` before returning the result.
| def check_arg_errcode(result, func, cargs, cpl=False):
"""
The error code is returned in the last argument, by reference.
Check its value with `check_err` before returning the result.
"""
check_err(arg_byref(cargs), cpl=cpl)
return result | [
"def",
"check_arg_errcode",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"cpl",
"=",
"False",
")",
":",
"check_err",
"(",
"arg_byref",
"(",
"cargs",
")",
",",
"cpl",
"=",
"cpl",
")",
"return",
"result"
] | [
103,
0
] | [
109,
17
] | python | en | ['en', 'error', 'th'] | False |
check_errcode | (result, func, cargs, cpl=False) |
Check the error code returned (c_int).
|
Check the error code returned (c_int).
| def check_errcode(result, func, cargs, cpl=False):
"""
Check the error code returned (c_int).
"""
check_err(result, cpl=cpl) | [
"def",
"check_errcode",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"cpl",
"=",
"False",
")",
":",
"check_err",
"(",
"result",
",",
"cpl",
"=",
"cpl",
")"
] | [
112,
0
] | [
116,
30
] | python | en | ['en', 'error', 'th'] | False |
check_pointer | (result, func, cargs) | Make sure the result pointer is valid. | Make sure the result pointer is valid. | def check_pointer(result, func, cargs):
"Make sure the result pointer is valid."
if isinstance(result, int):
result = c_void_p(result)
if result:
return result
else:
raise GDALException('Invalid pointer returned from "%s"' % func.__name__) | [
"def",
"check_pointer",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"int",
")",
":",
"result",
"=",
"c_void_p",
"(",
"result",
")",
"if",
"result",
":",
"return",
"result",
"else",
":",
"raise",
"GDALExce... | [
119,
0
] | [
126,
81
] | python | en | ['en', 'en', 'en'] | True |
check_str_arg | (result, func, cargs) |
This is for the OSRGet[Angular|Linear]Units functions, which
require that the returned string pointer not be freed. This
returns both the double and string values.
|
This is for the OSRGet[Angular|Linear]Units functions, which
require that the returned string pointer not be freed. This
returns both the double and string values.
| def check_str_arg(result, func, cargs):
"""
This is for the OSRGet[Angular|Linear]Units functions, which
require that the returned string pointer not be freed. This
returns both the double and string values.
"""
dbl = result
ptr = cargs[-1]._obj
return dbl, ptr.value.decode() | [
"def",
"check_str_arg",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"dbl",
"=",
"result",
"ptr",
"=",
"cargs",
"[",
"-",
"1",
"]",
".",
"_obj",
"return",
"dbl",
",",
"ptr",
".",
"value",
".",
"decode",
"(",
")"
] | [
129,
0
] | [
137,
34
] | python | en | ['en', 'error', 'th'] | False |
build_wheel | (source_dir, wheel_dir, config_settings=None) | Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subpr... | Build a wheel from a source directory using PEP 517 hooks. | def build_wheel(source_dir, wheel_dir, config_settings=None):
"""Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build b... | [
"def",
"build_wheel",
"(",
"source_dir",
",",
"wheel_dir",
",",
"config_settings",
"=",
"None",
")",
":",
"if",
"config_settings",
"is",
"None",
":",
"config_settings",
"=",
"{",
"}",
"requires",
",",
"backend",
",",
"backend_path",
"=",
"_load_pyproject",
"("... | [
125,
0
] | [
144,
60
] | python | en | ['en', 'en', 'en'] | True |
build_sdist | (source_dir, sdist_dir, config_settings=None) | Build an sdist from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str sdist_dir: Target directory to place sdist in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subpr... | Build an sdist from a source directory using PEP 517 hooks. | def build_sdist(source_dir, sdist_dir, config_settings=None):
"""Build an sdist from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str sdist_dir: Target directory to place sdist in
:param dict config_settings: Options to pass to build b... | [
"def",
"build_sdist",
"(",
"source_dir",
",",
"sdist_dir",
",",
"config_settings",
"=",
"None",
")",
":",
"if",
"config_settings",
"is",
"None",
":",
"config_settings",
"=",
"{",
"}",
"requires",
",",
"backend",
",",
"backend_path",
"=",
"_load_pyproject",
"("... | [
147,
0
] | [
166,
60
] | python | en | ['en', 'en', 'en'] | True |
BuildEnvironment.pip_install | (self, reqs) | Install dependencies into this env by calling pip in a subprocess | Install dependencies into this env by calling pip in a subprocess | def pip_install(self, reqs):
"""Install dependencies into this env by calling pip in a subprocess"""
if not reqs:
return
log.info('Calling pip to install %s', reqs)
cmd = [
sys.executable, '-m', 'pip', 'install', '--ignore-installed',
'--prefix', self.... | [
"def",
"pip_install",
"(",
"self",
",",
"reqs",
")",
":",
"if",
"not",
"reqs",
":",
"return",
"log",
".",
"info",
"(",
"'Calling pip to install %s'",
",",
"reqs",
")",
"cmd",
"=",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'install... | [
91,
4
] | [
103,
9
] | python | en | ['en', 'en', 'en'] | True |
Apps.populate | (self, installed_apps=None) |
Load application configurations and models.
Import each application module and then each model module.
It is thread-safe and idempotent, but not reentrant.
|
Load application configurations and models. | def populate(self, installed_apps=None):
"""
Load application configurations and models.
Import each application module and then each model module.
It is thread-safe and idempotent, but not reentrant.
"""
if self.ready:
return
# populate() might be ... | [
"def",
"populate",
"(",
"self",
",",
"installed_apps",
"=",
"None",
")",
":",
"if",
"self",
".",
"ready",
":",
"return",
"# populate() might be called by two threads in parallel on servers",
"# that create threads before initializing the WSGI callable.",
"with",
"self",
".",
... | [
60,
4
] | [
124,
34
] | python | en | ['en', 'error', 'th'] | False |
Apps.check_apps_ready | (self) | Raise an exception if all apps haven't been imported yet. | Raise an exception if all apps haven't been imported yet. | def check_apps_ready(self):
"""Raise an exception if all apps haven't been imported yet."""
if not self.apps_ready:
from django.conf import settings
# If "not ready" is due to unconfigured settings, accessing
# INSTALLED_APPS raises a more helpful ImproperlyConfigured... | [
"def",
"check_apps_ready",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"apps_ready",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"# If \"not ready\" is due to unconfigured settings, accessing",
"# INSTALLED_APPS raises a more helpful ImproperlyConfigured",
... | [
126,
4
] | [
134,
64
] | python | en | ['en', 'en', 'en'] | True |
Apps.check_models_ready | (self) | Raise an exception if all models haven't been imported yet. | Raise an exception if all models haven't been imported yet. | def check_models_ready(self):
"""Raise an exception if all models haven't been imported yet."""
if not self.models_ready:
raise AppRegistryNotReady("Models aren't loaded yet.") | [
"def",
"check_models_ready",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"models_ready",
":",
"raise",
"AppRegistryNotReady",
"(",
"\"Models aren't loaded yet.\"",
")"
] | [
136,
4
] | [
139,
66
] | python | en | ['en', 'en', 'en'] | True |
Apps.get_app_configs | (self) | Import applications and return an iterable of app configs. | Import applications and return an iterable of app configs. | def get_app_configs(self):
"""Import applications and return an iterable of app configs."""
self.check_apps_ready()
return self.app_configs.values() | [
"def",
"get_app_configs",
"(",
"self",
")",
":",
"self",
".",
"check_apps_ready",
"(",
")",
"return",
"self",
".",
"app_configs",
".",
"values",
"(",
")"
] | [
141,
4
] | [
144,
40
] | python | en | ['en', 'en', 'en'] | True |
Apps.get_app_config | (self, app_label) |
Import applications and returns an app config for the given label.
Raise LookupError if no application exists with this label.
|
Import applications and returns an app config for the given label. | def get_app_config(self, app_label):
"""
Import applications and returns an app config for the given label.
Raise LookupError if no application exists with this label.
"""
self.check_apps_ready()
try:
return self.app_configs[app_label]
except KeyError... | [
"def",
"get_app_config",
"(",
"self",
",",
"app_label",
")",
":",
"self",
".",
"check_apps_ready",
"(",
")",
"try",
":",
"return",
"self",
".",
"app_configs",
"[",
"app_label",
"]",
"except",
"KeyError",
":",
"message",
"=",
"\"No installed app with label '%s'.\... | [
146,
4
] | [
161,
38
] | python | en | ['en', 'error', 'th'] | False |
Apps.get_models | (self, include_auto_created=False, include_swapped=False) |
Return a list of all installed models.
By default, the following models aren't included:
- auto-created models for many-to-many relations without
an explicit intermediate table,
- models that have been swapped out.
Set the corresponding keyword argument to True to i... |
Return a list of all installed models. | def get_models(self, include_auto_created=False, include_swapped=False):
"""
Return a list of all installed models.
By default, the following models aren't included:
- auto-created models for many-to-many relations without
an explicit intermediate table,
- models that... | [
"def",
"get_models",
"(",
"self",
",",
"include_auto_created",
"=",
"False",
",",
"include_swapped",
"=",
"False",
")",
":",
"self",
".",
"check_models_ready",
"(",
")",
"result",
"=",
"[",
"]",
"for",
"app_config",
"in",
"self",
".",
"app_configs",
".",
"... | [
165,
4
] | [
182,
21
] | python | en | ['en', 'error', 'th'] | False |
Apps.get_model | (self, app_label, model_name=None, require_ready=True) |
Return the model matching the given app_label and model_name.
As a shortcut, app_label may be in the form <app_label>.<model_name>.
model_name is case-insensitive.
Raise LookupError if no application exists with this label, or no
model exists with this name in the application... |
Return the model matching the given app_label and model_name. | def get_model(self, app_label, model_name=None, require_ready=True):
"""
Return the model matching the given app_label and model_name.
As a shortcut, app_label may be in the form <app_label>.<model_name>.
model_name is case-insensitive.
Raise LookupError if no application exis... | [
"def",
"get_model",
"(",
"self",
",",
"app_label",
",",
"model_name",
"=",
"None",
",",
"require_ready",
"=",
"True",
")",
":",
"if",
"require_ready",
":",
"self",
".",
"check_models_ready",
"(",
")",
"else",
":",
"self",
".",
"check_apps_ready",
"(",
")",... | [
184,
4
] | [
209,
76
] | python | en | ['en', 'error', 'th'] | False |
Apps.is_installed | (self, app_name) |
Check whether an application with this name exists in the registry.
app_name is the full name of the app e.g. 'django.contrib.admin'.
|
Check whether an application with this name exists in the registry. | def is_installed(self, app_name):
"""
Check whether an application with this name exists in the registry.
app_name is the full name of the app e.g. 'django.contrib.admin'.
"""
self.check_apps_ready()
return any(ac.name == app_name for ac in self.app_configs.values()) | [
"def",
"is_installed",
"(",
"self",
",",
"app_name",
")",
":",
"self",
".",
"check_apps_ready",
"(",
")",
"return",
"any",
"(",
"ac",
".",
"name",
"==",
"app_name",
"for",
"ac",
"in",
"self",
".",
"app_configs",
".",
"values",
"(",
")",
")"
] | [
233,
4
] | [
240,
75
] | python | en | ['en', 'error', 'th'] | False |
Apps.get_containing_app_config | (self, object_name) |
Look for an app config containing a given object.
object_name is the dotted Python path to the object.
Return the app config for the inner application in case of nesting.
Return None if the object isn't in any registered app config.
|
Look for an app config containing a given object. | def get_containing_app_config(self, object_name):
"""
Look for an app config containing a given object.
object_name is the dotted Python path to the object.
Return the app config for the inner application in case of nesting.
Return None if the object isn't in any registered app... | [
"def",
"get_containing_app_config",
"(",
"self",
",",
"object_name",
")",
":",
"self",
".",
"check_apps_ready",
"(",
")",
"candidates",
"=",
"[",
"]",
"for",
"app_config",
"in",
"self",
".",
"app_configs",
".",
"values",
"(",
")",
":",
"if",
"object_name",
... | [
242,
4
] | [
259,
70
] | python | en | ['en', 'error', 'th'] | False |
Apps.get_registered_model | (self, app_label, model_name) |
Similar to get_model(), but doesn't require that an app exists with
the given app_label.
It's safe to call this method at import time, even while the registry
is being populated.
|
Similar to get_model(), but doesn't require that an app exists with
the given app_label. | def get_registered_model(self, app_label, model_name):
"""
Similar to get_model(), but doesn't require that an app exists with
the given app_label.
It's safe to call this method at import time, even while the registry
is being populated.
"""
model = self.all_mode... | [
"def",
"get_registered_model",
"(",
"self",
",",
"app_label",
",",
"model_name",
")",
":",
"model",
"=",
"self",
".",
"all_models",
"[",
"app_label",
"]",
".",
"get",
"(",
"model_name",
".",
"lower",
"(",
")",
")",
"if",
"model",
"is",
"None",
":",
"ra... | [
261,
4
] | [
273,
20
] | python | en | ['en', 'error', 'th'] | False |
Apps.get_swappable_settings_name | (self, to_string) |
For a given model string (e.g. "auth.User"), return the name of the
corresponding settings name if it refers to a swappable model. If the
referred model is not swappable, return None.
This method is decorated with lru_cache because it's performance
critical when it comes to mig... |
For a given model string (e.g. "auth.User"), return the name of the
corresponding settings name if it refers to a swappable model. If the
referred model is not swappable, return None. | def get_swappable_settings_name(self, to_string):
"""
For a given model string (e.g. "auth.User"), return the name of the
corresponding settings name if it refers to a swappable model. If the
referred model is not swappable, return None.
This method is decorated with lru_cache b... | [
"def",
"get_swappable_settings_name",
"(",
"self",
",",
"to_string",
")",
":",
"for",
"model",
"in",
"self",
".",
"get_models",
"(",
"include_swapped",
"=",
"True",
")",
":",
"swapped",
"=",
"model",
".",
"_meta",
".",
"swapped",
"# Is this model swapped out for... | [
276,
4
] | [
295,
19
] | python | en | ['en', 'error', 'th'] | False |
Apps.set_available_apps | (self, available) |
Restrict the set of installed apps used by get_app_config[s].
available must be an iterable of application names.
set_available_apps() must be balanced with unset_available_apps().
Primarily used for performance optimization in TransactionTestCase.
This method is safe in the... |
Restrict the set of installed apps used by get_app_config[s]. | def set_available_apps(self, available):
"""
Restrict the set of installed apps used by get_app_config[s].
available must be an iterable of application names.
set_available_apps() must be balanced with unset_available_apps().
Primarily used for performance optimization in Tran... | [
"def",
"set_available_apps",
"(",
"self",
",",
"available",
")",
":",
"available",
"=",
"set",
"(",
"available",
")",
"installed",
"=",
"{",
"app_config",
".",
"name",
"for",
"app_config",
"in",
"self",
".",
"get_app_configs",
"(",
")",
"}",
"if",
"not",
... | [
297,
4
] | [
323,
26
] | python | en | ['en', 'error', 'th'] | False |
Apps.unset_available_apps | (self) | Cancel a previous call to set_available_apps(). | Cancel a previous call to set_available_apps(). | def unset_available_apps(self):
"""Cancel a previous call to set_available_apps()."""
self.app_configs = self.stored_app_configs.pop()
self.clear_cache() | [
"def",
"unset_available_apps",
"(",
"self",
")",
":",
"self",
".",
"app_configs",
"=",
"self",
".",
"stored_app_configs",
".",
"pop",
"(",
")",
"self",
".",
"clear_cache",
"(",
")"
] | [
325,
4
] | [
328,
26
] | python | en | ['en', 'en', 'en'] | True |
Apps.set_installed_apps | (self, installed) |
Enable a different set of installed apps for get_app_config[s].
installed must be an iterable in the same format as INSTALLED_APPS.
set_installed_apps() must be balanced with unset_installed_apps(),
even if it exits with an exception.
Primarily used as a receiver of the setti... |
Enable a different set of installed apps for get_app_config[s]. | def set_installed_apps(self, installed):
"""
Enable a different set of installed apps for get_app_config[s].
installed must be an iterable in the same format as INSTALLED_APPS.
set_installed_apps() must be balanced with unset_installed_apps(),
even if it exits with an exception... | [
"def",
"set_installed_apps",
"(",
"self",
",",
"installed",
")",
":",
"if",
"not",
"self",
".",
"ready",
":",
"raise",
"AppRegistryNotReady",
"(",
"\"App registry isn't ready yet.\"",
")",
"self",
".",
"stored_app_configs",
".",
"append",
"(",
"self",
".",
"app_... | [
330,
4
] | [
353,
32
] | python | en | ['en', 'error', 'th'] | False |
Apps.unset_installed_apps | (self) | Cancel a previous call to set_installed_apps(). | Cancel a previous call to set_installed_apps(). | def unset_installed_apps(self):
"""Cancel a previous call to set_installed_apps()."""
self.app_configs = self.stored_app_configs.pop()
self.apps_ready = self.models_ready = self.ready = True
self.clear_cache() | [
"def",
"unset_installed_apps",
"(",
"self",
")",
":",
"self",
".",
"app_configs",
"=",
"self",
".",
"stored_app_configs",
".",
"pop",
"(",
")",
"self",
".",
"apps_ready",
"=",
"self",
".",
"models_ready",
"=",
"self",
".",
"ready",
"=",
"True",
"self",
"... | [
355,
4
] | [
359,
26
] | python | en | ['en', 'en', 'en'] | True |
Apps.clear_cache | (self) |
Clear all internal caches, for methods that alter the app registry.
This is mostly used in tests.
|
Clear all internal caches, for methods that alter the app registry. | def clear_cache(self):
"""
Clear all internal caches, for methods that alter the app registry.
This is mostly used in tests.
"""
# Call expire cache on each model. This will purge
# the relation tree and the fields cache.
self.get_models.cache_clear()
if ... | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"# Call expire cache on each model. This will purge",
"# the relation tree and the fields cache.",
"self",
".",
"get_models",
".",
"cache_clear",
"(",
")",
"if",
"self",
".",
"ready",
":",
"# Circumvent self.get_models() to prevent... | [
361,
4
] | [
375,
47
] | python | en | ['en', 'error', 'th'] | False |
Apps.lazy_model_operation | (self, function, *model_keys) |
Take a function and a number of ("app_label", "modelname") tuples, and
when all the corresponding models have been imported and registered,
call the function with the model classes as its arguments.
The function passed to this method must accept exactly n models as
arguments, w... |
Take a function and a number of ("app_label", "modelname") tuples, and
when all the corresponding models have been imported and registered,
call the function with the model classes as its arguments. | def lazy_model_operation(self, function, *model_keys):
"""
Take a function and a number of ("app_label", "modelname") tuples, and
when all the corresponding models have been imported and registered,
call the function with the model classes as its arguments.
The function passed t... | [
"def",
"lazy_model_operation",
"(",
"self",
",",
"function",
",",
"*",
"model_keys",
")",
":",
"# Base case: no arguments, just execute the function.",
"if",
"not",
"model_keys",
":",
"function",
"(",
")",
"# Recursive case: take the head of model_keys, wait for the",
"# corr... | [
377,
4
] | [
414,
45
] | python | en | ['en', 'error', 'th'] | False |
Apps.do_pending_operations | (self, model) |
Take a newly-prepared model and pass it to each function waiting for
it. This is called at the very end of Apps.register_model().
|
Take a newly-prepared model and pass it to each function waiting for
it. This is called at the very end of Apps.register_model().
| def do_pending_operations(self, model):
"""
Take a newly-prepared model and pass it to each function waiting for
it. This is called at the very end of Apps.register_model().
"""
key = model._meta.app_label, model._meta.model_name
for function in self._pending_operations.p... | [
"def",
"do_pending_operations",
"(",
"self",
",",
"model",
")",
":",
"key",
"=",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
"_meta",
".",
"model_name",
"for",
"function",
"in",
"self",
".",
"_pending_operations",
".",
"pop",
"(",
"key",
... | [
416,
4
] | [
423,
27
] | python | en | ['en', 'error', 'th'] | False |
colorize | (text='', opts=(), **kwargs) |
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
Valid o... |
Returns your text, enclosed in ANSI graphics codes. | def colorize(text='', opts=(), **kwargs):
"""
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow'... | [
"def",
"colorize",
"(",
"text",
"=",
"''",
",",
"opts",
"=",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"color_names",
"=",
"(",
"'black'",
",",
"'red'",
",",
"'green'",
",",
"'yellow'",
",",
"'blue'",
",",
"'magenta'",
",",
"'cyan'",
",",
"'whit... | [
117,
0
] | [
167,
52
] | python | en | ['en', 'error', 'th'] | False |
watch_for_translation_changes | (sender, **kwargs) | Register file watchers for .mo files in potential locale paths. | Register file watchers for .mo files in potential locale paths. | def watch_for_translation_changes(sender, **kwargs):
"""Register file watchers for .mo files in potential locale paths."""
from django.conf import settings
if settings.USE_I18N:
directories = [Path('locale')]
directories.extend(Path(config.path) / 'locale' for config in apps.get_app_configs... | [
"def",
"watch_for_translation_changes",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"if",
"settings",
".",
"USE_I18N",
":",
"directories",
"=",
"[",
"Path",
"(",
"'locale'",
")",
"]",
"directories",
... | [
7,
0
] | [
16,
45
] | python | en | ['en', 'en', 'en'] | True |
translation_file_changed | (sender, file_path, **kwargs) | Clear the internal translations cache if a .mo file is modified. | Clear the internal translations cache if a .mo file is modified. | def translation_file_changed(sender, file_path, **kwargs):
"""Clear the internal translations cache if a .mo file is modified."""
if file_path.suffix == '.mo':
import gettext
from django.utils.translation import trans_real
gettext._translations = {}
trans_real._translations = {}
... | [
"def",
"translation_file_changed",
"(",
"sender",
",",
"file_path",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"file_path",
".",
"suffix",
"==",
"'.mo'",
":",
"import",
"gettext",
"from",
"django",
".",
"utils",
".",
"translation",
"import",
"trans_real",
"get... | [
19,
0
] | [
28,
19
] | python | en | ['en', 'en', 'en'] | True |
Local.vote_comment | (self, blogId: str, commentId: str, value: int = 1) |
vote & unvote comment.
**Parameters**
- **blogId** : Id of the blog.
- **commentId** : Comment id.
- **value** : 1 for upvote -1 for downvote.
**Returns**
- **Success** : :meth:`Json Object <samino.lib.objects.Json>`
-... |
vote & unvote comment. | def vote_comment(self, blogId: str, commentId: str, value: int = 1):
"""
vote & unvote comment.
**Parameters**
- **blogId** : Id of the blog.
- **commentId** : Comment id.
- **value** : 1 for upvote -1 for downvote.
**Returns**
... | [
"def",
"vote_comment",
"(",
"self",
",",
"blogId",
":",
"str",
",",
"commentId",
":",
"str",
",",
"value",
":",
"int",
"=",
"1",
")",
":",
"if",
"value",
"!=",
"1",
":",
"pass",
"elif",
"value",
"!=",
"-",
"1",
":",
"raise",
"TypeError",
"(",
"f\... | [
353,
4
] | [
373,
31
] | python | en | ['en', 'error', 'th'] | False |
uts46_remap | (domain, std3_rules=True, transitional=False) | Re-map the characters in the string according to UTS46 processing. | Re-map the characters in the string according to UTS46 processing. | def uts46_remap(domain, std3_rules=True, transitional=False):
"""Re-map the characters in the string according to UTS46 processing."""
from .uts46data import uts46data
output = u""
try:
for pos, char in enumerate(domain):
code_point = ord(char)
uts46row = uts46data[code_p... | [
"def",
"uts46_remap",
"(",
"domain",
",",
"std3_rules",
"=",
"True",
",",
"transitional",
"=",
"False",
")",
":",
"from",
".",
"uts46data",
"import",
"uts46data",
"output",
"=",
"u\"\"",
"try",
":",
"for",
"pos",
",",
"char",
"in",
"enumerate",
"(",
"dom... | [
315,
0
] | [
340,
54
] | python | en | ['en', 'en', 'en'] | True |
SubscribeRequest.__init__ | (self, principal) |
Initialize the request.
:param principal: Principal email to impersonate
|
Initialize the request. | def __init__(self, principal):
"""
Initialize the request.
:param principal: Principal email to impersonate
"""
root = M.Subscribe(
M.StreamingSubscriptionRequest(
T.FolderIds(get_distinguished_folder_id_element(principal, 'calendar')),
... | [
"def",
"__init__",
"(",
"self",
",",
"principal",
")",
":",
"root",
"=",
"M",
".",
"Subscribe",
"(",
"M",
".",
"StreamingSubscriptionRequest",
"(",
"T",
".",
"FolderIds",
"(",
"get_distinguished_folder_id_element",
"(",
"principal",
",",
"'calendar'",
")",
")"... | [
29,
4
] | [
49,
77
] | python | en | ['en', 'error', 'th'] | False |
SubscribeRequest.send | (self, sess) |
Send the subscription request.
:type sess: respa_exchange.session.ExchangeSession
:return: Tuple with subscription ID and possible watermark
|
Send the subscription request. | def send(self, sess):
"""
Send the subscription request.
:type sess: respa_exchange.session.ExchangeSession
:return: Tuple with subscription ID and possible watermark
"""
resp = sess.soap(self)
srm = resp.find('*//m:SubscribeResponseMessage', namespaces=NAMESPACE... | [
"def",
"send",
"(",
"self",
",",
"sess",
")",
":",
"resp",
"=",
"sess",
".",
"soap",
"(",
"self",
")",
"srm",
"=",
"resp",
".",
"find",
"(",
"'*//m:SubscribeResponseMessage'",
",",
"namespaces",
"=",
"NAMESPACES",
")",
"response_code_el",
"=",
"srm",
"."... | [
51,
4
] | [
69,
42
] | python | en | ['en', 'error', 'th'] | False |
UnsubscribeRequest.__init__ | (self, principal, subscription_id) |
Initialize the request.
:param principal: Principal email to impersonate
:param subscription_id: Subscription ID to get rid of
|
Initialize the request. | def __init__(self, principal, subscription_id):
"""
Initialize the request.
:param principal: Principal email to impersonate
:param subscription_id: Subscription ID to get rid of
"""
root = M.Unsubscribe(
M.SubscriptionId(subscription_id)
)
su... | [
"def",
"__init__",
"(",
"self",
",",
"principal",
",",
"subscription_id",
")",
":",
"root",
"=",
"M",
".",
"Unsubscribe",
"(",
"M",
".",
"SubscriptionId",
"(",
"subscription_id",
")",
")",
"super",
"(",
"UnsubscribeRequest",
",",
"self",
")",
".",
"__init_... | [
80,
4
] | [
90,
79
] | python | en | ['en', 'error', 'th'] | False |
UnsubscribeRequest.send | (self, sess) |
Send the unsubscription request.
:type sess: respa_exchange.session.ExchangeSession
:return: True if the response class is "Success".
:rtype: bool
|
Send the unsubscription request. | def send(self, sess):
"""
Send the unsubscription request.
:type sess: respa_exchange.session.ExchangeSession
:return: True if the response class is "Success".
:rtype: bool
"""
resp = sess.soap(self)
urm = resp.find('*//m:UnsubscribeResponseMessage', name... | [
"def",
"send",
"(",
"self",
",",
"sess",
")",
":",
"resp",
"=",
"sess",
".",
"soap",
"(",
"self",
")",
"urm",
"=",
"resp",
".",
"find",
"(",
"'*//m:UnsubscribeResponseMessage'",
",",
"namespaces",
"=",
"NAMESPACES",
")",
"return",
"(",
"urm",
"is",
"no... | [
92,
4
] | [
102,
81
] | python | en | ['en', 'error', 'th'] | False |
StreamingEvent.__init__ | (self, subscription_id, type, data, exchange=None, resource=None) |
:param subscription_id: The subscription ID that yielded this Event.
:type subscription_id: str
:param type: The type of this event. TODO: Document better.
:type type: str
:param data: The event data.
:type data: dict[str, str]
:param exchange: The ExchangeSessio... |
:param subscription_id: The subscription ID that yielded this Event.
:type subscription_id: str
:param type: The type of this event. TODO: Document better.
:type type: str
:param data: The event data.
:type data: dict[str, str]
:param exchange: The ExchangeSessio... | def __init__(self, subscription_id, type, data, exchange=None, resource=None):
"""
:param subscription_id: The subscription ID that yielded this Event.
:type subscription_id: str
:param type: The type of this event. TODO: Document better.
:type type: str
:param data: The ... | [
"def",
"__init__",
"(",
"self",
",",
"subscription_id",
",",
"type",
",",
"data",
",",
"exchange",
"=",
"None",
",",
"resource",
"=",
"None",
")",
":",
"self",
".",
"subscription_id",
"=",
"subscription_id",
"self",
".",
"type",
"=",
"type",
"self",
".",... | [
106,
4
] | [
123,
32
] | python | en | ['en', 'error', 'th'] | False |
GetStreamingEventsRequest.__init__ | (self, subscription_ids, timeout_minutes=30) |
Initialize the request.
:param principal: Principal email to impersonate
:param subscription_id: Subscription ID to get rid of
|
Initialize the request. | def __init__(self, subscription_ids, timeout_minutes=30):
"""
Initialize the request.
:param principal: Principal email to impersonate
:param subscription_id: Subscription ID to get rid of
"""
self.timeout_minutes = timeout_minutes
root = M.GetStreamingEvents(
... | [
"def",
"__init__",
"(",
"self",
",",
"subscription_ids",
",",
"timeout_minutes",
"=",
"30",
")",
":",
"self",
".",
"timeout_minutes",
"=",
"timeout_minutes",
"root",
"=",
"M",
".",
"GetStreamingEvents",
"(",
"M",
".",
"SubscriptionIds",
"(",
"*",
"[",
"T",
... | [
140,
4
] | [
152,
61
] | python | en | ['en', 'error', 'th'] | False |
GetStreamingEventsRequest.send | (self, sess) |
Send the event request request [sic].
Note that this is a long-polling operation; returning from this function
may take up to `timeout_minutes` minutes.
:type sess: respa_exchange.session.ExchangeSession
:return: Iterable of StreamingEvents
:rtype: list[respa_exchange.... |
Send the event request request [sic]. | def send(self, sess):
"""
Send the event request request [sic].
Note that this is a long-polling operation; returning from this function
may take up to `timeout_minutes` minutes.
:type sess: respa_exchange.session.ExchangeSession
:return: Iterable of StreamingEvents
... | [
"def",
"send",
"(",
"self",
",",
"sess",
")",
":",
"timeout",
"=",
"(",
"self",
".",
"timeout_minutes",
"+",
"1",
")",
"*",
"60",
"for",
"resp",
"in",
"sess",
".",
"soap_stream",
"(",
"self",
",",
"timeout",
"=",
"timeout",
")",
":",
"events",
"=",... | [
176,
4
] | [
191,
27
] | python | en | ['en', 'error', 'th'] | False |
iter_content | (self, *args, **kwargs) |
Monkey-patched version of Response.iter_content()
|
Monkey-patched version of Response.iter_content()
| def iter_content(self, *args, **kwargs):
"""
Monkey-patched version of Response.iter_content()
"""
yield self._content | [
"def",
"iter_content",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"yield",
"self",
".",
"_content"
] | [
11,
0
] | [
15,
23
] | python | en | ['en', 'error', 'th'] | False |
SoapSeller.__init__ | (self, handler_delegate) |
Construct a SoapSeller using the given delegate object.
:param handler_delegate: The delegate object; see the class docstring.
|
Construct a SoapSeller using the given delegate object. | def __init__(self, handler_delegate):
"""
Construct a SoapSeller using the given delegate object.
:param handler_delegate: The delegate object; see the class docstring.
"""
super(SoapSeller, self).__init__("http://example.com", "CONTOSO\\dummy", "dummy")
self.handler_del... | [
"def",
"__init__",
"(",
"self",
",",
"handler_delegate",
")",
":",
"super",
"(",
"SoapSeller",
",",
"self",
")",
".",
"__init__",
"(",
"\"http://example.com\"",
",",
"\"CONTOSO\\\\dummy\"",
",",
"\"dummy\"",
")",
"self",
".",
"handler_delegate",
"=",
"handler_de... | [
28,
4
] | [
35,
48
] | python | en | ['en', 'error', 'th'] | False |
SoapSeller.send | (self, request, **kwargs) |
Send a requests PreparedRequest. (Override of the super-superclass's method)
:type request: requests.models.PreparedRequest
|
Send a requests PreparedRequest. (Override of the super-superclass's method) | def send(self, request, **kwargs):
"""
Send a requests PreparedRequest. (Override of the super-superclass's method)
:type request: requests.models.PreparedRequest
"""
assert request.method == "POST" # Soap sellers don't do GET
xml = etree.XML(request.body)
for h... | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"request",
".",
"method",
"==",
"\"POST\"",
"# Soap sellers don't do GET",
"xml",
"=",
"etree",
".",
"XML",
"(",
"request",
".",
"body",
")",
"for",
"handler",
"in",... | [
37,
4
] | [
50,
83
] | python | en | ['en', 'error', 'th'] | False |
SoapSeller.wire | (cls, settings, handler_delegate) |
Wire up SoapSeller with the given handler delegate in the given `settings`.
:param settings: Settings monkeypatch object
|
Wire up SoapSeller with the given handler delegate in the given `settings`. | def wire(cls, settings, handler_delegate):
"""
Wire up SoapSeller with the given handler delegate in the given `settings`.
:param settings: Settings monkeypatch object
"""
id = "get_wired_soap_seller_%s" % get_random_string()
def getter(**kwargs):
return cls... | [
"def",
"wire",
"(",
"cls",
",",
"settings",
",",
"handler_delegate",
")",
":",
"id",
"=",
"\"get_wired_soap_seller_%s\"",
"%",
"get_random_string",
"(",
")",
"def",
"getter",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"handler_delegate",
")",
... | [
76,
4
] | [
88,
76
] | python | en | ['en', 'error', 'th'] | False |
make_contrib | (superclass, func=None) |
Returns a suitable contribute_to_class() method for the Field subclass.
If 'func' is passed in, it is the existing contribute_to_class() method on
the subclass and it is called before anything else. It is assumed in this
case that the existing contribute_to_class() calls all the necessary
supercla... |
Returns a suitable contribute_to_class() method for the Field subclass. | def make_contrib(superclass, func=None):
"""
Returns a suitable contribute_to_class() method for the Field subclass.
If 'func' is passed in, it is the existing contribute_to_class() method on
the subclass and it is called before anything else. It is assumed in this
case that the existing contribute... | [
"def",
"make_contrib",
"(",
"superclass",
",",
"func",
"=",
"None",
")",
":",
"def",
"contribute_to_class",
"(",
"self",
",",
"cls",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"func",
":",
"func",
"(",
"self",
",",
"cls",
",",
"name",
",... | [
46,
0
] | [
62,
30
] | 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 |
deepfool_batch | (
sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
nb_classes,
feed=None,
) |
Applies DeepFool to a batch of inputs
:param sess: TF session
:param x: The input placeholder
:param pred: The model's sorted symbolic output of logits, only the top
nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
... |
Applies DeepFool to a batch of inputs
:param sess: TF session
:param x: The input placeholder
:param pred: The model's sorted symbolic output of logits, only the top
nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
... | def deepfool_batch(
sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
nb_classes,
feed=None,
):
"""
Applies DeepFool to a batch of inputs
:param sess: TF session
:param x: The input placeholder
:param pred: The... | [
"def",
"deepfool_batch",
"(",
"sess",
",",
"x",
",",
"pred",
",",
"logits",
",",
"grads",
",",
"X",
",",
"nb_candidate",
",",
"overshoot",
",",
"max_iter",
",",
"clip_min",
",",
"clip_max",
",",
"nb_classes",
",",
"feed",
"=",
"None",
",",
")",
":",
... | [
134,
0
] | [
187,
44
] | python | en | ['en', 'error', 'th'] | False |
deepfool_attack | (
sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
feed=None,
) |
TensorFlow implementation of DeepFool.
Paper link: see https://arxiv.org/pdf/1511.04599.pdf
:param sess: TF session
:param x: The input placeholder
:param predictions: The model's sorted symbolic output of logits, only the
top nb_candidate classes are contained
:param log... |
TensorFlow implementation of DeepFool.
Paper link: see https://arxiv.org/pdf/1511.04599.pdf
:param sess: TF session
:param x: The input placeholder
:param predictions: The model's sorted symbolic output of logits, only the
top nb_candidate classes are contained
:param log... | def deepfool_attack(
sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
feed=None,
):
"""
TensorFlow implementation of DeepFool.
Paper link: see https://arxiv.org/pdf/1511.04599.pdf
:param sess: TF session
... | [
"def",
"deepfool_attack",
"(",
"sess",
",",
"x",
",",
"predictions",
",",
"logits",
",",
"grads",
",",
"sample",
",",
"nb_candidate",
",",
"overshoot",
",",
"max_iter",
",",
"clip_min",
",",
"clip_max",
",",
"feed",
"=",
"None",
",",
")",
":",
"adv_x",
... | [
190,
0
] | [
277,
16
] | python | en | ['en', 'error', 'th'] | False |
DeepFool.__init__ | (self, model, sess, dtypestr="float32", **kwargs) |
Create a DeepFool instance.
|
Create a DeepFool instance.
| def __init__(self, model, sess, dtypestr="float32", **kwargs):
"""
Create a DeepFool instance.
"""
if not isinstance(model, Model):
wrapper_warning_logits()
model = CallableModelWrapper(model, "logits")
super(DeepFool, self).__init__(model, sess, dtypestr... | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"sess",
",",
"dtypestr",
"=",
"\"float32\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"wrapper_warning_logits",
"(",
")",
"model",
"=",
"Calla... | [
34,
4
] | [
50,
9
] | python | en | ['en', 'error', 'th'] | False |
DeepFool.generate | (self, x, **kwargs) |
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
|
Generate symbolic graph for adversarial examples and return. | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
assert (
self.sess is not None
), "Cannot use `generate` when no `sess` was ... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"(",
"self",
".",
"sess",
"is",
"not",
"None",
")",
",",
"\"Cannot use `generate` when no `sess` was provided\"",
"from",
"cleverhans",
".",
"utils_tf",
"import",
"jacobian_... | [
52,
4
] | [
99,
19
] | python | en | ['en', 'error', 'th'] | False |
DeepFool.parse_params | (
self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.0,
clip_max=1.0,
**kwargs
) |
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
... |
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
... | def parse_params(
self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.0,
clip_max=1.0,
**kwargs
):
"""
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate... | [
"def",
"parse_params",
"(",
"self",
",",
"nb_candidate",
"=",
"10",
",",
"overshoot",
"=",
"0.02",
",",
"max_iter",
"=",
"50",
",",
"clip_min",
"=",
"0.0",
",",
"clip_max",
"=",
"1.0",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"nb_candidate",
"... | [
101,
4
] | [
131,
19
] | python | en | ['en', 'error', 'th'] | False |
sensitive_variables | (*variables) |
Indicate which variables used in the decorated function are sensitive so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Accept two forms:
* with specified variable names:
@sensitive_variables('user', 'password', '... |
Indicate which variables used in the decorated function are sensitive so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions. | def sensitive_variables(*variables):
"""
Indicate which variables used in the decorated function are sensitive so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Accept two forms:
* with specified variable names:
... | [
"def",
"sensitive_variables",
"(",
"*",
"variables",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"sensitive_variables_wrapper",
"(",
"*",
"func_args",
",",
"*",
"*",
"func_kwargs",
")",
":",... | [
5,
0
] | [
37,
20
] | python | en | ['en', 'error', 'th'] | False |
sensitive_post_parameters | (*parameters) |
Indicate which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Accept two forms:
* with specified parameters:
@sensitive_post_parameters('password', 'cr... |
Indicate which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions. | def sensitive_post_parameters(*parameters):
"""
Indicate which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Accept two forms:
* with specified parameters:
... | [
"def",
"sensitive_post_parameters",
"(",
"*",
"parameters",
")",
":",
"def",
"decorator",
"(",
"view",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"view",
")",
"def",
"sensitive_post_parameters_wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
... | [
40,
0
] | [
77,
20
] | python | en | ['en', 'error', 'th'] | False |
MigrationGraph.forwards_plan | (self, node) |
Given a node, returns a list of which previous nodes (dependencies)
must be applied, ending with the node itself.
This is the list you would follow if applying the migrations to
a database.
|
Given a node, returns a list of which previous nodes (dependencies)
must be applied, ending with the node itself.
This is the list you would follow if applying the migrations to
a database.
| def forwards_plan(self, node):
"""
Given a node, returns a list of which previous nodes (dependencies)
must be applied, ending with the node itself.
This is the list you would follow if applying the migrations to
a database.
"""
if node not in self.nodes:
... | [
"def",
"forwards_plan",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"not",
"in",
"self",
".",
"nodes",
":",
"raise",
"ValueError",
"(",
"\"Node %r not a valid node\"",
"%",
"(",
"node",
",",
")",
")",
"return",
"self",
".",
"dfs",
"(",
"node",
",... | [
45,
4
] | [
54,
72
] | python | en | ['en', 'error', 'th'] | False |
MigrationGraph.backwards_plan | (self, node) |
Given a node, returns a list of which dependent nodes (dependencies)
must be unapplied, ending with the node itself.
This is the list you would follow if removing the migrations from
a database.
|
Given a node, returns a list of which dependent nodes (dependencies)
must be unapplied, ending with the node itself.
This is the list you would follow if removing the migrations from
a database.
| def backwards_plan(self, node):
"""
Given a node, returns a list of which dependent nodes (dependencies)
must be unapplied, ending with the node itself.
This is the list you would follow if removing the migrations from
a database.
"""
if node not in self.nodes:
... | [
"def",
"backwards_plan",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"not",
"in",
"self",
".",
"nodes",
":",
"raise",
"ValueError",
"(",
"\"Node %r not a valid node\"",
"%",
"(",
"node",
",",
")",
")",
"return",
"self",
".",
"dfs",
"(",
"node",
"... | [
56,
4
] | [
65,
70
] | python | en | ['en', 'error', 'th'] | False |
MigrationGraph.root_nodes | (self, app=None) |
Returns all root nodes - that is, nodes with no dependencies inside
their app. These are the starting point for an app.
|
Returns all root nodes - that is, nodes with no dependencies inside
their app. These are the starting point for an app.
| def root_nodes(self, app=None):
"""
Returns all root nodes - that is, nodes with no dependencies inside
their app. These are the starting point for an app.
"""
roots = set()
for node in self.nodes:
if not any(key[0] == node[0] for key in self.dependencies.get(... | [
"def",
"root_nodes",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"roots",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"not",
"any",
"(",
"key",
"[",
"0",
"]",
"==",
"node",
"[",
"0",
"]",
"for",
"key",
"in"... | [
67,
4
] | [
76,
28
] | python | en | ['en', 'error', 'th'] | False |
MigrationGraph.leaf_nodes | (self, app=None) |
Returns all leaf nodes - that is, nodes with no dependents in their app.
These are the "most current" version of an app's schema.
Having more than one per app is technically an error, but one that
gets handled further up, in the interactive command - it's usually the
result of a... |
Returns all leaf nodes - that is, nodes with no dependents in their app.
These are the "most current" version of an app's schema.
Having more than one per app is technically an error, but one that
gets handled further up, in the interactive command - it's usually the
result of a... | def leaf_nodes(self, app=None):
"""
Returns all leaf nodes - that is, nodes with no dependents in their app.
These are the "most current" version of an app's schema.
Having more than one per app is technically an error, but one that
gets handled further up, in the interactive com... | [
"def",
"leaf_nodes",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"leaves",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"not",
"any",
"(",
"key",
"[",
"0",
"]",
"==",
"node",
"[",
"0",
"]",
"for",
"key",
"in... | [
78,
4
] | [
90,
29
] | python | en | ['en', 'error', 'th'] | False |
MigrationGraph.dfs | (self, start, get_children) |
Dynamic programming based depth first search, for finding dependencies.
|
Dynamic programming based depth first search, for finding dependencies.
| def dfs(self, start, get_children):
"""
Dynamic programming based depth first search, for finding dependencies.
"""
visited = []
visited.append(start)
path = [start]
stack = sorted(get_children(start))
while stack:
node = stack.pop(0)
... | [
"def",
"dfs",
"(",
"self",
",",
"start",
",",
"get_children",
")",
":",
"visited",
"=",
"[",
"]",
"visited",
".",
"append",
"(",
"start",
")",
"path",
"=",
"[",
"start",
"]",
"stack",
"=",
"sorted",
"(",
"get_children",
"(",
"start",
")",
")",
"whi... | [
92,
4
] | [
115,
40
] | python | en | ['en', 'error', 'th'] | False |
MigrationGraph.make_state | (self, nodes=None, at_end=True, real_apps=None) |
Given a migration node or nodes, returns a complete ProjectState for it.
If at_end is False, returns the state before the migration has run.
If nodes is not provided, returns the overall most current project state.
|
Given a migration node or nodes, returns a complete ProjectState for it.
If at_end is False, returns the state before the migration has run.
If nodes is not provided, returns the overall most current project state.
| def make_state(self, nodes=None, at_end=True, real_apps=None):
"""
Given a migration node or nodes, returns a complete ProjectState for it.
If at_end is False, returns the state before the migration has run.
If nodes is not provided, returns the overall most current project state.
... | [
"def",
"make_state",
"(",
"self",
",",
"nodes",
"=",
"None",
",",
"at_end",
"=",
"True",
",",
"real_apps",
"=",
"None",
")",
":",
"if",
"nodes",
"is",
"None",
":",
"nodes",
"=",
"list",
"(",
"self",
".",
"leaf_nodes",
"(",
")",
")",
"if",
"len",
... | [
120,
4
] | [
142,
28
] | python | en | ['en', 'error', 'th'] | False |
_stride_arr | (stride) | Map a stride scalar to the stride array for tf.nn.conv2d. | Map a stride scalar to the stride array for tf.nn.conv2d. | def _stride_arr(stride):
"""Map a stride scalar to the stride array for tf.nn.conv2d."""
return [1, stride, stride, 1] | [
"def",
"_stride_arr",
"(",
"stride",
")",
":",
"return",
"[",
"1",
",",
"stride",
",",
"stride",
",",
"1",
"]"
] | [
106,
0
] | [
108,
33
] | python | en | ['en', 'en', 'en'] | True |
_batch_norm | (name, x) | Batch normalization. | Batch normalization. | def _batch_norm(name, x):
"""Batch normalization."""
with tf.name_scope(name):
return tf.contrib.layers.batch_norm(
inputs=x,
decay=0.9,
center=True,
scale=True,
activation_fn=None,
updates_collections=None,
is_training=... | [
"def",
"_batch_norm",
"(",
"name",
",",
"x",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
":",
"return",
"tf",
".",
"contrib",
".",
"layers",
".",
"batch_norm",
"(",
"inputs",
"=",
"x",
",",
"decay",
"=",
"0.9",
",",
"center",
"=",
... | [
233,
0
] | [
244,
9
] | python | en | ['en', 'co', 'en'] | False |
_residual | (x, in_filter, out_filter, stride, activate_before_residual=False) | Residual unit with 2 sub layers. | Residual unit with 2 sub layers. | def _residual(x, in_filter, out_filter, stride, activate_before_residual=False):
"""Residual unit with 2 sub layers."""
if activate_before_residual:
with tf.variable_scope("shared_activation"):
x = _batch_norm("init_bn", x)
x = _relu(x, 0.1)
orig_x = x
else:
... | [
"def",
"_residual",
"(",
"x",
",",
"in_filter",
",",
"out_filter",
",",
"stride",
",",
"activate_before_residual",
"=",
"False",
")",
":",
"if",
"activate_before_residual",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"shared_activation\"",
")",
":",
"x",
... | [
247,
0
] | [
283,
12
] | python | en | ['en', 'en', 'en'] | True |
_decay | () | L2 weight decay loss. | L2 weight decay loss. | def _decay():
"""L2 weight decay loss."""
costs = []
for var in tf.trainable_variables():
if var.op.name.find("DW") > 0:
costs.append(tf.nn.l2_loss(var))
return tf.add_n(costs) | [
"def",
"_decay",
"(",
")",
":",
"costs",
"=",
"[",
"]",
"for",
"var",
"in",
"tf",
".",
"trainable_variables",
"(",
")",
":",
"if",
"var",
".",
"op",
".",
"name",
".",
"find",
"(",
"\"DW\"",
")",
">",
"0",
":",
"costs",
".",
"append",
"(",
"tf",... | [
286,
0
] | [
292,
26
] | python | en | ['oc', 'en', 'en'] | True |
_conv | (name, x, filter_size, in_filters, out_filters, strides) | Convolution. | Convolution. | def _conv(name, x, filter_size, in_filters, out_filters, strides):
"""Convolution."""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
n = filter_size * filter_size * out_filters
kernel = tf.get_variable(
"DW",
[filter_size, filter_size, in_filters, out_filters],
... | [
"def",
"_conv",
"(",
"name",
",",
"x",
",",
"filter_size",
",",
"in_filters",
",",
"out_filters",
",",
"strides",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"n",
"=",
"filter_size",... | [
295,
0
] | [
305,
63
] | python | en | ['en', 'it', 'en'] | False |
_relu | (x, leakiness=0.0) | Relu, with optional leaky support. | Relu, with optional leaky support. | def _relu(x, leakiness=0.0):
"""Relu, with optional leaky support."""
return tf.where(tf.less(x, 0.0), leakiness * x, x, name="leaky_relu") | [
"def",
"_relu",
"(",
"x",
",",
"leakiness",
"=",
"0.0",
")",
":",
"return",
"tf",
".",
"where",
"(",
"tf",
".",
"less",
"(",
"x",
",",
"0.0",
")",
",",
"leakiness",
"*",
"x",
",",
"x",
",",
"name",
"=",
"\"leaky_relu\"",
")"
] | [
308,
0
] | [
310,
73
] | python | en | ['en', 'en', 'en'] | True |
ResNet.__init__ | (self, layers, input_shape, scope=None) | ResNet constructor.
:param layers: a list of layers in CleverHans format
each with set_input_shape() and fprop() methods.
:param input_shape: 4-tuple describing input shape (e.g None, 32, 32, 3)
:param scope: string name of scope for Variables
This works in two ways.
... | ResNet constructor. | def __init__(self, layers, input_shape, scope=None):
"""ResNet constructor.
:param layers: a list of layers in CleverHans format
each with set_input_shape() and fprop() methods.
:param input_shape: 4-tuple describing input shape (e.g None, 32, 32, 3)
:param scope: string name ... | [
"def",
"__init__",
"(",
"self",
",",
"layers",
",",
"input_shape",
",",
"scope",
"=",
"None",
")",
":",
"super",
"(",
"ResNet",
",",
"self",
")",
".",
"__init__",
"(",
"scope",
",",
"10",
",",
"{",
"}",
",",
"scope",
"is",
"not",
"None",
")",
"if... | [
26,
4
] | [
52,
47
] | python | en | ['en', 'sv', 'en'] | False |
Input.set_input_shape | (self, input_shape) | Build the core model within the graph. | Build the core model within the graph. | def set_input_shape(self, input_shape):
batch_size, rows, cols, input_channels = input_shape
# assert self.mode == 'train' or self.mode == 'eval'
"""Build the core model within the graph."""
input_shape = list(input_shape)
input_shape[0] = 1
dummy_batch = tf.zeros(input_s... | [
"def",
"set_input_shape",
"(",
"self",
",",
"input_shape",
")",
":",
"batch_size",
",",
"rows",
",",
"cols",
",",
"input_channels",
"=",
"input_shape",
"# assert self.mode == 'train' or self.mode == 'eval'",
"input_shape",
"=",
"list",
"(",
"input_shape",
")",
"input_... | [
115,
4
] | [
125,
47
] | python | en | ['en', 'en', 'en'] | True |
migrate_fix_invalid_bot_owner_values | (
apps: StateApps, schema_editor: DatabaseSchemaEditor
) | Fixes UserProfile objects that incorrectly had a bot_owner set | Fixes UserProfile objects that incorrectly had a bot_owner set | def migrate_fix_invalid_bot_owner_values(
apps: StateApps, schema_editor: DatabaseSchemaEditor
) -> None:
"""Fixes UserProfile objects that incorrectly had a bot_owner set"""
UserProfile = apps.get_model("zerver", "UserProfile")
UserProfile.objects.filter(is_bot=False).exclude(bot_owner=None).update(bot... | [
"def",
"migrate_fix_invalid_bot_owner_values",
"(",
"apps",
":",
"StateApps",
",",
"schema_editor",
":",
"DatabaseSchemaEditor",
")",
"->",
"None",
":",
"UserProfile",
"=",
"apps",
".",
"get_model",
"(",
"\"zerver\"",
",",
"\"UserProfile\"",
")",
"UserProfile",
".",... | [
7,
0
] | [
12,
91
] | python | en | ['en', 'en', 'en'] | True |
copy2_fixed | (src, dest) | Wrap shutil.copy2() but map errors copying socket files to
SpecialFileError as expected.
See also https://bugs.python.org/issue37700.
| Wrap shutil.copy2() but map errors copying socket files to
SpecialFileError as expected. | def copy2_fixed(src, dest):
# type: (str, str) -> None
"""Wrap shutil.copy2() but map errors copying socket files to
SpecialFileError as expected.
See also https://bugs.python.org/issue37700.
"""
try:
shutil.copy2(src, dest)
except (OSError, IOError):
for f in [src, dest]:
... | [
"def",
"copy2_fixed",
"(",
"src",
",",
"dest",
")",
":",
"# type: (str, str) -> None",
"try",
":",
"shutil",
".",
"copy2",
"(",
"src",
",",
"dest",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"for",
"f",
"in",
"[",
"src",
",",
"dest",
"]... | [
58,
0
] | [
80,
13
] | python | en | ['en', 'en', 'en'] | True |
adjacent_tmp_file | (path, **kwargs) | Return a file-like object pointing to a tmp file next to path.
The file is created securely and is ensured to be written to disk
after the context reaches its end.
kwargs will be passed to tempfile.NamedTemporaryFile to control
the way the temporary file will be opened.
| Return a file-like object pointing to a tmp file next to path. | def adjacent_tmp_file(path, **kwargs):
# type: (str, **Any) -> Iterator[NamedTemporaryFileResult]
"""Return a file-like object pointing to a tmp file next to path.
The file is created securely and is ensured to be written to disk
after the context reaches its end.
kwargs will be passed to tempfile... | [
"def",
"adjacent_tmp_file",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, **Any) -> Iterator[NamedTemporaryFileResult]",
"with",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
",",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
... | [
89,
0
] | [
111,
42
] | python | en | ['en', 'en', 'en'] | True |
test_writable_dir | (path) | Check if a directory is writable.
Uses os.access() on POSIX, tries creating files on Windows.
| Check if a directory is writable. | def test_writable_dir(path):
# type: (str) -> bool
"""Check if a directory is writable.
Uses os.access() on POSIX, tries creating files on Windows.
"""
# If the directory doesn't exist, find the closest parent that does.
while not os.path.isdir(path):
parent = os.path.dirname(path)
... | [
"def",
"test_writable_dir",
"(",
"path",
")",
":",
"# type: (str) -> bool",
"# If the directory doesn't exist, find the closest parent that does.",
"while",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"parent",
"=",
"os",
".",
"path",
".",
"dirnam... | [
132,
0
] | [
148,
39
] | python | en | ['en', 'en', 'en'] | True |
find_files | (path, pattern) | Returns a list of absolute paths of files beneath path, recursively,
with filenames which match the UNIX-style shell glob pattern. | Returns a list of absolute paths of files beneath path, recursively,
with filenames which match the UNIX-style shell glob pattern. | def find_files(path, pattern):
# type: (str, str) -> List[str]
"""Returns a list of absolute paths of files beneath path, recursively,
with filenames which match the UNIX-style shell glob pattern."""
result = [] # type: List[str]
for root, dirs, files in os.walk(path):
matches = fnmatch.fil... | [
"def",
"find_files",
"(",
"path",
",",
"pattern",
")",
":",
"# type: (str, str) -> List[str]",
"result",
"=",
"[",
"]",
"# type: List[str]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"matches",
"=",
"fnmatch"... | [
185,
0
] | [
193,
17
] | python | en | ['en', 'en', 'en'] | True |
DeferTests.test_defer_proxy | (self) |
Ensure select_related together with only on a proxy model behaves
as expected. See #17876.
|
Ensure select_related together with only on a proxy model behaves
as expected. See #17876.
| def test_defer_proxy(self):
"""
Ensure select_related together with only on a proxy model behaves
as expected. See #17876.
"""
related = Secondary.objects.create(first='x1', second='x2')
ChildProxy.objects.create(name='p1', value='xx', related=related)
children = ... | [
"def",
"test_defer_proxy",
"(",
"self",
")",
":",
"related",
"=",
"Secondary",
".",
"objects",
".",
"create",
"(",
"first",
"=",
"'x1'",
",",
"second",
"=",
"'x2'",
")",
"ChildProxy",
".",
"objects",
".",
"create",
"(",
"name",
"=",
"'p1'",
",",
"value... | [
157,
4
] | [
169,
43
] | python | en | ['en', 'error', 'th'] | False |
DeferTests.test_defer_inheritance_pk_chaining | (self) |
When an inherited model is fetched from the DB, its PK is also fetched.
When getting the PK of the parent model it is useful to use the already
fetched parent model PK if it happens to be available. Tests that this
is done.
|
When an inherited model is fetched from the DB, its PK is also fetched.
When getting the PK of the parent model it is useful to use the already
fetched parent model PK if it happens to be available. Tests that this
is done.
| def test_defer_inheritance_pk_chaining(self):
"""
When an inherited model is fetched from the DB, its PK is also fetched.
When getting the PK of the parent model it is useful to use the already
fetched parent model PK if it happens to be available. Tests that this
is done.
... | [
"def",
"test_defer_inheritance_pk_chaining",
"(",
"self",
")",
":",
"s1",
"=",
"Secondary",
".",
"objects",
".",
"create",
"(",
"first",
"=",
"\"x1\"",
",",
"second",
"=",
"\"y1\"",
")",
"bc",
"=",
"BigChild",
".",
"objects",
".",
"create",
"(",
"name",
... | [
171,
4
] | [
184,
56
] | python | en | ['en', 'error', 'th'] | False |
popen_wrapper | (args, stdout_encoding='utf-8') |
Friendly wrapper around Popen.
Return stdout output, stderr output, and OS status code.
|
Friendly wrapper around Popen. | def popen_wrapper(args, stdout_encoding='utf-8'):
"""
Friendly wrapper around Popen.
Return stdout output, stderr output, and OS status code.
"""
try:
p = run(args, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt')
except OSError as err:
raise CommandError('Error executing %s... | [
"def",
"popen_wrapper",
"(",
"args",
",",
"stdout_encoding",
"=",
"'utf-8'",
")",
":",
"try",
":",
"p",
"=",
"run",
"(",
"args",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"close_fds",
"=",
"os",
".",
"name",
"!=",
"'nt'",
")",
"e... | [
12,
0
] | [
26,
5
] | python | en | ['en', 'error', 'th'] | False |
handle_extensions | (extensions) |
Organize multiple extensions that are separated with commas or passed by
using --extension/-e multiple times.
For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
would result in an extension list: ['.js', '.txt', '.xhtml']
>>> handle_extensions(['.html', 'html,js,py,py,py,.py',... |
Organize multiple extensions that are separated with commas or passed by
using --extension/-e multiple times. | def handle_extensions(extensions):
"""
Organize multiple extensions that are separated with commas or passed by
using --extension/-e multiple times.
For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
would result in an extension list: ['.js', '.txt', '.xhtml']
>>> handle_ex... | [
"def",
"handle_extensions",
"(",
"extensions",
")",
":",
"ext_list",
"=",
"[",
"]",
"for",
"ext",
"in",
"extensions",
":",
"ext_list",
".",
"extend",
"(",
"ext",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
")",
"for",
... | [
29,
0
] | [
48,
24
] | python | en | ['en', 'error', 'th'] | False |
get_random_secret_key | () |
Return a 50 character random string usable as a SECRET_KEY setting value.
|
Return a 50 character random string usable as a SECRET_KEY setting value.
| def get_random_secret_key():
"""
Return a 50 character random string usable as a SECRET_KEY setting value.
"""
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
return get_random_string(50, chars) | [
"def",
"get_random_secret_key",
"(",
")",
":",
"chars",
"=",
"'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'",
"return",
"get_random_string",
"(",
"50",
",",
"chars",
")"
] | [
76,
0
] | [
81,
39
] | python | en | ['en', 'error', 'th'] | False |
parse_apps_and_model_labels | (labels) |
Parse a list of "app_label.ModelName" or "app_label" strings into actual
objects and return a two-element tuple:
(set of model classes, set of app_configs).
Raise a CommandError if some specified models or apps don't exist.
|
Parse a list of "app_label.ModelName" or "app_label" strings into actual
objects and return a two-element tuple:
(set of model classes, set of app_configs).
Raise a CommandError if some specified models or apps don't exist.
| def parse_apps_and_model_labels(labels):
"""
Parse a list of "app_label.ModelName" or "app_label" strings into actual
objects and return a two-element tuple:
(set of model classes, set of app_configs).
Raise a CommandError if some specified models or apps don't exist.
"""
apps = set()
... | [
"def",
"parse_apps_and_model_labels",
"(",
"labels",
")",
":",
"apps",
"=",
"set",
"(",
")",
"models",
"=",
"set",
"(",
")",
"for",
"label",
"in",
"labels",
":",
"if",
"'.'",
"in",
"label",
":",
"try",
":",
"model",
"=",
"installed_apps",
".",
"get_mod... | [
84,
0
] | [
108,
23
] | python | en | ['en', 'error', 'th'] | False |
get_command_line_option | (argv, option) |
Return the value of a command line option (which should include leading
dashes, e.g. '--testrunner') from an argument list. Return None if the
option wasn't passed or if the argument list couldn't be parsed.
|
Return the value of a command line option (which should include leading
dashes, e.g. '--testrunner') from an argument list. Return None if the
option wasn't passed or if the argument list couldn't be parsed.
| def get_command_line_option(argv, option):
"""
Return the value of a command line option (which should include leading
dashes, e.g. '--testrunner') from an argument list. Return None if the
option wasn't passed or if the argument list couldn't be parsed.
"""
parser = CommandParser(add_help=False... | [
"def",
"get_command_line_option",
"(",
"argv",
",",
"option",
")",
":",
"parser",
"=",
"CommandParser",
"(",
"add_help",
"=",
"False",
",",
"allow_abbrev",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"option",
",",
"dest",
"=",
"'value'",
")",
"... | [
111,
0
] | [
124,
28
] | python | en | ['en', 'error', 'th'] | False |
normalize_path_patterns | (patterns) | Normalize an iterable of glob style patterns based on OS. | Normalize an iterable of glob style patterns based on OS. | def normalize_path_patterns(patterns):
"""Normalize an iterable of glob style patterns based on OS."""
patterns = [os.path.normcase(p) for p in patterns]
dir_suffixes = {'%s*' % path_sep for path_sep in {'/', os.sep}}
norm_patterns = []
for pattern in patterns:
for dir_suffix in dir_suffixes... | [
"def",
"normalize_path_patterns",
"(",
"patterns",
")",
":",
"patterns",
"=",
"[",
"os",
".",
"path",
".",
"normcase",
"(",
"p",
")",
"for",
"p",
"in",
"patterns",
"]",
"dir_suffixes",
"=",
"{",
"'%s*'",
"%",
"path_sep",
"for",
"path_sep",
"in",
"{",
"... | [
127,
0
] | [
139,
24
] | python | en | ['en', 'en', 'en'] | True |
is_ignored_path | (path, ignore_patterns) |
Check if the given path should be ignored or not based on matching
one of the glob style `ignore_patterns`.
|
Check if the given path should be ignored or not based on matching
one of the glob style `ignore_patterns`.
| def is_ignored_path(path, ignore_patterns):
"""
Check if the given path should be ignored or not based on matching
one of the glob style `ignore_patterns`.
"""
path = Path(path)
def ignore(pattern):
return fnmatch.fnmatchcase(path.name, pattern) or fnmatch.fnmatchcase(str(path), pattern... | [
"def",
"is_ignored_path",
"(",
"path",
",",
"ignore_patterns",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"def",
"ignore",
"(",
"pattern",
")",
":",
"return",
"fnmatch",
".",
"fnmatchcase",
"(",
"path",
".",
"name",
",",
"pattern",
")",
"or",
"fn... | [
142,
0
] | [
152,
87
] | python | en | ['en', 'error', 'th'] | False |
dictfetchall | (cursor: connection.cursor) | Returns all rows from a cursor as a dict | Returns all rows from a cursor as a dict | def dictfetchall(cursor: connection.cursor) -> List[Dict[str, Any]]:
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [dict(zip((col[0] for col in desc), row)) for row in cursor.fetchall()] | [
"def",
"dictfetchall",
"(",
"cursor",
":",
"connection",
".",
"cursor",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"desc",
"=",
"cursor",
".",
"description",
"return",
"[",
"dict",
"(",
"zip",
"(",
"(",
"col",
"[",
"0",
... | [
576,
0
] | [
579,
82
] | python | en | ['en', 'en', 'en'] | True |
BaseStorage._loaded_messages | (self) |
Returns a list of loaded messages, retrieving them first if they have
not been loaded yet.
|
Returns a list of loaded messages, retrieving them first if they have
not been loaded yet.
| def _loaded_messages(self):
"""
Returns a list of loaded messages, retrieving them first if they have
not been loaded yet.
"""
if not hasattr(self, '_loaded_data'):
messages, all_retrieved = self._get()
self._loaded_data = messages or []
return sel... | [
"def",
"_loaded_messages",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_loaded_data'",
")",
":",
"messages",
",",
"all_retrieved",
"=",
"self",
".",
"_get",
"(",
")",
"self",
".",
"_loaded_data",
"=",
"messages",
"or",
"[",
"]",
... | [
86,
4
] | [
94,
32
] | 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.