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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
text_format_value | (field, value) | Format the value as protobuf text format
Args:
field: a FieldDescriptor that describes the field
value: the value stored in the field
Returns:
value in protobuf text format
| Format the value as protobuf text format | def text_format_value(field, value):
"""Format the value as protobuf text format
Args:
field: a FieldDescriptor that describes the field
value: the value stored in the field
Returns:
value in protobuf text format
"""
out = io.StringIO()
text_format.PrintFieldValue(field... | [
"def",
"text_format_value",
"(",
"field",
",",
"value",
")",
":",
"out",
"=",
"io",
".",
"StringIO",
"(",
")",
"text_format",
".",
"PrintFieldValue",
"(",
"field",
",",
"value",
",",
"out",
")",
"return",
"out",
".",
"getvalue",
"(",
")"
] | [
502,
0
] | [
514,
25
] | python | en | ['en', 'en', 'en'] | True |
format_options | (options) | Format *Options (e.g.
MessageOptions, FieldOptions) message.
Args:
options: A *Options (e.g. MessageOptions, FieldOptions) message.
Returns:
Formatted options as a string.
| Format *Options (e.g. | def format_options(options):
"""Format *Options (e.g.
MessageOptions, FieldOptions) message.
Args:
options: A *Options (e.g. MessageOptions, FieldOptions) message.
Returns:
Formatted options as a string.
"""
formatted_options = []
for option_descriptor, option_value in so... | [
"def",
"format_options",
"(",
"options",
")",
":",
"formatted_options",
"=",
"[",
"]",
"for",
"option_descriptor",
",",
"option_value",
"in",
"sorted",
"(",
"options",
".",
"ListFields",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
... | [
517,
0
] | [
551,
13
] | python | en | ['en', 'bg', 'en'] | True |
format_reserved | (enum_or_msg_proto) | Format reserved values/names in a [Enum]DescriptorProto.
Args:
enum_or_msg_proto: [Enum]DescriptorProto message.
Returns:
Formatted enum_or_msg_proto as a string.
| Format reserved values/names in a [Enum]DescriptorProto. | def format_reserved(enum_or_msg_proto):
"""Format reserved values/names in a [Enum]DescriptorProto.
Args:
enum_or_msg_proto: [Enum]DescriptorProto message.
Returns:
Formatted enum_or_msg_proto as a string.
"""
rrs = copy.deepcopy(enum_or_msg_proto.reserved_range)
# Fixups for s... | [
"def",
"format_reserved",
"(",
"enum_or_msg_proto",
")",
":",
"rrs",
"=",
"copy",
".",
"deepcopy",
"(",
"enum_or_msg_proto",
".",
"reserved_range",
")",
"# Fixups for singletons that don't seem to always have [inclusive, exclusive)",
"# format when parsed by protoc.",
"for",
"r... | [
554,
0
] | [
575,
26
] | python | en | ['en', 'ca', 'en'] | True |
ProtoFormatVisitor._add_deprecation_version | (self, field_or_evalue, deprecation_tag, disallowed_tag) | Adds a deprecation version annotation if needed to the given field or enum value.
The annotation is added if all the following hold:
- The field or enum value are marked as deprecated.
- The proto is not frozen.
- The field or enum value are not marked as hidden.
- The field or e... | Adds a deprecation version annotation if needed to the given field or enum value.
The annotation is added if all the following hold:
- The field or enum value are marked as deprecated.
- The proto is not frozen.
- The field or enum value are not marked as hidden.
- The field or e... | def _add_deprecation_version(self, field_or_evalue, deprecation_tag, disallowed_tag):
"""Adds a deprecation version annotation if needed to the given field or enum value.
The annotation is added if all the following hold:
- The field or enum value are marked as deprecated.
- The proto is... | [
"def",
"_add_deprecation_version",
"(",
"self",
",",
"field_or_evalue",
",",
"deprecation_tag",
",",
"disallowed_tag",
")",
":",
"if",
"field_or_evalue",
".",
"options",
".",
"deprecated",
"and",
"not",
"self",
".",
"_frozen_proto",
"and",
"not",
"protoxform_options... | [
591,
4
] | [
626,
84
] | python | en | ['en', 'en', 'en'] | True |
entry_page | () | Returns the entry page to browser. | Returns the entry page to browser. | def entry_page() -> 'html':
"""Returns the entry page to browser."""
return render_template('entry.html',
the_title='Welcome to search4letters on the web!') | [
"def",
"entry_page",
"(",
")",
"->",
"'html'",
":",
"return",
"render_template",
"(",
"'entry.html'",
",",
"the_title",
"=",
"'Welcome to search4letters on the web!'",
")"
] | [
8,
0
] | [
11,
77
] | python | en | ['en', 'en', 'en'] | True |
search4 | () | Returns the results of a call to 'search4letters' to the browser. | Returns the results of a call to 'search4letters' to the browser. | def search4() -> 'html':
"""Returns the results of a call to 'search4letters' to the browser."""
phrase = request.form['phrase']
letters = request.form['letters']
results = str(search4letters(phrase, letters))
return render_template('results.html',
the_title='Here are your... | [
"def",
"search4",
"(",
")",
"->",
"'html'",
":",
"phrase",
"=",
"request",
".",
"form",
"[",
"'phrase'",
"]",
"letters",
"=",
"request",
".",
"form",
"[",
"'letters'",
"]",
"results",
"=",
"str",
"(",
"search4letters",
"(",
"phrase",
",",
"letters",
")... | [
14,
0
] | [
23,
47
] | python | en | ['en', 'en', 'en'] | True |
search4json | () | Returns the results of a call to 'search4letters' as json. | Returns the results of a call to 'search4letters' as json. | def search4json() -> 'json':
"""Returns the results of a call to 'search4letters' as json."""
phrase = request.form['phrase']
letters = request.form['letters']
results = str(search4letters(phrase, letters))
return jsonify(the_phrase=phrase,
the_letters=letters,
... | [
"def",
"search4json",
"(",
")",
"->",
"'json'",
":",
"phrase",
"=",
"request",
".",
"form",
"[",
"'phrase'",
"]",
"letters",
"=",
"request",
".",
"form",
"[",
"'letters'",
"]",
"results",
"=",
"str",
"(",
"search4letters",
"(",
"phrase",
",",
"letters",
... | [
26,
0
] | [
33,
38
] | python | en | ['en', 'en', 'en'] | True |
test_finetuning_with_resume_from_checkpoint | (tmpdir) |
This test validates that generated ModelCheckpoint is pointing to the right best_model_path during test
|
This test validates that generated ModelCheckpoint is pointing to the right best_model_path during test
| def test_finetuning_with_resume_from_checkpoint(tmpdir):
"""
This test validates that generated ModelCheckpoint is pointing to the right best_model_path during test
"""
seed_everything(3)
checkpoint_callback = ModelCheckpoint(monitor='val_loss', dirpath=tmpdir, filename="{epoch:02d}", save_top_k=-... | [
"def",
"test_finetuning_with_resume_from_checkpoint",
"(",
"tmpdir",
")",
":",
"seed_everything",
"(",
"3",
")",
"checkpoint_callback",
"=",
"ModelCheckpoint",
"(",
"monitor",
"=",
"'val_loss'",
",",
"dirpath",
"=",
"tmpdir",
",",
"filename",
"=",
"\"{epoch:02d}\"",
... | [
24,
0
] | [
85,
56
] | python | en | ['en', 'error', 'th'] | False |
NeptuneLogger.experiment | (self) | r"""
Actual Neptune object. To use neptune features in your
:class:`~pytorch_lightning.core.lightning.LightningModule` do the following.
Example::
self.logger.experiment.some_neptune_function()
| r"""
Actual Neptune object. To use neptune features in your
:class:`~pytorch_lightning.core.lightning.LightningModule` do the following. | def experiment(self) -> Experiment:
r"""
Actual Neptune object. To use neptune features in your
:class:`~pytorch_lightning.core.lightning.LightningModule` do the following.
Example::
self.logger.experiment.some_neptune_function()
"""
# Note that even thoug... | [
"def",
"experiment",
"(",
"self",
")",
"->",
"Experiment",
":",
"# Note that even though we initialize self._experiment in __init__,",
"# it may still end up being None after being pickled and un-pickled",
"if",
"self",
".",
"_experiment",
"is",
"None",
":",
"self",
".",
"_expe... | [
218,
4
] | [
234,
31
] | python | cy | ['en', 'cy', 'hi'] | False |
NeptuneLogger.log_metrics | (self, metrics: Dict[str, Union[torch.Tensor, float]], step: Optional[int] = None) |
Log metrics (numeric values) in Neptune experiments.
Args:
metrics: Dictionary with metric names as keys and measured quantities as values
step: Step number at which the metrics should be recorded, currently ignored
|
Log metrics (numeric values) in Neptune experiments. | def log_metrics(self, metrics: Dict[str, Union[torch.Tensor, float]], step: Optional[int] = None) -> None:
"""
Log metrics (numeric values) in Neptune experiments.
Args:
metrics: Dictionary with metric names as keys and measured quantities as values
step: Step number at ... | [
"def",
"log_metrics",
"(",
"self",
",",
"metrics",
":",
"Dict",
"[",
"str",
",",
"Union",
"[",
"torch",
".",
"Tensor",
",",
"float",
"]",
"]",
",",
"step",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"assert",
"rank_zero_... | [
244,
4
] | [
258,
37
] | python | en | ['en', 'error', 'th'] | False |
NeptuneLogger.log_metric | (
self, metric_name: str, metric_value: Union[torch.Tensor, float, str], step: Optional[int] = None
) |
Log metrics (numeric values) in Neptune experiments.
Args:
metric_name: The name of log, i.e. mse, loss, accuracy.
metric_value: The value of the log (data-point).
step: Step number at which the metrics should be recorded, must be strictly increasing
|
Log metrics (numeric values) in Neptune experiments. | def log_metric(
self, metric_name: str, metric_value: Union[torch.Tensor, float, str], step: Optional[int] = None
) -> None:
"""
Log metrics (numeric values) in Neptune experiments.
Args:
metric_name: The name of log, i.e. mse, loss, accuracy.
metric_value: T... | [
"def",
"log_metric",
"(",
"self",
",",
"metric_name",
":",
"str",
",",
"metric_value",
":",
"Union",
"[",
"torch",
".",
"Tensor",
",",
"float",
",",
"str",
"]",
",",
"step",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if... | [
286,
4
] | [
303,
75
] | python | en | ['en', 'error', 'th'] | False |
NeptuneLogger.log_text | (self, log_name: str, text: str, step: Optional[int] = None) |
Log text data in Neptune experiments.
Args:
log_name: The name of log, i.e. mse, my_text_data, timing_info.
text: The value of the log (data-point).
step: Step number at which the metrics should be recorded, must be strictly increasing
|
Log text data in Neptune experiments. | def log_text(self, log_name: str, text: str, step: Optional[int] = None) -> None:
"""
Log text data in Neptune experiments.
Args:
log_name: The name of log, i.e. mse, my_text_data, timing_info.
text: The value of the log (data-point).
step: Step number at whi... | [
"def",
"log_text",
"(",
"self",
",",
"log_name",
":",
"str",
",",
"text",
":",
"str",
",",
"step",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"experiment",
".",
"log_text",
"(",
"log_name",
",",
"text",
",",... | [
306,
4
] | [
315,
59
] | python | en | ['en', 'error', 'th'] | False |
NeptuneLogger.log_image | (self, log_name: str, image: Union[str, Any], step: Optional[int] = None) |
Log image data in Neptune experiment
Args:
log_name: The name of log, i.e. bboxes, visualisations, sample_images.
image: The value of the log (data-point).
Can be one of the following types: PIL image, `matplotlib.figure.Figure`,
path to image fi... |
Log image data in Neptune experiment | def log_image(self, log_name: str, image: Union[str, Any], step: Optional[int] = None) -> None:
"""
Log image data in Neptune experiment
Args:
log_name: The name of log, i.e. bboxes, visualisations, sample_images.
image: The value of the log (data-point).
... | [
"def",
"log_image",
"(",
"self",
",",
"log_name",
":",
"str",
",",
"image",
":",
"Union",
"[",
"str",
",",
"Any",
"]",
",",
"step",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"step",
"is",
"None",
":",
"self",
... | [
318,
4
] | [
332,
64
] | python | en | ['en', 'error', 'th'] | False |
NeptuneLogger.log_artifact | (self, artifact: str, destination: Optional[str] = None) | Save an artifact (file) in Neptune experiment storage.
Args:
artifact: A path to the file in local filesystem.
destination: Optional. Default is ``None``. A destination path.
If ``None`` is passed, an artifact file name will be used.
| Save an artifact (file) in Neptune experiment storage. | def log_artifact(self, artifact: str, destination: Optional[str] = None) -> None:
"""Save an artifact (file) in Neptune experiment storage.
Args:
artifact: A path to the file in local filesystem.
destination: Optional. Default is ``None``. A destination path.
If ... | [
"def",
"log_artifact",
"(",
"self",
",",
"artifact",
":",
"str",
",",
"destination",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"experiment",
".",
"log_artifact",
"(",
"artifact",
",",
"destination",
")"
] | [
335,
4
] | [
343,
59
] | python | en | ['en', 'en', 'en'] | True |
NeptuneLogger.set_property | (self, key: str, value: Any) |
Set key-value pair as Neptune experiment property.
Args:
key: Property key.
value: New value of a property.
|
Set key-value pair as Neptune experiment property. | def set_property(self, key: str, value: Any) -> None:
"""
Set key-value pair as Neptune experiment property.
Args:
key: Property key.
value: New value of a property.
"""
self.experiment.set_property(key, value) | [
"def",
"set_property",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"experiment",
".",
"set_property",
"(",
"key",
",",
"value",
")"
] | [
346,
4
] | [
354,
48
] | python | en | ['en', 'error', 'th'] | False |
NeptuneLogger.append_tags | (self, tags: Union[str, Iterable[str]]) |
Appends tags to the neptune experiment.
Args:
tags: Tags to add to the current experiment. If str is passed, a single tag is added.
If multiple - comma separated - str are passed, all of them are added as tags.
If list of str is passed, all elements of the l... |
Appends tags to the neptune experiment. | def append_tags(self, tags: Union[str, Iterable[str]]) -> None:
"""
Appends tags to the neptune experiment.
Args:
tags: Tags to add to the current experiment. If str is passed, a single tag is added.
If multiple - comma separated - str are passed, all of them are add... | [
"def",
"append_tags",
"(",
"self",
",",
"tags",
":",
"Union",
"[",
"str",
",",
"Iterable",
"[",
"str",
"]",
"]",
")",
"->",
"None",
":",
"if",
"str",
"(",
"tags",
")",
"==",
"tags",
":",
"tags",
"=",
"[",
"tags",
"]",
"# make it as an iterable is if ... | [
357,
4
] | [
368,
42
] | python | en | ['en', 'error', 'th'] | False |
profile_edit | (request) |
view function to render profile
|
view function to render profile | def profile_edit(request):
"""
view function to render profile
"""
form = EditProfileForm()
current_user = request.user
if request.method == 'POST':
form = EditProfileForm(request.POST, request.FILES, instance=current_user.profile)
if form.is_valid():
form.save()
... | [
"def",
"profile_edit",
"(",
"request",
")",
":",
"form",
"=",
"EditProfileForm",
"(",
")",
"current_user",
"=",
"request",
".",
"user",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"EditProfileForm",
"(",
"request",
".",
"POST",
",",
... | [
16,
0
] | [
30,
63
] | python | en | ['en', 'error', 'th'] | False |
updatebiz | (request, id) |
create business function
:param request:
:return:
|
create business function
:param request:
:return:
| def updatebiz(request, id):
"""
create business function
:param request:
:return:
"""
bsns = Business.objects.get(id=id)
if request.method == 'POST':
form = CreatebizForm(request.POST, request.FILES, instance=bsns)
if form.is_valid():
b = form.save(commit=False)
... | [
"def",
"updatebiz",
"(",
"request",
",",
"id",
")",
":",
"bsns",
"=",
"Business",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"id",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"CreatebizForm",
"(",
"request",
".",
"POST",
... | [
32,
0
] | [
49,
58
] | python | en | ['en', 'error', 'th'] | False |
profile | (request) |
view function to render profile
|
view function to render profile | def profile(request):
"""
view function to render profile
"""
current_user = request.user
profile = Profile.objects.get(user =current_user)
bsns = Business.objects.filter(user=current_user)
post = Post.objects.filter(user= current_user)
return render(request, 'profile.html', {'profile':... | [
"def",
"profile",
"(",
"request",
")",
":",
"current_user",
"=",
"request",
".",
"user",
"profile",
"=",
"Profile",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"current_user",
")",
"bsns",
"=",
"Business",
".",
"objects",
".",
"filter",
"(",
"user",
... | [
54,
0
] | [
63,
90
] | python | en | ['en', 'error', 'th'] | False |
create_hood | (request) |
view function to create hood
:param request:
:return:
|
view function to create hood
:param request:
:return:
| def create_hood(request):
"""
view function to create hood
:param request:
:return:
"""
if request.method == 'POST':
form = NeighbourhoodForm(request.POST, request.FILES)
if form.is_valid():
n = form.save(commit=False)
n.admin = request.user.profile
... | [
"def",
"create_hood",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"NeighbourhoodForm",
"(",
"request",
".",
"POST",
",",
"request",
".",
"FILES",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"n",
... | [
79,
0
] | [
95,
63
] | python | en | ['en', 'error', 'th'] | False |
create_post | (request) |
view function to create posts
:param request:
:return:
|
view function to create posts
:param request:
:return:
| def create_post(request):
"""
view function to create posts
:param request:
:return:
"""
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
p =form.save(commit=False)
p.user = request.user.profile
p.neighbourhood = r... | [
"def",
"create_post",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"PostForm",
"(",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"p",
"=",
"form",
".",
"save",
"(",
"commi... | [
99,
0
] | [
115,
52
] | python | en | ['en', 'error', 'th'] | False |
createbiz | (request) |
create business function
:param request:
:return:
|
create business function
:param request:
:return:
| def createbiz(request):
"""
create business function
:param request:
:return:
"""
if request.method == 'POST':
form = CreatebizForm(request.POST, request.FILES)
if form.is_valid():
b = form.save(commit=False)
b.user = request.user.profile
b.nei... | [
"def",
"createbiz",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"CreatebizForm",
"(",
"request",
".",
"POST",
",",
"request",
".",
"FILES",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"b",
"=",
... | [
119,
0
] | [
135,
58
] | python | en | ['en', 'error', 'th'] | False |
neighbourhood | (request, neighbourhood_id) |
view function to render neighbourhood
|
view function to render neighbourhood | def neighbourhood(request, neighbourhood_id):
"""
view function to render neighbourhood
"""
comments = Comment.objects.all()
form = CommentForm()
hood = Neighbourhood.find_neighbourhood(neighbourhood_id)
bsns = Business.objects.filter(neighbourhood=request.user.profile.neighbourhood)
po... | [
"def",
"neighbourhood",
"(",
"request",
",",
"neighbourhood_id",
")",
":",
"comments",
"=",
"Comment",
".",
"objects",
".",
"all",
"(",
")",
"form",
"=",
"CommentForm",
"(",
")",
"hood",
"=",
"Neighbourhood",
".",
"find_neighbourhood",
"(",
"neighbourhood_id",... | [
138,
0
] | [
149,
60
] | python | en | ['en', 'error', 'th'] | False |
ConfigureOptimizersPool.configure_optimizers | (self) |
return whatever optimizers we want here.
:return: list of optimizers
|
return whatever optimizers we want here.
:return: list of optimizers
| def configure_optimizers(self):
"""
return whatever optimizers we want here.
:return: list of optimizers
"""
optimizer = optim.Adam(self.parameters(), lr=self.learning_rate)
return optimizer | [
"def",
"configure_optimizers",
"(",
"self",
")",
":",
"optimizer",
"=",
"optim",
".",
"Adam",
"(",
"self",
".",
"parameters",
"(",
")",
",",
"lr",
"=",
"self",
".",
"learning_rate",
")",
"return",
"optimizer"
] | [
20,
4
] | [
26,
24
] | python | en | ['en', 'error', 'th'] | False |
ConfigureOptimizersPool.configure_optimizers__lbfgs | (self) |
return whatever optimizers we want here.
:return: list of optimizers
|
return whatever optimizers we want here.
:return: list of optimizers
| def configure_optimizers__lbfgs(self):
"""
return whatever optimizers we want here.
:return: list of optimizers
"""
optimizer = optim.LBFGS(self.parameters(), lr=self.learning_rate)
return optimizer | [
"def",
"configure_optimizers__lbfgs",
"(",
"self",
")",
":",
"optimizer",
"=",
"optim",
".",
"LBFGS",
"(",
"self",
".",
"parameters",
"(",
")",
",",
"lr",
"=",
"self",
".",
"learning_rate",
")",
"return",
"optimizer"
] | [
31,
4
] | [
37,
24
] | python | en | ['en', 'error', 'th'] | False |
_unpack_field | (dtype, offset, title=None) |
Helper function to normalize the items in dtype.fields.
Call as:
dtype, offset, title = _unpack_field(*dtype.fields[name])
|
Helper function to normalize the items in dtype.fields. | def _unpack_field(dtype, offset, title=None):
"""
Helper function to normalize the items in dtype.fields.
Call as:
dtype, offset, title = _unpack_field(*dtype.fields[name])
"""
return dtype, offset, title | [
"def",
"_unpack_field",
"(",
"dtype",
",",
"offset",
",",
"title",
"=",
"None",
")",
":",
"return",
"dtype",
",",
"offset",
",",
"title"
] | [
63,
0
] | [
71,
31
] | python | en | ['en', 'error', 'th'] | False |
_construction_repr | (dtype, include_align=False, short=False) |
Creates a string repr of the dtype, excluding the 'dtype()' part
surrounding the object. This object may be a string, a list, or
a dict depending on the nature of the dtype. This
is the object passed as the first parameter to the dtype
constructor, and if no additional constructor parameters are
... |
Creates a string repr of the dtype, excluding the 'dtype()' part
surrounding the object. This object may be a string, a list, or
a dict depending on the nature of the dtype. This
is the object passed as the first parameter to the dtype
constructor, and if no additional constructor parameters are
... | def _construction_repr(dtype, include_align=False, short=False):
"""
Creates a string repr of the dtype, excluding the 'dtype()' part
surrounding the object. This object may be a string, a list, or
a dict depending on the nature of the dtype. This
is the object passed as the first parameter to the d... | [
"def",
"_construction_repr",
"(",
"dtype",
",",
"include_align",
"=",
"False",
",",
"short",
"=",
"False",
")",
":",
"if",
"dtype",
".",
"fields",
"is",
"not",
"None",
":",
"return",
"_struct_str",
"(",
"dtype",
",",
"include_align",
"=",
"include_align",
... | [
79,
0
] | [
111,
46
] | python | en | ['en', 'error', 'th'] | False |
_byte_order_str | (dtype) | Normalize byteorder to '<' or '>' | Normalize byteorder to '<' or '>' | def _byte_order_str(dtype):
""" Normalize byteorder to '<' or '>' """
# hack to obtain the native and swapped byte order characters
swapped = np.dtype(int).newbyteorder('s')
native = swapped.newbyteorder('s')
byteorder = dtype.byteorder
if byteorder == '=':
return native.byteorder
i... | [
"def",
"_byte_order_str",
"(",
"dtype",
")",
":",
"# hack to obtain the native and swapped byte order characters",
"swapped",
"=",
"np",
".",
"dtype",
"(",
"int",
")",
".",
"newbyteorder",
"(",
"'s'",
")",
"native",
"=",
"swapped",
".",
"newbyteorder",
"(",
"'s'",... | [
171,
0
] | [
186,
24
] | python | en | ['en', 'en', 'en'] | True |
_is_packed | (dtype) |
Checks whether the structured data type in 'dtype'
has a simple layout, where all the fields are in order,
and follow each other with no alignment padding.
When this returns true, the dtype can be reconstructed
from a list of the field names and dtypes with no additional
dtype parameters.
... |
Checks whether the structured data type in 'dtype'
has a simple layout, where all the fields are in order,
and follow each other with no alignment padding. | def _is_packed(dtype):
"""
Checks whether the structured data type in 'dtype'
has a simple layout, where all the fields are in order,
and follow each other with no alignment padding.
When this returns true, the dtype can be reconstructed
from a list of the field names and dtypes with no additio... | [
"def",
"_is_packed",
"(",
"dtype",
")",
":",
"total_offset",
"=",
"0",
"for",
"name",
"in",
"dtype",
".",
"names",
":",
"fld_dtype",
",",
"fld_offset",
",",
"title",
"=",
"_unpack_field",
"(",
"*",
"dtype",
".",
"fields",
"[",
"name",
"]",
")",
"if",
... | [
244,
0
] | [
264,
15
] | python | en | ['en', 'error', 'th'] | False |
_allreduce_coalesced | (tensors, world_size, bucket_size_mb=-1) | Allreduce parameters as a whole. | Allreduce parameters as a whole. | def _allreduce_coalesced(tensors, world_size, bucket_size_mb=-1):
"""Allreduce parameters as a whole."""
if bucket_size_mb > 0:
bucket_size_bytes = bucket_size_mb * 1024 * 1024
buckets = _take_tensors(tensors, bucket_size_bytes)
else:
buckets = OrderedDict()
for tensor in ten... | [
"def",
"_allreduce_coalesced",
"(",
"tensors",
",",
"world_size",
",",
"bucket_size_mb",
"=",
"-",
"1",
")",
":",
"if",
"bucket_size_mb",
">",
"0",
":",
"bucket_size_bytes",
"=",
"bucket_size_mb",
"*",
"1024",
"*",
"1024",
"buckets",
"=",
"_take_tensors",
"(",... | [
7,
0
] | [
27,
32
] | python | en | ['en', 'en', 'en'] | True |
allreduce_grads | (params, coalesce=True, bucket_size_mb=-1) | Allreduce gradients.
Args:
params (list[torch.Parameters]): List of parameters of a model
coalesce (bool, optional): Whether allreduce parameters as a whole.
Default: True.
bucket_size_mb (int, optional): Size of bucket, the unit is MB.
Default: -1.
| Allreduce gradients. | def allreduce_grads(params, coalesce=True, bucket_size_mb=-1):
"""Allreduce gradients.
Args:
params (list[torch.Parameters]): List of parameters of a model
coalesce (bool, optional): Whether allreduce parameters as a whole.
Default: True.
bucket_size_mb (int, optional): Size... | [
"def",
"allreduce_grads",
"(",
"params",
",",
"coalesce",
"=",
"True",
",",
"bucket_size_mb",
"=",
"-",
"1",
")",
":",
"grads",
"=",
"[",
"param",
".",
"grad",
".",
"data",
"for",
"param",
"in",
"params",
"if",
"param",
".",
"requires_grad",
"and",
"pa... | [
30,
0
] | [
49,
52
] | python | de | ['de', 'la', 'en'] | False |
validate_future_date | (value) | Validate that 'value' is not a date in the past (if provided). | Validate that 'value' is not a date in the past (if provided). | def validate_future_date(value):
"""Validate that 'value' is not a date in the past (if provided)."""
if value and value <= timezone.now():
raise ValidationError("Date cannot be in the past") | [
"def",
"validate_future_date",
"(",
"value",
")",
":",
"if",
"value",
"and",
"value",
"<=",
"timezone",
".",
"now",
"(",
")",
":",
"raise",
"ValidationError",
"(",
"\"Date cannot be in the past\"",
")"
] | [
21,
0
] | [
24,
59
] | python | en | ['en', 'en', 'en'] | True |
Person.full_name | (self) | Returns the person's full name. | Returns the person's full name. | def full_name(self):
"""Returns the person's full name."""
return "%s %s" % (self.first_name, self.last_name) | [
"def",
"full_name",
"(",
"self",
")",
":",
"return",
"\"%s %s\"",
"%",
"(",
"self",
".",
"first_name",
",",
"self",
".",
"last_name",
")"
] | [
71,
4
] | [
73,
58
] | python | en | ['en', 'en', 'en'] | True |
Meeting.schedule_recurring | (
name: str,
begin_date: date,
end_date: date,
duration_mins: int,
weekdays: List[Weekdays],
start_times: List[time],
create_after: datetime = None,
group: MeetingGroup = None,
) | Creates recurring Meeting instances based on parameters.
:param name: the name to use for all meeting instances
:param begin_date: the initial date of the recurring meetings
:param end_date: the ending date of the recurring meetings
:param duration_mins: the length of each meeting (in m... | Creates recurring Meeting instances based on parameters. | def schedule_recurring(
name: str,
begin_date: date,
end_date: date,
duration_mins: int,
weekdays: List[Weekdays],
start_times: List[time],
create_after: datetime = None,
group: MeetingGroup = None,
) -> None:
"""Creates recurring Meeting insta... | [
"def",
"schedule_recurring",
"(",
"name",
":",
"str",
",",
"begin_date",
":",
"date",
",",
"end_date",
":",
"date",
",",
"duration_mins",
":",
"int",
",",
"weekdays",
":",
"List",
"[",
"Weekdays",
"]",
",",
"start_times",
":",
"List",
"[",
"time",
"]",
... | [
130,
4
] | [
180,
54
] | python | en | ['en', 'en', 'en'] | True |
Meeting.full_name | (self) | Includes meeting name and start+end datetimes. | Includes meeting name and start+end datetimes. | def full_name(self):
"""Includes meeting name and start+end datetimes."""
return f"{self.name}: {str(self)}" | [
"def",
"full_name",
"(",
"self",
")",
":",
"return",
"f\"{self.name}: {str(self)}\""
] | [
187,
4
] | [
189,
42
] | python | en | ['en', 'en', 'en'] | True |
test_neptune_leave_open_experiment_after_fit | (neptune, tmpdir) | Verify that neptune experiment was closed after training | Verify that neptune experiment was closed after training | def test_neptune_leave_open_experiment_after_fit(neptune, tmpdir):
"""Verify that neptune experiment was closed after training"""
model = BoringModel()
def _run_training(logger):
logger._experiment = MagicMock()
trainer = Trainer(
default_root_dir=tmpdir,
max_epochs=... | [
"def",
"test_neptune_leave_open_experiment_after_fit",
"(",
"neptune",
",",
"tmpdir",
")",
":",
"model",
"=",
"BoringModel",
"(",
")",
"def",
"_run_training",
"(",
"logger",
")",
":",
"logger",
".",
"_experiment",
"=",
"MagicMock",
"(",
")",
"trainer",
"=",
"T... | [
104,
0
] | [
125,
65
] | python | en | ['en', 'en', 'en'] | True |
solution | (n: int = 600851475143) | Returns the largest prime factor of a given number n.
>>> solution(13195)
29
>>> solution(10)
5
>>> solution(17)
17
>>> solution(3.4)
3
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater or equal to one.
>>> solution(-17... | Returns the largest prime factor of a given number n.
>>> solution(13195)
29
>>> solution(10)
5
>>> solution(17)
17
>>> solution(3.4)
3
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater or equal to one.
>>> solution(-17... | def solution(n: int = 600851475143) -> int:
"""Returns the largest prime factor of a given number n.
>>> solution(13195)
29
>>> solution(10)
5
>>> solution(17)
17
>>> solution(3.4)
3
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n mu... | [
"def",
"solution",
"(",
"n",
":",
"int",
"=",
"600851475143",
")",
"->",
"int",
":",
"try",
":",
"n",
"=",
"int",
"(",
"n",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"TypeError",
"(",
"\"Parameter n must be int or passive of ca... | [
10,
0
] | [
61,
19
] | python | en | ['en', 'en', 'en'] | True |
__generator_ctor | (bit_generator_name='MT19937') |
Pickling helper function that returns a Generator object
Parameters
----------
bit_generator_name: str
String containing the core BitGenerator
Returns
-------
rg: Generator
Generator using the named core BitGenerator
|
Pickling helper function that returns a Generator object | def __generator_ctor(bit_generator_name='MT19937'):
"""
Pickling helper function that returns a Generator object
Parameters
----------
bit_generator_name: str
String containing the core BitGenerator
Returns
-------
rg: Generator
Generator using the named core BitGenerat... | [
"def",
"__generator_ctor",
"(",
"bit_generator_name",
"=",
"'MT19937'",
")",
":",
"if",
"bit_generator_name",
"in",
"BitGenerators",
":",
"bit_generator",
"=",
"BitGenerators",
"[",
"bit_generator_name",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"b... | [
15,
0
] | [
35,
37
] | python | en | ['en', 'error', 'th'] | False |
__bit_generator_ctor | (bit_generator_name='MT19937') |
Pickling helper function that returns a bit generator object
Parameters
----------
bit_generator_name: str
String containing the name of the BitGenerator
Returns
-------
bit_generator: BitGenerator
BitGenerator instance
|
Pickling helper function that returns a bit generator object | def __bit_generator_ctor(bit_generator_name='MT19937'):
"""
Pickling helper function that returns a bit generator object
Parameters
----------
bit_generator_name: str
String containing the name of the BitGenerator
Returns
-------
bit_generator: BitGenerator
BitGenerator... | [
"def",
"__bit_generator_ctor",
"(",
"bit_generator_name",
"=",
"'MT19937'",
")",
":",
"if",
"bit_generator_name",
"in",
"BitGenerators",
":",
"bit_generator",
"=",
"BitGenerators",
"[",
"bit_generator_name",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"str",
"(",
... | [
38,
0
] | [
58,
26
] | python | en | ['en', 'error', 'th'] | False |
__randomstate_ctor | (bit_generator_name='MT19937') |
Pickling helper function that returns a legacy RandomState-like object
Parameters
----------
bit_generator_name: str
String containing the core BitGenerator
Returns
-------
rs: RandomState
Legacy RandomState using the named core BitGenerator
|
Pickling helper function that returns a legacy RandomState-like object | def __randomstate_ctor(bit_generator_name='MT19937'):
"""
Pickling helper function that returns a legacy RandomState-like object
Parameters
----------
bit_generator_name: str
String containing the core BitGenerator
Returns
-------
rs: RandomState
Legacy RandomState usin... | [
"def",
"__randomstate_ctor",
"(",
"bit_generator_name",
"=",
"'MT19937'",
")",
":",
"if",
"bit_generator_name",
"in",
"BitGenerators",
":",
"bit_generator",
"=",
"BitGenerators",
"[",
"bit_generator_name",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"str",
"(",
... | [
61,
0
] | [
81,
39
] | python | en | ['en', 'error', 'th'] | False |
CheckpointConnector.restore_weights | (self) |
Attempt to restore a checkpoint (e.g. weights) in this priority:
1. from HPC weights
2. from `resume_from_checkpoint` file
3. don't restore
|
Attempt to restore a checkpoint (e.g. weights) in this priority:
1. from HPC weights
2. from `resume_from_checkpoint` file
3. don't restore
| def restore_weights(self) -> None:
"""
Attempt to restore a checkpoint (e.g. weights) in this priority:
1. from HPC weights
2. from `resume_from_checkpoint` file
3. don't restore
"""
# clear cache before restore
if self.trainer._device_type == DeviceType.G... | [
"def",
"restore_weights",
"(",
"self",
")",
"->",
"None",
":",
"# clear cache before restore",
"if",
"self",
".",
"trainer",
".",
"_device_type",
"==",
"DeviceType",
".",
"GPU",
":",
"torch",
".",
"cuda",
".",
"empty_cache",
"(",
")",
"# 1. Attempt to restore st... | [
51,
4
] | [
79,
36
] | python | en | ['en', 'error', 'th'] | False |
CheckpointConnector.restore | (self, checkpoint_path: str, on_gpu: bool) |
Load model/training states from a 'PyTorch-Lightning checkpoint' file through file-read and state-restore.
All restored states are listed in return value description of `dump_checkpoint`.
|
Load model/training states from a 'PyTorch-Lightning checkpoint' file through file-read and state-restore.
All restored states are listed in return value description of `dump_checkpoint`.
| def restore(self, checkpoint_path: str, on_gpu: bool) -> bool:
"""
Load model/training states from a 'PyTorch-Lightning checkpoint' file through file-read and state-restore.
All restored states are listed in return value description of `dump_checkpoint`.
"""
# Try to read the che... | [
"def",
"restore",
"(",
"self",
",",
"checkpoint_path",
":",
"str",
",",
"on_gpu",
":",
"bool",
")",
"->",
"bool",
":",
"# Try to read the checkpoint file at `checkpoint_path`. If not exist, do not restore checkpoint.",
"fs",
"=",
"get_filesystem",
"(",
"checkpoint_path",
... | [
81,
4
] | [
108,
19
] | python | en | ['en', 'error', 'th'] | False |
CheckpointConnector.restore_model_state | (self, model: LightningModule, checkpoint) |
Restore model states from a 'PyTorch-Lightning checkpoint' dictionary object
|
Restore model states from a 'PyTorch-Lightning checkpoint' dictionary object
| def restore_model_state(self, model: LightningModule, checkpoint) -> None:
"""
Restore model states from a 'PyTorch-Lightning checkpoint' dictionary object
"""
# restore datamodule states
if self.trainer.datamodule is not None:
self.trainer.datamodule.on_load_checkpo... | [
"def",
"restore_model_state",
"(",
"self",
",",
"model",
":",
"LightningModule",
",",
"checkpoint",
")",
"->",
"None",
":",
"# restore datamodule states",
"if",
"self",
".",
"trainer",
".",
"datamodule",
"is",
"not",
"None",
":",
"self",
".",
"trainer",
".",
... | [
110,
4
] | [
123,
55
] | python | en | ['en', 'error', 'th'] | False |
CheckpointConnector.restore_training_state | (self, checkpoint) |
Restore trainer state.
Model will get its change to update
:param checkpoint:
:return:
|
Restore trainer state.
Model will get its change to update
:param checkpoint:
:return:
| def restore_training_state(self, checkpoint):
"""
Restore trainer state.
Model will get its change to update
:param checkpoint:
:return:
"""
# validation
if 'optimizer_states' not in checkpoint or 'lr_schedulers' not in checkpoint:
raise KeyErr... | [
"def",
"restore_training_state",
"(",
"self",
",",
"checkpoint",
")",
":",
"# validation",
"if",
"'optimizer_states'",
"not",
"in",
"checkpoint",
"or",
"'lr_schedulers'",
"not",
"in",
"checkpoint",
":",
"raise",
"KeyError",
"(",
"'Trying to restore training state but ch... | [
125,
4
] | [
195,
61
] | python | en | ['en', 'error', 'th'] | False |
CheckpointConnector.dump_checkpoint | (self, weights_only: bool = False) | Creating a model checkpoint dictionary object from various component states.
Args:
weights_only: saving model weights only
Return:
structured dictionary: {
'epoch': training epoch
'global_step': training global s... | Creating a model checkpoint dictionary object from various component states. | def dump_checkpoint(self, weights_only: bool = False) -> dict:
"""Creating a model checkpoint dictionary object from various component states.
Args:
weights_only: saving model weights only
Return:
structured dictionary: {
'epoch': tra... | [
"def",
"dump_checkpoint",
"(",
"self",
",",
"weights_only",
":",
"bool",
"=",
"False",
")",
"->",
"dict",
":",
"# dump epoch/global_step/pytorch-lightning_version",
"current_epoch",
"=",
"self",
".",
"trainer",
".",
"current_epoch",
"global_step",
"=",
"self",
".",
... | [
238,
4
] | [
328,
25
] | python | en | ['en', 'en', 'en'] | True |
CheckpointConnector.hpc_load | (self, checkpoint_path: str, on_gpu: bool) |
Load model/training states from a 'PyTorch-Lightning checkpoint' file for hpc.
All restored states are listed in return value description of `dump_checkpoint`.
|
Load model/training states from a 'PyTorch-Lightning checkpoint' file for hpc.
All restored states are listed in return value description of `dump_checkpoint`.
| def hpc_load(self, checkpoint_path: str, on_gpu: bool):
"""
Load model/training states from a 'PyTorch-Lightning checkpoint' file for hpc.
All restored states are listed in return value description of `dump_checkpoint`.
"""
# read a checkpoint dictionary object from the 'PyTorch... | [
"def",
"hpc_load",
"(",
"self",
",",
"checkpoint_path",
":",
"str",
",",
"on_gpu",
":",
"bool",
")",
":",
"# read a checkpoint dictionary object from the 'PyTorch-Lightning checkpoint' file at `checkpoint_path`",
"checkpoint",
"=",
"pl_load",
"(",
"checkpoint_path",
",",
"m... | [
330,
4
] | [
352,
37
] | python | en | ['en', 'error', 'th'] | False |
CheckpointConnector.max_ckpt_in_folder | (self, dir_path: Union[str, Path], name_key: str = 'ckpt_') | List up files in `dir_path` with `name_key`, then yield maximum suffix number.
Args:
dir_path: path of directory which may contain files whose name include `name_key`
name_key: file name prefix
Returns:
None if no-corresponding-file else maximum suffix number
... | List up files in `dir_path` with `name_key`, then yield maximum suffix number. | def max_ckpt_in_folder(self, dir_path: Union[str, Path], name_key: str = 'ckpt_') -> Optional[int]:
"""List up files in `dir_path` with `name_key`, then yield maximum suffix number.
Args:
dir_path: path of directory which may contain files whose name include `name_key`
name_key:... | [
"def",
"max_ckpt_in_folder",
"(",
"self",
",",
"dir_path",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"name_key",
":",
"str",
"=",
"'ckpt_'",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"# check directory existence",
"fs",
"=",
"get_filesystem",
"("... | [
354,
4
] | [
383,
27
] | python | en | ['en', 'en', 'en'] | True |
CheckpointConnector.get_max_ckpt_path_from_folder | (self, folder_path: Union[str, Path]) | Get path of maximum-epoch checkpoint in the folder. | Get path of maximum-epoch checkpoint in the folder. | def get_max_ckpt_path_from_folder(self, folder_path: Union[str, Path]) -> str:
"""Get path of maximum-epoch checkpoint in the folder."""
max_suffix = self.max_ckpt_in_folder(folder_path)
ckpt_number = max_suffix if max_suffix is not None else 0
return f'{folder_path}/hpc_ckpt_{ckpt_numb... | [
"def",
"get_max_ckpt_path_from_folder",
"(",
"self",
",",
"folder_path",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
")",
"->",
"str",
":",
"max_suffix",
"=",
"self",
".",
"max_ckpt_in_folder",
"(",
"folder_path",
")",
"ckpt_number",
"=",
"max_suffix",
"if",
... | [
385,
4
] | [
390,
59
] | python | en | ['en', 'en', 'en'] | True |
CheckpointConnector.save_checkpoint | (self, filepath, weights_only: bool = False) | Save model/training states as a checkpoint file through state-dump and file-write.
Args:
filepath: write-target file's path
weights_only: saving model weights only
| Save model/training states as a checkpoint file through state-dump and file-write. | def save_checkpoint(self, filepath, weights_only: bool = False):
"""Save model/training states as a checkpoint file through state-dump and file-write.
Args:
filepath: write-target file's path
weights_only: saving model weights only
"""
# dump states as a checkpoi... | [
"def",
"save_checkpoint",
"(",
"self",
",",
"filepath",
",",
"weights_only",
":",
"bool",
"=",
"False",
")",
":",
"# dump states as a checkpoint dictionary object",
"checkpoint",
"=",
"self",
".",
"dump_checkpoint",
"(",
"weights_only",
")",
"if",
"self",
".",
"tr... | [
392,
4
] | [
415,
49
] | python | en | ['en', 'en', 'en'] | True |
generate_main_code | (type, main_header_file, resolver_cc_file, metrics_header_file, input_files) |
Main code generator.
Takes input files and processes them into structures representing a Kafka message (request or
response).
These responses are then used to create:
- main_header_file - contains definitions of Kafka structures and their deserializers
- resolver_cc_file - contains request api key & vers... |
Main code generator. | def generate_main_code(type, main_header_file, resolver_cc_file, metrics_header_file, input_files):
"""
Main code generator.
Takes input files and processes them into structures representing a Kafka message (request or
response).
These responses are then used to create:
- main_header_file - contains def... | [
"def",
"generate_main_code",
"(",
"type",
",",
"main_header_file",
",",
"resolver_cc_file",
",",
"metrics_header_file",
",",
"input_files",
")",
":",
"processor",
"=",
"StatefulProcessor",
"(",
")",
"# Parse provided input files.",
"messages",
"=",
"processor",
".",
"... | [
5,
0
] | [
52,
26
] | python | en | ['en', 'error', 'th'] | False |
generate_test_code | (
type, header_test_cc_file, codec_test_cc_file, utilities_cc_file, input_files) |
Test code generator.
Takes input files and processes them into structures representing a Kafka message (request or
response).
These responses are then used to create:
- header_test_cc_file - tests for basic message serialization deserialization,
- codec_test_cc_file - tests involving codec and Request/Re... |
Test code generator. | def generate_test_code(
type, header_test_cc_file, codec_test_cc_file, utilities_cc_file, input_files):
"""
Test code generator.
Takes input files and processes them into structures representing a Kafka message (request or
response).
These responses are then used to create:
- header_test_cc_file... | [
"def",
"generate_test_code",
"(",
"type",
",",
"header_test_cc_file",
",",
"codec_test_cc_file",
",",
"utilities_cc_file",
",",
"input_files",
")",
":",
"processor",
"=",
"StatefulProcessor",
"(",
")",
"# Parse provided input files.",
"messages",
"=",
"processor",
".",
... | [
55,
0
] | [
88,
26
] | python | en | ['en', 'error', 'th'] | False |
StatefulProcessor.parse_messages | (self, input_files) |
Parse request/response structures from provided input files.
|
Parse request/response structures from provided input files.
| def parse_messages(self, input_files):
"""
Parse request/response structures from provided input files.
"""
import re
import json
messages = []
# Sort the input files, as the processing is stateful, as we want the same order every time.
input_files.sort()
... | [
"def",
"parse_messages",
"(",
"self",
",",
"input_files",
")",
":",
"import",
"re",
"import",
"json",
"messages",
"=",
"[",
"]",
"# Sort the input files, as the processing is stateful, as we want the same order every time.",
"input_files",
".",
"sort",
"(",
")",
"# For ea... | [
107,
4
] | [
134,
23
] | python | en | ['en', 'error', 'th'] | False |
StatefulProcessor.parse_top_level_element | (self, spec) |
Parse a given structure into a request/response.
Request/response is just a complex type, that has name & version information kept in differently
named fields, compared to sub-structures in a message.
|
Parse a given structure into a request/response.
Request/response is just a complex type, that has name & version information kept in differently
named fields, compared to sub-structures in a message.
| def parse_top_level_element(self, spec):
"""
Parse a given structure into a request/response.
Request/response is just a complex type, that has name & version information kept in differently
named fields, compared to sub-structures in a message.
"""
self.currently_processed_message_type ... | [
"def",
"parse_top_level_element",
"(",
"self",
",",
"spec",
")",
":",
"self",
".",
"currently_processed_message_type",
"=",
"spec",
"[",
"'name'",
"]",
"# Figure out all versions of this message type.",
"versions",
"=",
"Statics",
".",
"parse_version_string",
"(",
"spec... | [
136,
4
] | [
182,
56
] | python | en | ['en', 'error', 'th'] | False |
StatefulProcessor.parse_complex_type | (self, type_name, field_spec, versions) |
Parse given complex type, returning a structure that holds its name, field specification and
allowed versions.
|
Parse given complex type, returning a structure that holds its name, field specification and
allowed versions.
| def parse_complex_type(self, type_name, field_spec, versions):
"""
Parse given complex type, returning a structure that holds its name, field specification and
allowed versions.
"""
fields_el = field_spec.get('fields')
if fields_el is not None:
fields = []
fo... | [
"def",
"parse_complex_type",
"(",
"self",
",",
"type_name",
",",
"field_spec",
",",
"versions",
")",
":",
"fields_el",
"=",
"field_spec",
".",
"get",
"(",
"'fields'",
")",
"if",
"fields_el",
"is",
"not",
"None",
":",
"fields",
"=",
"[",
"]",
"for",
"chil... | [
184,
4
] | [
212,
49
] | python | en | ['en', 'error', 'th'] | False |
StatefulProcessor.parse_field | (self, field_spec, highest_possible_version) |
Parse given field, returning a structure holding the name, type, and versions when this field is
actually used (nullable or not). Obviously, field cannot be used in version higher than its
type's usage.
|
Parse given field, returning a structure holding the name, type, and versions when this field is
actually used (nullable or not). Obviously, field cannot be used in version higher than its
type's usage.
| def parse_field(self, field_spec, highest_possible_version):
"""
Parse given field, returning a structure holding the name, type, and versions when this field is
actually used (nullable or not). Obviously, field cannot be used in version higher than its
type's usage.
"""
if field_spec.ge... | [
"def",
"parse_field",
"(",
"self",
",",
"field_spec",
",",
"highest_possible_version",
")",
":",
"if",
"field_spec",
".",
"get",
"(",
"'tag'",
")",
"is",
"not",
"None",
":",
"return",
"None",
"version_usage",
"=",
"Statics",
".",
"parse_version_string",
"(",
... | [
214,
4
] | [
229,
99
] | python | en | ['en', 'error', 'th'] | False |
StatefulProcessor.parse_type | (self, type_name, field_spec, highest_possible_version) |
Parse a given type element - returns an array type, primitive (e.g. uint32_t) or complex one.
|
Parse a given type element - returns an array type, primitive (e.g. uint32_t) or complex one.
| def parse_type(self, type_name, field_spec, highest_possible_version):
"""
Parse a given type element - returns an array type, primitive (e.g. uint32_t) or complex one.
"""
if (type_name.startswith('[]')):
# In spec files, array types are defined as `[]underlying_type` instead of hav... | [
"def",
"parse_type",
"(",
"self",
",",
"type_name",
",",
"field_spec",
",",
"highest_possible_version",
")",
":",
"if",
"(",
"type_name",
".",
"startswith",
"(",
"'[]'",
")",
")",
":",
"# In spec files, array types are defined as `[]underlying_type` instead of having its ... | [
231,
4
] | [
246,
79
] | python | en | ['en', 'error', 'th'] | False |
Statics.parse_version_string | (raw_versions, highest_possible_version) |
Return integer range that corresponds to version string in spec file.
|
Return integer range that corresponds to version string in spec file.
| def parse_version_string(raw_versions, highest_possible_version):
"""
Return integer range that corresponds to version string in spec file.
"""
if raw_versions.endswith('+'):
return range(int(raw_versions[:-1]), highest_possible_version + 1)
else:
if '-' in raw_ve... | [
"def",
"parse_version_string",
"(",
"raw_versions",
",",
"highest_possible_version",
")",
":",
"if",
"raw_versions",
".",
"endswith",
"(",
"'+'",
")",
":",
"return",
"range",
"(",
"int",
"(",
"raw_versions",
"[",
":",
"-",
"1",
"]",
")",
",",
"highest_possib... | [
252,
4
] | [
264,
64
] | python | en | ['en', 'error', 'th'] | False |
FieldList.used_fields | (self) |
Return list of fields that are actually used in this version of structure.
|
Return list of fields that are actually used in this version of structure.
| def used_fields(self):
"""
Return list of fields that are actually used in this version of structure.
"""
return filter(lambda x: x.used_in_version(self.version), self.fields) | [
"def",
"used_fields",
"(",
"self",
")",
":",
"return",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"used_in_version",
"(",
"self",
".",
"version",
")",
",",
"self",
".",
"fields",
")"
] | [
278,
4
] | [
282,
77
] | python | en | ['en', 'error', 'th'] | False |
FieldList.constructor_signature | (self) |
Return constructor signature.
Multiple versions of the same structure can have identical signatures (due to version bumps in
Kafka).
|
Return constructor signature.
Multiple versions of the same structure can have identical signatures (due to version bumps in
Kafka).
| def constructor_signature(self):
"""
Return constructor signature.
Multiple versions of the same structure can have identical signatures (due to version bumps in
Kafka).
"""
parameter_spec = map(lambda x: x.parameter_declaration(self.version), self.used_fields())
return ', '.join... | [
"def",
"constructor_signature",
"(",
"self",
")",
":",
"parameter_spec",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"parameter_declaration",
"(",
"self",
".",
"version",
")",
",",
"self",
".",
"used_fields",
"(",
")",
")",
"return",
"', '",
".",
"joi... | [
284,
4
] | [
291,
40
] | python | en | ['en', 'error', 'th'] | False |
FieldList.constructor_init_list | (self) |
Renders member initialization list in constructor.
Takes care of potential optional<T> conversions (as field could be T in V1, but optional<T>
in V2).
|
Renders member initialization list in constructor.
Takes care of potential optional<T> conversions (as field could be T in V1, but optional<T>
in V2).
| def constructor_init_list(self):
"""
Renders member initialization list in constructor.
Takes care of potential optional<T> conversions (as field could be T in V1, but optional<T>
in V2).
"""
init_list = []
for field in self.fields:
if field.used_in_version(self.versi... | [
"def",
"constructor_init_list",
"(",
"self",
")",
":",
"init_list",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"if",
"field",
".",
"used_in_version",
"(",
"self",
".",
"version",
")",
":",
"if",
"field",
".",
"is_nullable",
"(",
"... | [
293,
4
] | [
320,
35
] | python | en | ['en', 'error', 'th'] | False |
FieldSpec.is_nullable_in_version | (self, version) |
Whether the field is nullable in given version.
Fields can be non-nullable in earlier versions.
See https://github.com/apache/kafka/tree/2.2.0-rc0/clients/src/main/resources/common/message#nullable-fields
|
Whether the field is nullable in given version.
Fields can be non-nullable in earlier versions.
See https://github.com/apache/kafka/tree/2.2.0-rc0/clients/src/main/resources/common/message#nullable-fields
| def is_nullable_in_version(self, version):
"""
Whether the field is nullable in given version.
Fields can be non-nullable in earlier versions.
See https://github.com/apache/kafka/tree/2.2.0-rc0/clients/src/main/resources/common/message#nullable-fields
"""
return version in self.version_u... | [
"def",
"is_nullable_in_version",
"(",
"self",
",",
"version",
")",
":",
"return",
"version",
"in",
"self",
".",
"version_usage_as_nullable"
] | [
346,
4
] | [
352,
56
] | python | en | ['en', 'error', 'th'] | False |
TypeSpecification.compute_declaration_chain | (self) |
Computes types that need to be declared before this type can be declared, in C++ sense.
|
Computes types that need to be declared before this type can be declared, in C++ sense.
| def compute_declaration_chain(self):
"""
Computes types that need to be declared before this type can be declared, in C++ sense.
"""
raise NotImplementedError() | [
"def",
"compute_declaration_chain",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
399,
4
] | [
403,
35
] | python | en | ['en', 'error', 'th'] | False |
TypeSpecification.deserializer_name_in_version | (self, version, compact) |
Renders the deserializer name of given type, in message with given version.
|
Renders the deserializer name of given type, in message with given version.
| def deserializer_name_in_version(self, version, compact):
"""
Renders the deserializer name of given type, in message with given version.
"""
raise NotImplementedError() | [
"def",
"deserializer_name_in_version",
"(",
"self",
",",
"version",
",",
"compact",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
405,
4
] | [
409,
35
] | python | en | ['en', 'error', 'th'] | False |
TypeSpecification.default_value | (self) |
Returns a default value for given type.
|
Returns a default value for given type.
| def default_value(self):
"""
Returns a default value for given type.
"""
raise NotImplementedError() | [
"def",
"default_value",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
411,
4
] | [
415,
35
] | python | en | ['en', 'error', 'th'] | False |
TypeSpecification.has_flexible_handling | (self) |
Whether the given type has special encoding when carrying message is using flexible encoding.
|
Whether the given type has special encoding when carrying message is using flexible encoding.
| def has_flexible_handling(self):
"""
Whether the given type has special encoding when carrying message is using flexible encoding.
"""
raise NotImplementedError() | [
"def",
"has_flexible_handling",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
417,
4
] | [
421,
35
] | python | en | ['en', 'error', 'th'] | False |
Complex.compute_declaration_chain | (self) |
Computes all dependencies, what means all non-primitive types used by this type.
They need to be declared before this struct is declared.
|
Computes all dependencies, what means all non-primitive types used by this type.
They need to be declared before this struct is declared.
| def compute_declaration_chain(self):
"""
Computes all dependencies, what means all non-primitive types used by this type.
They need to be declared before this struct is declared.
"""
result = []
for field in self.fields:
field_dependencies = field.type.compute_declaration... | [
"def",
"compute_declaration_chain",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"field_dependencies",
"=",
"field",
".",
"type",
".",
"compute_declaration_chain",
"(",
")",
"for",
"field_dependency",
"in",
... | [
604,
4
] | [
616,
21
] | python | en | ['en', 'error', 'th'] | False |
Complex.compute_constructors | (self) |
Field lists for different versions may not differ (as Kafka can bump version without any
changes). But constructors need to be unique, so we need to remove duplicates if the signatures
match.
|
Field lists for different versions may not differ (as Kafka can bump version without any
changes). But constructors need to be unique, so we need to remove duplicates if the signatures
match.
| def compute_constructors(self):
"""
Field lists for different versions may not differ (as Kafka can bump version without any
changes). But constructors need to be unique, so we need to remove duplicates if the signatures
match.
"""
signature_to_constructor = {}
for field_list in ... | [
"def",
"compute_constructors",
"(",
"self",
")",
":",
"signature_to_constructor",
"=",
"{",
"}",
"for",
"field_list",
"in",
"self",
".",
"compute_field_lists",
"(",
")",
":",
"signature",
"=",
"field_list",
".",
"constructor_signature",
"(",
")",
"constructor",
... | [
625,
4
] | [
647,
88
] | python | en | ['en', 'error', 'th'] | False |
Complex.compute_field_lists | (self) |
Return field lists representing each of structure versions.
|
Return field lists representing each of structure versions.
| def compute_field_lists(self):
"""
Return field lists representing each of structure versions.
"""
field_lists = []
for version in self.versions:
field_list = FieldList(version, version in self.flexible_versions, self.fields)
field_lists.append(field_list)
... | [
"def",
"compute_field_lists",
"(",
"self",
")",
":",
"field_lists",
"=",
"[",
"]",
"for",
"version",
"in",
"self",
".",
"versions",
":",
"field_list",
"=",
"FieldList",
"(",
"version",
",",
"version",
"in",
"self",
".",
"flexible_versions",
",",
"self",
".... | [
649,
4
] | [
657,
26
] | python | en | ['en', 'error', 'th'] | False |
parse_structure | (astr, level) |
The returned line number is from the beginning of the string, starting
at zero. Returns an empty list if no loops found.
|
The returned line number is from the beginning of the string, starting
at zero. Returns an empty list if no loops found. | def parse_structure(astr, level):
"""
The returned line number is from the beginning of the string, starting
at zero. Returns an empty list if no loops found.
"""
if level == 0 :
loopbeg = "/**begin repeat"
loopend = "/**end repeat**/"
else :
loopbeg = "/**begin repeat%d... | [
"def",
"parse_structure",
"(",
"astr",
",",
"level",
")",
":",
"if",
"level",
"==",
"0",
":",
"loopbeg",
"=",
"\"/**begin repeat\"",
"loopend",
"=",
"\"/**end repeat**/\"",
"else",
":",
"loopbeg",
"=",
"\"/**begin repeat%d\"",
"%",
"level",
"loopend",
"=",
"\"... | [
106,
0
] | [
135,
19
] | python | en | ['en', 'error', 'th'] | False |
parse_loop_header | (loophead) | Find all named replacements in the header
Returns a list of dictionaries, one for each loop iteration,
where each key is a name to be substituted and the corresponding
value is the replacement string.
Also return a list of exclusions. The exclusions are dictionaries
of key value pairs. There can... | Find all named replacements in the header | def parse_loop_header(loophead) :
"""Find all named replacements in the header
Returns a list of dictionaries, one for each loop iteration,
where each key is a name to be substituted and the corresponding
value is the replacement string.
Also return a list of exclusions. The exclusions are dictio... | [
"def",
"parse_loop_header",
"(",
"loophead",
")",
":",
"# Strip out '\\n' and leading '*', if any, in continuation lines.",
"# This should not effect code previous to this change as",
"# continuation lines were not allowed.",
"loophead",
"=",
"stripast",
".",
"sub",
"(",
"\"\"",
",",... | [
161,
0
] | [
211,
16
] | python | en | ['en', 'en', 'en'] | True |
RPCPlugin.rpc_save_model | (self, save_model_fn, last_filepath, trainer, pl_module) |
Override to save model to disk.
This is required as the main process will be required to handle aggregating model states from RPC processes.
Args:
save_model_fn: The saving function to save final model.
last_filepath: The filepath to save the model to.
train... |
Override to save model to disk.
This is required as the main process will be required to handle aggregating model states from RPC processes. | def rpc_save_model(self, save_model_fn, last_filepath, trainer, pl_module) -> None:
"""
Override to save model to disk.
This is required as the main process will be required to handle aggregating model states from RPC processes.
Args:
save_model_fn: The saving function to sa... | [
"def",
"rpc_save_model",
"(",
"self",
",",
"save_model_fn",
",",
"last_filepath",
",",
"trainer",
",",
"pl_module",
")",
"->",
"None",
":",
"raise",
"NotImplementedError"
] | [
65,
4
] | [
76,
33
] | python | en | ['en', 'error', 'th'] | False |
Trainer.__init__ | (
self,
logger: Union[LightningLoggerBase, Iterable[LightningLoggerBase], bool] = True,
checkpoint_callback: bool = True,
callbacks: Optional[Union[List[Callback], Callback]] = None,
default_root_dir: Optional[str] = None,
gradient_clip_val: float = 0,
process_pos... | r"""
Customize every aspect of training via flags
Args:
accelerator: Previously known as distributed_backend (dp, ddp, ddp2, etc...).
Can also take in an accelerator object for custom hardware.
accumulate_grad_batches: Accumulates grads every k batches or as se... | r"""
Customize every aspect of training via flags | def __init__(
self,
logger: Union[LightningLoggerBase, Iterable[LightningLoggerBase], bool] = True,
checkpoint_callback: bool = True,
callbacks: Optional[Union[List[Callback], Callback]] = None,
default_root_dir: Optional[str] = None,
gradient_clip_val: float = 0,
... | [
"def",
"__init__",
"(",
"self",
",",
"logger",
":",
"Union",
"[",
"LightningLoggerBase",
",",
"Iterable",
"[",
"LightningLoggerBase",
"]",
",",
"bool",
"]",
"=",
"True",
",",
"checkpoint_callback",
":",
"bool",
"=",
"True",
",",
"callbacks",
":",
"Optional",... | [
85,
4
] | [
383,
26
] | python | cy | ['en', 'cy', 'hi'] | False |
Trainer.setup_trainer | (self, model: LightningModule) |
Sanity check a few things before starting actual training or testing.
Args:
model: The model to run sanity test on.
|
Sanity check a few things before starting actual training or testing. | def setup_trainer(self, model: LightningModule):
"""
Sanity check a few things before starting actual training or testing.
Args:
model: The model to run sanity test on.
"""
# log hyper-parameters
if self.logger is not None:
# save exp to get star... | [
"def",
"setup_trainer",
"(",
"self",
",",
"model",
":",
"LightningModule",
")",
":",
"# log hyper-parameters",
"if",
"self",
".",
"logger",
"is",
"not",
"None",
":",
"# save exp to get started (this is where the first experiment logs are written)",
"self",
".",
"logger",
... | [
385,
4
] | [
398,
30
] | python | en | ['en', 'error', 'th'] | False |
Trainer.fit | (
self,
model: LightningModule,
train_dataloader: Optional[DataLoader] = None,
val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
datamodule: Optional[LightningDataModule] = None,
) | r"""
Runs the full optimization routine.
Args:
datamodule: A instance of :class:`LightningDataModule`.
model: Model to fit.
train_dataloader: A Pytorch DataLoader with training samples. If the model has
a predefined train_dataloader method this will... | r"""
Runs the full optimization routine. | def fit(
self,
model: LightningModule,
train_dataloader: Optional[DataLoader] = None,
val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
datamodule: Optional[LightningDataModule] = None,
):
r"""
Runs the full optimization routine.
... | [
"def",
"fit",
"(",
"self",
",",
"model",
":",
"LightningModule",
",",
"train_dataloader",
":",
"Optional",
"[",
"DataLoader",
"]",
"=",
"None",
",",
"val_dataloaders",
":",
"Optional",
"[",
"Union",
"[",
"DataLoader",
",",
"List",
"[",
"DataLoader",
"]",
"... | [
400,
4
] | [
511,
44
] | python | cy | ['en', 'cy', 'hi'] | False |
Trainer.test | (
self,
model: Optional[LightningModule] = None,
test_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
ckpt_path: Optional[str] = 'best',
verbose: bool = True,
datamodule: Optional[LightningDataModule] = None,
) | r"""
Separates from fit to make sure you never run on your test set until you want to.
Args:
ckpt_path: Either ``best`` or path to the checkpoint you wish to test.
If ``None``, use the weights from the last epoch to test. Default to ``best``.
datamodule: A inst... | r""" | def test(
self,
model: Optional[LightningModule] = None,
test_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
ckpt_path: Optional[str] = 'best',
verbose: bool = True,
datamodule: Optional[LightningDataModule] = None,
):
r"""
Separat... | [
"def",
"test",
"(",
"self",
",",
"model",
":",
"Optional",
"[",
"LightningModule",
"]",
"=",
"None",
",",
"test_dataloaders",
":",
"Optional",
"[",
"Union",
"[",
"DataLoader",
",",
"List",
"[",
"DataLoader",
"]",
"]",
"]",
"=",
"None",
",",
"ckpt_path",
... | [
842,
4
] | [
893,
22
] | python | cy | ['en', 'cy', 'hi'] | False |
Trainer.predict | (
self,
model: Optional[LightningModule] = None,
dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
datamodule: Optional[LightningDataModule] = None,
) | r"""
Separates from fit to make sure you never run on your predictions set until you want to.
This will call the model forward function to compute predictions.
Args:
model: The model to predict on.
dataloaders: Either a single
Pytorch Dataloader or a l... | r""" | def predict(
self,
model: Optional[LightningModule] = None,
dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
datamodule: Optional[LightningDataModule] = None,
):
r"""
Separates from fit to make sure you never run on your predictions set until you wa... | [
"def",
"predict",
"(",
"self",
",",
"model",
":",
"Optional",
"[",
"LightningModule",
"]",
"=",
"None",
",",
"dataloaders",
":",
"Optional",
"[",
"Union",
"[",
"DataLoader",
",",
"List",
"[",
"DataLoader",
"]",
"]",
"]",
"=",
"None",
",",
"datamodule",
... | [
953,
4
] | [
1003,
22
] | python | cy | ['en', 'cy', 'hi'] | False |
Trainer.tune | (
self,
model: LightningModule,
train_dataloader: Optional[DataLoader] = None,
val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
datamodule: Optional[LightningDataModule] = None,
) | r"""
Runs routines to tune hyperparameters before training.
Args:
datamodule: A instance of :class:`LightningDataModule`.
model: Model to tune.
train_dataloader: A Pytorch DataLoader with training samples. If the model has
a predefined train_dataloa... | r"""
Runs routines to tune hyperparameters before training. | def tune(
self,
model: LightningModule,
train_dataloader: Optional[DataLoader] = None,
val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
datamodule: Optional[LightningDataModule] = None,
):
r"""
Runs routines to tune hyperparameters before... | [
"def",
"tune",
"(",
"self",
",",
"model",
":",
"LightningModule",
",",
"train_dataloader",
":",
"Optional",
"[",
"DataLoader",
"]",
"=",
"None",
",",
"val_dataloaders",
":",
"Optional",
"[",
"Union",
"[",
"DataLoader",
",",
"List",
"[",
"DataLoader",
"]",
... | [
1005,
4
] | [
1027,
77
] | python | cy | ['en', 'cy', 'hi'] | False |
get_class | (name, notfound_action=1) |
notfound_action:
0 - do nothing
1 - display warning message
2 - raise error
|
notfound_action:
0 - do nothing
1 - display warning message
2 - raise error
| def get_class(name, notfound_action=1):
"""
notfound_action:
0 - do nothing
1 - display warning message
2 - raise error
"""
cl = {'temp1': Temp1Info,
'temp2': Temp2Info,
'duplicate_options': DuplicateOptionInfo,
}.get(name.lower(), _system_info)
return... | [
"def",
"get_class",
"(",
"name",
",",
"notfound_action",
"=",
"1",
")",
":",
"cl",
"=",
"{",
"'temp1'",
":",
"Temp1Info",
",",
"'temp2'",
":",
"Temp2Info",
",",
"'duplicate_options'",
":",
"DuplicateOptionInfo",
",",
"}",
".",
"get",
"(",
"name",
".",
"l... | [
17,
0
] | [
28,
15
] | python | en | ['en', 'error', 'th'] | False |
have_compiler | () | Return True if there appears to be an executable compiler
| Return True if there appears to be an executable compiler
| def have_compiler():
""" Return True if there appears to be an executable compiler
"""
compiler = customized_ccompiler()
try:
cmd = compiler.compiler # Unix compilers
except AttributeError:
try:
if not compiler.initialized:
compiler.initialize() # MSVC i... | [
"def",
"have_compiler",
"(",
")",
":",
"compiler",
"=",
"customized_ccompiler",
"(",
")",
"try",
":",
"cmd",
"=",
"compiler",
".",
"compiler",
"# Unix compilers",
"except",
"AttributeError",
":",
"try",
":",
"if",
"not",
"compiler",
".",
"initialized",
":",
... | [
65,
0
] | [
85,
15
] | python | en | ['en', 'en', 'en'] | True |
_system_info._check_libs | (self, lib_dirs, libs, opt_libs, exts) | Override _check_libs to return with all dirs | Override _check_libs to return with all dirs | def _check_libs(self, lib_dirs, libs, opt_libs, exts):
"""Override _check_libs to return with all dirs """
info = {'libraries': libs, 'library_dirs': lib_dirs}
return info | [
"def",
"_check_libs",
"(",
"self",
",",
"lib_dirs",
",",
"libs",
",",
"opt_libs",
",",
"exts",
")",
":",
"info",
"=",
"{",
"'libraries'",
":",
"libs",
",",
"'library_dirs'",
":",
"lib_dirs",
"}",
"return",
"info"
] | [
112,
4
] | [
115,
19
] | python | en | ['en', 'en', 'en'] | True |
TestSystemInfoReading.setup | (self) | Create the libraries | Create the libraries | def setup(self):
""" Create the libraries """
# Create 2 sources and 2 libraries
self._dir1 = mkdtemp()
self._src1 = os.path.join(self._dir1, 'foo.c')
self._lib1 = os.path.join(self._dir1, 'libfoo.so')
self._dir2 = mkdtemp()
self._src2 = os.path.join(self._dir2, '... | [
"def",
"setup",
"(",
"self",
")",
":",
"# Create 2 sources and 2 libraries",
"self",
".",
"_dir1",
"=",
"mkdtemp",
"(",
")",
"self",
".",
"_src1",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_dir1",
",",
"'foo.c'",
")",
"self",
".",
"_lib1"... | [
134,
4
] | [
173,
58
] | python | en | ['en', 'en', 'en'] | True |
asmatrix | (data, dtype=None) |
Interpret the input as a matrix.
Unlike `matrix`, `asmatrix` does not make a copy if the input is already
a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
Parameters
----------
data : array_like
Input data.
dtype : data-type
Data-type of the output matri... |
Interpret the input as a matrix. | def asmatrix(data, dtype=None):
"""
Interpret the input as a matrix.
Unlike `matrix`, `asmatrix` does not make a copy if the input is already
a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
Parameters
----------
data : array_like
Input data.
dtype : data-ty... | [
"def",
"asmatrix",
"(",
"data",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"matrix",
"(",
"data",
",",
"dtype",
"=",
"dtype",
",",
"copy",
"=",
"False",
")"
] | [
38,
0
] | [
70,
48
] | python | en | ['en', 'error', 'th'] | False |
bmat | (obj, ldict=None, gdict=None) |
Build a matrix object from a string, nested sequence, or array.
Parameters
----------
obj : str or array_like
Input data. If a string, variables in the current scope may be
referenced by name.
ldict : dict, optional
A dictionary that replaces local operands in current frame... |
Build a matrix object from a string, nested sequence, or array. | def bmat(obj, ldict=None, gdict=None):
"""
Build a matrix object from a string, nested sequence, or array.
Parameters
----------
obj : str or array_like
Input data. If a string, variables in the current scope may be
referenced by name.
ldict : dict, optional
A dictionary... | [
"def",
"bmat",
"(",
"obj",
",",
"ldict",
"=",
"None",
",",
"gdict",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"if",
"gdict",
"is",
"None",
":",
"# get previous frame",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
"... | [
1037,
0
] | [
1112,
26
] | python | en | ['en', 'error', 'th'] | False |
_indices_for_nelems | (nelems) | Returns slices of length nelems, from start onwards, in direction sign. | Returns slices of length nelems, from start onwards, in direction sign. | def _indices_for_nelems(nelems):
"""Returns slices of length nelems, from start onwards, in direction sign."""
if nelems == 0:
return [size // 2] # int index
res = []
for step in (1, 2):
for sign in (-1, 1):
start = size // 2 - nelems * step * sign // 2
stop = ... | [
"def",
"_indices_for_nelems",
"(",
"nelems",
")",
":",
"if",
"nelems",
"==",
"0",
":",
"return",
"[",
"size",
"//",
"2",
"]",
"# int index",
"res",
"=",
"[",
"]",
"for",
"step",
"in",
"(",
"1",
",",
"2",
")",
":",
"for",
"sign",
"in",
"(",
"-",
... | [
27,
0
] | [
40,
14
] | python | en | ['en', 'en', 'en'] | True |
_indices_for_axis | () | Returns (src, dst) pairs of indices. | Returns (src, dst) pairs of indices. | def _indices_for_axis():
"""Returns (src, dst) pairs of indices."""
res = []
for nelems in (0, 2, 3):
ind = _indices_for_nelems(nelems)
# no itertools.product available in Py2.4
res.extend([(a, b) for a in ind for b in ind]) # all assignments of size "nelems"
return res | [
"def",
"_indices_for_axis",
"(",
")",
":",
"res",
"=",
"[",
"]",
"for",
"nelems",
"in",
"(",
"0",
",",
"2",
",",
"3",
")",
":",
"ind",
"=",
"_indices_for_nelems",
"(",
"nelems",
")",
"# no itertools.product available in Py2.4",
"res",
".",
"extend",
"(",
... | [
43,
0
] | [
53,
14
] | python | en | ['en', 'en', 'en'] | True |
_indices | (ndims) | Returns ((axis0_src, axis0_dst), (axis1_src, axis1_dst), ... ) index pairs. | Returns ((axis0_src, axis0_dst), (axis1_src, axis1_dst), ... ) index pairs. | def _indices(ndims):
"""Returns ((axis0_src, axis0_dst), (axis1_src, axis1_dst), ... ) index pairs."""
ind = _indices_for_axis()
# no itertools.product available in Py2.4
res = [[]]
for i in range(ndims):
newres = []
for elem in ind:
for others in res:
... | [
"def",
"_indices",
"(",
"ndims",
")",
":",
"ind",
"=",
"_indices_for_axis",
"(",
")",
"# no itertools.product available in Py2.4",
"res",
"=",
"[",
"[",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"ndims",
")",
":",
"newres",
"=",
"[",
"]",
"for",
"elem",
... | [
56,
0
] | [
71,
14
] | python | en | ['en', 'en', 'en'] | True |
_check_assignment | (srcidx, dstidx) | Check assignment arr[dstidx] = arr[srcidx] works. | Check assignment arr[dstidx] = arr[srcidx] works. | def _check_assignment(srcidx, dstidx):
"""Check assignment arr[dstidx] = arr[srcidx] works."""
arr = np.arange(np.product(shape)).reshape(shape)
cpy = arr.copy()
cpy[dstidx] = arr[srcidx]
arr[dstidx] = arr[srcidx]
assert_(np.all(arr == cpy),
'assigning arr[%s] = arr[%s]' % (dstid... | [
"def",
"_check_assignment",
"(",
"srcidx",
",",
"dstidx",
")",
":",
"arr",
"=",
"np",
".",
"arange",
"(",
"np",
".",
"product",
"(",
"shape",
")",
")",
".",
"reshape",
"(",
"shape",
")",
"cpy",
"=",
"arr",
".",
"copy",
"(",
")",
"cpy",
"[",
"dsti... | [
74,
0
] | [
85,
61
] | python | en | ['en', 'fr', 'en'] | True |
view_element_first_byte | (x) | Construct an array viewing the first byte of each element of `x` | Construct an array viewing the first byte of each element of `x` | def view_element_first_byte(x):
"""Construct an array viewing the first byte of each element of `x`"""
from numpy.lib.stride_tricks import DummyArray
interface = dict(x.__array_interface__)
interface['typestr'] = '|b1'
interface['descr'] = [('', '|b1')]
return np.asarray(DummyArray(interface, x)... | [
"def",
"view_element_first_byte",
"(",
"x",
")",
":",
"from",
"numpy",
".",
"lib",
".",
"stride_tricks",
"import",
"DummyArray",
"interface",
"=",
"dict",
"(",
"x",
".",
"__array_interface__",
")",
"interface",
"[",
"'typestr'",
"]",
"=",
"'|b1'",
"interface",... | [
591,
0
] | [
597,
47
] | python | en | ['en', 'en', 'en'] | True |
assert_copy_equivalent | (operation, args, out, **kwargs) |
Check that operation(*args, out=out) produces results
equivalent to out[...] = operation(*args, out=out.copy())
|
Check that operation(*args, out=out) produces results
equivalent to out[...] = operation(*args, out=out.copy())
| def assert_copy_equivalent(operation, args, out, **kwargs):
"""
Check that operation(*args, out=out) produces results
equivalent to out[...] = operation(*args, out=out.copy())
"""
kwargs['out'] = out
kwargs2 = dict(kwargs)
kwargs2['out'] = out.copy()
out_orig = out.copy()
out[...] ... | [
"def",
"assert_copy_equivalent",
"(",
"operation",
",",
"args",
",",
"out",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'out'",
"]",
"=",
"out",
"kwargs2",
"=",
"dict",
"(",
"kwargs",
")",
"kwargs2",
"[",
"'out'",
"]",
"=",
"out",
".",
"copy",... | [
600,
0
] | [
618,
35
] | python | en | ['en', 'error', 'th'] | False |
_strip_basic_auth | (url: str) | Returns *url* with basic auth credentials removed. Also returns the
basic auth username and password if they're present in *url*.
E.g.: https://user:pass@example.com => https://example.com
*url* need not include basic auth credentials.
:param url: url which may or may not contain basic auth credentia... | Returns *url* with basic auth credentials removed. Also returns the
basic auth username and password if they're present in *url*. | def _strip_basic_auth(url: str) -> str:
"""Returns *url* with basic auth credentials removed. Also returns the
basic auth username and password if they're present in *url*.
E.g.: https://user:pass@example.com => https://example.com
*url* need not include basic auth credentials.
:param url: url wh... | [
"def",
"_strip_basic_auth",
"(",
"url",
":",
"str",
")",
"->",
"str",
":",
"frags",
"=",
"list",
"(",
"urlsplit",
"(",
"url",
")",
")",
"# swap out \"user[:pass]@hostname\" for \"hostname\"",
"if",
"'@'",
"in",
"frags",
"[",
"1",
"]",
":",
"frags",
"[",
"1... | [
94,
0
] | [
112,
28
] | python | en | ['en', 'en', 'en'] | True |
_read_from_url | (url: str, config: Config = None) | Reads data from *url* with an HTTP *GET*.
This function supports fetching from resources which use basic HTTP auth as
laid out by RFC1738 § 3.1. See § 5 for grammar definitions for URLs.
.. seealso:
https://www.ietf.org/rfc/rfc1738.txt
:param url: URL of an HTTP resource
:type url: ``str`... | Reads data from *url* with an HTTP *GET*. | def _read_from_url(url: str, config: Config = None) -> IO:
"""Reads data from *url* with an HTTP *GET*.
This function supports fetching from resources which use basic HTTP auth as
laid out by RFC1738 § 3.1. See § 5 for grammar definitions for URLs.
.. seealso:
https://www.ietf.org/rfc/rfc1738.... | [
"def",
"_read_from_url",
"(",
"url",
":",
"str",
",",
"config",
":",
"Config",
"=",
"None",
")",
"->",
"IO",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
",",
"config",
"=",
"config",
",",
"timeout",
"=",
"config",... | [
115,
0
] | [
137,
16
] | python | en | ['en', 'en', 'en'] | True |
_get_safe_url | (url: str) | Gets version of *url* with basic auth passwords obscured. This function
returns results suitable for printing and logging.
E.g.: https://user:12345@example.com => https://user@example.com
:param url: a url
:type url: ``str``
:return: *url* with password removed
:rtype: ``str``
| Gets version of *url* with basic auth passwords obscured. This function
returns results suitable for printing and logging. | def _get_safe_url(url: str) -> str:
"""Gets version of *url* with basic auth passwords obscured. This function
returns results suitable for printing and logging.
E.g.: https://user:12345@example.com => https://user@example.com
:param url: a url
:type url: ``str``
:return: *url* with password ... | [
"def",
"_get_safe_url",
"(",
"url",
":",
"str",
")",
"->",
"str",
":",
"parts",
"=",
"urlsplit",
"(",
"url",
")",
"if",
"parts",
".",
"username",
"is",
"None",
":",
"return",
"url",
"else",
":",
"frags",
"=",
"list",
"(",
"parts",
")",
"if",
"parts... | [
140,
0
] | [
162,
32
] | python | en | ['en', 'en', 'en'] | True |
fetch_inventory | (app: Sphinx, uri: str, inv: Any) | Fetch, parse and return an intersphinx inventory file. | Fetch, parse and return an intersphinx inventory file. | def fetch_inventory(app: Sphinx, uri: str, inv: Any) -> Any:
"""Fetch, parse and return an intersphinx inventory file."""
# both *uri* (base URI of the links to generate) and *inv* (actual
# location of the inventory file) can be local or remote URIs
localuri = '://' not in uri
if not localuri:
... | [
"def",
"fetch_inventory",
"(",
"app",
":",
"Sphinx",
",",
"uri",
":",
"str",
",",
"inv",
":",
"Any",
")",
"->",
"Any",
":",
"# both *uri* (base URI of the links to generate) and *inv* (actual",
"# location of the inventory file) can be local or remote URIs",
"localuri",
"="... | [
165,
0
] | [
201,
22
] | python | en | ['en', 'en', 'en'] | True |
load_mappings | (app: Sphinx) | Load all intersphinx mappings into the environment. | Load all intersphinx mappings into the environment. | def load_mappings(app: Sphinx) -> None:
"""Load all intersphinx mappings into the environment."""
now = int(time.time())
inventories = InventoryAdapter(app.builder.env)
with concurrent.futures.ThreadPoolExecutor() as pool:
futures = []
for name, (uri, invs) in app.config.intersphinx_map... | [
"def",
"load_mappings",
"(",
"app",
":",
"Sphinx",
")",
"->",
"None",
":",
"now",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"inventories",
"=",
"InventoryAdapter",
"(",
"app",
".",
"builder",
".",
"env",
")",
"with",
"concurrent",
".",
"fu... | [
241,
0
] | [
271,
79
] | python | en | ['en', 'en', 'en'] | True |
missing_reference | (app: Sphinx, env: BuildEnvironment, node: pending_xref,
contnode: TextElement) | Attempt to resolve a missing reference via intersphinx references. | Attempt to resolve a missing reference via intersphinx references. | def missing_reference(app: Sphinx, env: BuildEnvironment, node: pending_xref,
contnode: TextElement) -> nodes.reference:
"""Attempt to resolve a missing reference via intersphinx references."""
target = node['reftarget']
inventories = InventoryAdapter(env)
objtypes: List[str] = Non... | [
"def",
"missing_reference",
"(",
"app",
":",
"Sphinx",
",",
"env",
":",
"BuildEnvironment",
",",
"node",
":",
"pending_xref",
",",
"contnode",
":",
"TextElement",
")",
"->",
"nodes",
".",
"reference",
":",
"target",
"=",
"node",
"[",
"'reftarget'",
"]",
"i... | [
274,
0
] | [
365,
15
] | python | en | ['en', 'en', 'en'] | True |
inspect_main | (argv: List[str]) | Debug functionality to print out an inventory | Debug functionality to print out an inventory | def inspect_main(argv: List[str]) -> None:
"""Debug functionality to print out an inventory"""
if len(argv) < 1:
print("Print out an inventory file.\n"
"Error: must specify local path or URL to an inventory file.",
file=sys.stderr)
sys.exit(1)
class MockConfig:
... | [
"def",
"inspect_main",
"(",
"argv",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"if",
"len",
"(",
"argv",
")",
"<",
"1",
":",
"print",
"(",
"\"Print out an inventory file.\\n\"",
"\"Error: must specify local path or URL to an inventory file.\"",
",",
"fi... | [
407,
0
] | [
440,
40
] | python | en | ['en', 'en', 'en'] | True |
get_multi_stage_outputs | (outputs,
outputs_flip,
num_joints,
with_heatmaps,
with_ae,
tag_per_joint=True,
flip_index=None,
project2image=True,
... | Inference the model to get multi-stage outputs (heatmaps & tags), and
resize them to base sizes.
Args:
outputs (list(torch.Tensor)): Outputs of network
outputs_flip (list(torch.Tensor)): Flip outputs of network
num_joints (int): Number of joints
with_heatmaps (list[bool]): Optio... | Inference the model to get multi-stage outputs (heatmaps & tags), and
resize them to base sizes. | def get_multi_stage_outputs(outputs,
outputs_flip,
num_joints,
with_heatmaps,
with_ae,
tag_per_joint=True,
flip_index=None,
... | [
"def",
"get_multi_stage_outputs",
"(",
"outputs",
",",
"outputs_flip",
",",
"num_joints",
",",
"with_heatmaps",
",",
"with_ae",
",",
"tag_per_joint",
"=",
"True",
",",
"flip_index",
"=",
"None",
",",
"project2image",
"=",
"True",
",",
"size_projected",
"=",
"Non... | [
7,
0
] | [
119,
34
] | python | en | ['en', 'en', 'en'] | True |
aggregate_results | (scale,
aggregated_heatmaps,
tags_list,
heatmaps,
tags,
test_scale_factor,
project2image,
flip_test,
align_corners=False) | Aggregate multi-scale outputs.
Note:
batch size: N
keypoints num : K
heatmap width: W
heatmap height: H
Args:
scale (int): current scale
aggregated_heatmaps (torch.Tensor | None): Aggregated heatmaps.
tags_list (list(torch.Tensor)): Tags list of previous... | Aggregate multi-scale outputs. | def aggregate_results(scale,
aggregated_heatmaps,
tags_list,
heatmaps,
tags,
test_scale_factor,
project2image,
flip_test,
align_corners=False):
... | [
"def",
"aggregate_results",
"(",
"scale",
",",
"aggregated_heatmaps",
",",
"tags_list",
",",
"heatmaps",
",",
"tags",
",",
"test_scale_factor",
",",
"project2image",
",",
"flip_test",
",",
"align_corners",
"=",
"False",
")",
":",
"if",
"scale",
"==",
"1",
"or"... | [
122,
0
] | [
183,
41
] | python | en | ['en', 'it', 'en'] | True |
get_group_preds | (grouped_joints,
center,
scale,
heatmap_size,
use_udp=False) | Transform the grouped joints back to the image.
Args:
grouped_joints (list): Grouped person joints.
center (np.ndarray[2, ]): Center of the bounding box (x, y).
scale (np.ndarray[2, ]): Scale of the bounding box
wrt [width, height].
heatmap_size (np.ndarray[2, ]): Size o... | Transform the grouped joints back to the image. | def get_group_preds(grouped_joints,
center,
scale,
heatmap_size,
use_udp=False):
"""Transform the grouped joints back to the image.
Args:
grouped_joints (list): Grouped person joints.
center (np.ndarray[2, ]): Cente... | [
"def",
"get_group_preds",
"(",
"grouped_joints",
",",
"center",
",",
"scale",
",",
"heatmap_size",
",",
"use_udp",
"=",
"False",
")",
":",
"if",
"use_udp",
":",
"if",
"grouped_joints",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
">",
"0",
":",
"heatmap... | [
186,
0
] | [
223,
18
] | python | en | ['en', 'en', 'en'] | True |
StatScores.update | (self, preds: torch.Tensor, target: torch.Tensor) |
Update state with predictions and targets. See :ref:`extensions/metrics:input types` for more information
on input types.
Args:
preds: Predictions from model (probabilities or labels)
target: Ground truth values
|
Update state with predictions and targets. See :ref:`extensions/metrics:input types` for more information
on input types. | def update(self, preds: torch.Tensor, target: torch.Tensor):
"""
Update state with predictions and targets. See :ref:`extensions/metrics:input types` for more information
on input types.
Args:
preds: Predictions from model (probabilities or labels)
target: Ground... | [
"def",
"update",
"(",
"self",
",",
"preds",
":",
"torch",
".",
"Tensor",
",",
"target",
":",
"torch",
".",
"Tensor",
")",
":",
"tp",
",",
"fp",
",",
"tn",
",",
"fn",
"=",
"_stat_scores_update",
"(",
"preds",
",",
"target",
",",
"reduce",
"=",
"self... | [
175,
4
] | [
207,
30
] | 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.