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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
require_jinja2 | (test_func) |
Decorator to enable a Jinja2 template engine in addition to the regular
Django template engine for a test or skip it if Jinja2 isn't available.
|
Decorator to enable a Jinja2 template engine in addition to the regular
Django template engine for a test or skip it if Jinja2 isn't available.
| def require_jinja2(test_func):
"""
Decorator to enable a Jinja2 template engine in addition to the regular
Django template engine for a test or skip it if Jinja2 isn't available.
"""
test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func)
test_func = override_settings(TEMPLATE... | [
"def",
"require_jinja2",
"(",
"test_func",
")",
":",
"test_func",
"=",
"skipIf",
"(",
"jinja2",
"is",
"None",
",",
"\"this test requires jinja2\"",
")",
"(",
"test_func",
")",
"test_func",
"=",
"override_settings",
"(",
"TEMPLATES",
"=",
"[",
"{",
"'BACKEND'",
... | [
806,
0
] | [
820,
20
] | python | en | ['en', 'error', 'th'] | False |
tag | (*tags) |
Decorator to add tags to a test class or method.
|
Decorator to add tags to a test class or method.
| def tag(*tags):
"""
Decorator to add tags to a test class or method.
"""
def decorator(obj):
setattr(obj, 'tags', set(tags))
return obj
return decorator | [
"def",
"tag",
"(",
"*",
"tags",
")",
":",
"def",
"decorator",
"(",
"obj",
")",
":",
"setattr",
"(",
"obj",
",",
"'tags'",
",",
"set",
"(",
"tags",
")",
")",
"return",
"obj",
"return",
"decorator"
] | [
885,
0
] | [
892,
20
] | python | en | ['en', 'error', 'th'] | False |
ContextList.keys | (self) |
Flattened keys of subcontexts.
|
Flattened keys of subcontexts.
| def keys(self):
"""
Flattened keys of subcontexts.
"""
keys = set()
for subcontext in self:
for dict in subcontext:
keys |= set(dict.keys())
return keys | [
"def",
"keys",
"(",
"self",
")",
":",
"keys",
"=",
"set",
"(",
")",
"for",
"subcontext",
"in",
"self",
":",
"for",
"dict",
"in",
"subcontext",
":",
"keys",
"|=",
"set",
"(",
"dict",
".",
"keys",
"(",
")",
")",
"return",
"keys"
] | [
89,
4
] | [
97,
19
] | python | en | ['en', 'error', 'th'] | False |
guess_content_type | (filename, default="application/octet-stream") |
Guess the "Content-Type" of a file.
:param filename:
The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
If no "Content-Type" can be guessed, default to `default`.
|
Guess the "Content-Type" of a file. | def guess_content_type(filename, default="application/octet-stream"):
"""
Guess the "Content-Type" of a file.
:param filename:
The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
If no "Content-Type" can be guessed, default to `default`.
"""
if fi... | [
"def",
"guess_content_type",
"(",
"filename",
",",
"default",
"=",
"\"application/octet-stream\"",
")",
":",
"if",
"filename",
":",
"return",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"[",
"0",
"]",
"or",
"default",
"return",
"default"
] | [
9,
0
] | [
20,
18
] | python | en | ['en', 'error', 'th'] | False |
format_header_param_rfc2231 | (name, value) |
Helper function to format and quote a single header parameter using the
strategy defined in RFC 2231.
Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows
`RFC 2388 Section 4.4 <https://tools.ietf.org/html/rfc2388#section-4.4>`_.
:param... |
Helper function to format and quote a single header parameter using the
strategy defined in RFC 2231. | def format_header_param_rfc2231(name, value):
"""
Helper function to format and quote a single header parameter using the
strategy defined in RFC 2231.
Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows
`RFC 2388 Section 4.4 <https://to... | [
"def",
"format_header_param_rfc2231",
"(",
"name",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"binary_type",
")",
":",
"value",
"=",
"value",
".",
"decode",
"(",
"\"utf-8\"",
")",
"if",
"not",
"any",
"(",
"ch",
"in",
"va... | [
23,
0
] | [
62,
16
] | python | en | ['en', 'error', 'th'] | False |
format_header_param_html5 | (name, value) |
Helper function to format and quote a single header parameter using the
HTML5 strategy.
Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows the `HTML5 Working Draft
Section 4.10.22.7`_ and matches the behavior of curl and modern browsers.
... |
Helper function to format and quote a single header parameter using the
HTML5 strategy. | def format_header_param_html5(name, value):
"""
Helper function to format and quote a single header parameter using the
HTML5 strategy.
Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows the `HTML5 Working Draft
Section 4.10.22.7`_ and ... | [
"def",
"format_header_param_html5",
"(",
"name",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"binary_type",
")",
":",
"value",
"=",
"value",
".",
"decode",
"(",
"\"utf-8\"",
")",
"value",
"=",
"_replace_multiple",
"(",
"value... | [
94,
0
] | [
118,
37
] | python | en | ['en', 'error', 'th'] | False |
RequestField.from_tuples | (cls, fieldname, value, header_formatter=format_header_param_html5) |
A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
Supports constructing :class:`~urllib3.fields.RequestField` from
parameter of key/value strings AND key/filetuple. A filetuple is a
(filename, data, MIME type) tuple where the MIME type is optional.
... |
A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. | def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5):
"""
A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
Supports constructing :class:`~urllib3.fields.RequestField` from
parameter of key/value strings AND key/filetuple. A f... | [
"def",
"from_tuples",
"(",
"cls",
",",
"fieldname",
",",
"value",
",",
"header_formatter",
"=",
"format_header_param_html5",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"if",
"len",
"(",
"value",
")",
"==",
"3",
":",
"filename",
"... | [
159,
4
] | [
192,
28
] | python | en | ['en', 'error', 'th'] | False |
RequestField._render_part | (self, name, value) |
Overridable helper function to format a single header parameter. By
default, this calls ``self.header_formatter``.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string.... |
Overridable helper function to format a single header parameter. By
default, this calls ``self.header_formatter``. | def _render_part(self, name, value):
"""
Overridable helper function to format a single header parameter. By
default, this calls ``self.header_formatter``.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value... | [
"def",
"_render_part",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"return",
"self",
".",
"header_formatter",
"(",
"name",
",",
"value",
")"
] | [
194,
4
] | [
205,
49
] | python | en | ['en', 'error', 'th'] | False |
RequestField._render_parts | (self, header_parts) |
Helper function to format and quote a single header.
Useful for single headers that are composed of multiple items. E.g.,
'Content-Disposition' fields.
:param header_parts:
A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
as `k1="v1"; k2="v2";... |
Helper function to format and quote a single header. | def _render_parts(self, header_parts):
"""
Helper function to format and quote a single header.
Useful for single headers that are composed of multiple items. E.g.,
'Content-Disposition' fields.
:param header_parts:
A sequence of (k, v) tuples or a :class:`dict` of ... | [
"def",
"_render_parts",
"(",
"self",
",",
"header_parts",
")",
":",
"parts",
"=",
"[",
"]",
"iterable",
"=",
"header_parts",
"if",
"isinstance",
"(",
"header_parts",
",",
"dict",
")",
":",
"iterable",
"=",
"header_parts",
".",
"items",
"(",
")",
"for",
"... | [
207,
4
] | [
227,
32
] | python | en | ['en', 'error', 'th'] | False |
RequestField.render_headers | (self) |
Renders the headers for this request field.
|
Renders the headers for this request field.
| def render_headers(self):
"""
Renders the headers for this request field.
"""
lines = []
sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"]
for sort_key in sort_keys:
if self.headers.get(sort_key, False):
lines.append(u"%s... | [
"def",
"render_headers",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"sort_keys",
"=",
"[",
"\"Content-Disposition\"",
",",
"\"Content-Type\"",
",",
"\"Content-Location\"",
"]",
"for",
"sort_key",
"in",
"sort_keys",
":",
"if",
"self",
".",
"headers",
".",
... | [
229,
4
] | [
246,
34
] | python | en | ['en', 'error', 'th'] | False |
RequestField.make_multipart | (
self, content_disposition=None, content_type=None, content_location=None
) |
Makes this request field into a multipart request field.
This method overrides "Content-Disposition", "Content-Type" and
"Content-Location" headers to the request parameter.
:param content_type:
The 'Content-Type' of the request body.
:param content_location:
... |
Makes this request field into a multipart request field. | def make_multipart(
self, content_disposition=None, content_type=None, content_location=None
):
"""
Makes this request field into a multipart request field.
This method overrides "Content-Disposition", "Content-Type" and
"Content-Location" headers to the request parameter.
... | [
"def",
"make_multipart",
"(",
"self",
",",
"content_disposition",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"content_location",
"=",
"None",
")",
":",
"self",
".",
"headers",
"[",
"\"Content-Disposition\"",
"]",
"=",
"content_disposition",
"or",
"u\"fo... | [
248,
4
] | [
273,
59
] | python | en | ['en', 'error', 'th'] | False |
TestMenuRendering.test_remember_collapsed | (self) | Sidebar should render with collapsed class applied. | Sidebar should render with collapsed class applied. | def test_remember_collapsed(self):
'''Sidebar should render with collapsed class applied.'''
# Sidebar should not be collapsed
self.client.cookies['wagtail_sidebar_collapsed'] = '0'
response = self.client.get(reverse('wagtailadmin_home'))
self.assertNotContains(response, 'sidebar... | [
"def",
"test_remember_collapsed",
"(",
"self",
")",
":",
"# Sidebar should not be collapsed",
"self",
".",
"client",
".",
"cookies",
"[",
"'wagtail_sidebar_collapsed'",
"]",
"=",
"'0'",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"reverse",
"(",
"'w... | [
23,
4
] | [
33,
58
] | python | en | ['en', 'en', 'en'] | True |
TestMenuRendering.test_collapsed_only_with_feature_flag | (self) | Sidebar should only remember its collapsed state with the right feature flag set. | Sidebar should only remember its collapsed state with the right feature flag set. | def test_collapsed_only_with_feature_flag(self):
'''Sidebar should only remember its collapsed state with the right feature flag set.'''
# Sidebar should not be collapsed because the feature flag is not enabled
self.client.cookies['wagtail_sidebar_collapsed'] = '1'
response = self.client... | [
"def",
"test_collapsed_only_with_feature_flag",
"(",
"self",
")",
":",
"# Sidebar should not be collapsed because the feature flag is not enabled",
"self",
".",
"client",
".",
"cookies",
"[",
"'wagtail_sidebar_collapsed'",
"]",
"=",
"'1'",
"response",
"=",
"self",
".",
"cli... | [
36,
4
] | [
41,
61
] | python | en | ['en', 'en', 'en'] | True |
conv_output_length | (input_length, filter_size, stride, pad=0) | Helper function to compute the output size of a convolution operation
This function computes the length along a single axis, which corresponds
to a 1D convolution. It can also be used for convolutions with higher
dimensionalities by using it individually for each axis.
Parameters
----------
inpu... | Helper function to compute the output size of a convolution operation
This function computes the length along a single axis, which corresponds
to a 1D convolution. It can also be used for convolutions with higher
dimensionalities by using it individually for each axis.
Parameters
----------
inpu... | def conv_output_length(input_length, filter_size, stride, pad=0):
"""Helper function to compute the output size of a convolution operation
This function computes the length along a single axis, which corresponds
to a 1D convolution. It can also be used for convolutions with higher
dimensionalities by us... | [
"def",
"conv_output_length",
"(",
"input_length",
",",
"filter_size",
",",
"stride",
",",
"pad",
"=",
"0",
")",
":",
"if",
"input_length",
"is",
"None",
":",
"return",
"None",
"if",
"pad",
"==",
"'valid'",
":",
"output_length",
"=",
"input_length",
"-",
"f... | [
59,
0
] | [
113,
24
] | python | en | ['en', 'en', 'en'] | True |
get_all_layers | (layer, treat_as_input=None) |
:type layer: Layer | list[Layer]
:rtype: list[Layer]
|
:type layer: Layer | list[Layer]
:rtype: list[Layer]
| def get_all_layers(layer, treat_as_input=None):
"""
:type layer: Layer | list[Layer]
:rtype: list[Layer]
"""
# We perform a depth-first search. We add a layer to the result list only
# after adding all its incoming layers (if any) or when detecting a cycle.
# We use a LIFO stack to avoid eve... | [
"def",
"get_all_layers",
"(",
"layer",
",",
"treat_as_input",
"=",
"None",
")",
":",
"# We perform a depth-first search. We add a layer to the result list only",
"# after adding all its incoming layers (if any) or when detecting a cycle.",
"# We use a LIFO stack to avoid ever running into re... | [
1681,
0
] | [
1726,
17
] | python | en | ['en', 'error', 'th'] | False |
unique | (l) | Filters duplicates of iterable.
Create a new list from l with duplicate entries removed,
while preserving the original order.
Parameters
----------
l : iterable
Input iterable to filter of duplicates.
Returns
-------
list
A list of elements of `l` without duplicates and i... | Filters duplicates of iterable.
Create a new list from l with duplicate entries removed,
while preserving the original order.
Parameters
----------
l : iterable
Input iterable to filter of duplicates.
Returns
-------
list
A list of elements of `l` without duplicates and i... | def unique(l):
"""Filters duplicates of iterable.
Create a new list from l with duplicate entries removed,
while preserving the original order.
Parameters
----------
l : iterable
Input iterable to filter of duplicates.
Returns
-------
list
A list of elements of `l` wi... | [
"def",
"unique",
"(",
"l",
")",
":",
"new_list",
"=",
"[",
"]",
"seen",
"=",
"set",
"(",
")",
"for",
"el",
"in",
"l",
":",
"if",
"el",
"not",
"in",
"seen",
":",
"new_list",
".",
"append",
"(",
"el",
")",
"seen",
".",
"add",
"(",
"el",
")",
... | [
1895,
0
] | [
1915,
19
] | python | en | ['en', 'en', 'en'] | True |
get_all_params | (layer, **tags) |
:type layer: Layer|list[Layer]
|
:type layer: Layer|list[Layer]
| def get_all_params(layer, **tags):
"""
:type layer: Layer|list[Layer]
"""
layers = get_all_layers(layer)
params = chain.from_iterable(l.get_params(**tags) for l in layers)
return unique(params) | [
"def",
"get_all_params",
"(",
"layer",
",",
"*",
"*",
"tags",
")",
":",
"layers",
"=",
"get_all_layers",
"(",
"layer",
")",
"params",
"=",
"chain",
".",
"from_iterable",
"(",
"l",
".",
"get_params",
"(",
"*",
"*",
"tags",
")",
"for",
"l",
"in",
"laye... | [
1918,
0
] | [
1924,
25
] | python | en | ['en', 'error', 'th'] | False |
BaseConvLayer.__init__ | (self, incoming, num_filters, filter_size, stride=1, pad="VALID",
untie_biases=False,
W=XavierUniformInitializer(), b=tf.zeros_initializer(),
nonlinearity=tf.nn.relu, n=None, **kwargs) |
Input is assumed to be of shape batch*height*width*channels
|
Input is assumed to be of shape batch*height*width*channels
| def __init__(self, incoming, num_filters, filter_size, stride=1, pad="VALID",
untie_biases=False,
W=XavierUniformInitializer(), b=tf.zeros_initializer(),
nonlinearity=tf.nn.relu, n=None, **kwargs):
"""
Input is assumed to be of shape batch*height*width*... | [
"def",
"__init__",
"(",
"self",
",",
"incoming",
",",
"num_filters",
",",
"filter_size",
",",
"stride",
"=",
"1",
",",
"pad",
"=",
"\"VALID\"",
",",
"untie_biases",
"=",
"False",
",",
"W",
"=",
"XavierUniformInitializer",
"(",
")",
",",
"b",
"=",
"tf",
... | [
459,
4
] | [
501,
56
] | python | en | ['en', 'error', 'th'] | False |
BaseConvLayer.get_W_shape | (self) | Get the shape of the weight matrix `W`.
Returns
-------
tuple of int
The shape of the weight matrix.
| Get the shape of the weight matrix `W`.
Returns
-------
tuple of int
The shape of the weight matrix.
| def get_W_shape(self):
"""Get the shape of the weight matrix `W`.
Returns
-------
tuple of int
The shape of the weight matrix.
"""
num_input_channels = self.input_shape[-1]
return self.filter_size + (num_input_channels, self.num_filters) | [
"def",
"get_W_shape",
"(",
"self",
")",
":",
"num_input_channels",
"=",
"self",
".",
"input_shape",
"[",
"-",
"1",
"]",
"return",
"self",
".",
"filter_size",
"+",
"(",
"num_input_channels",
",",
"self",
".",
"num_filters",
")"
] | [
503,
4
] | [
511,
72
] | python | en | ['en', 'en', 'en'] | True |
BaseConvLayer.convolve | (self, input, **kwargs) |
Symbolically convolves `input` with ``self.W``, producing an output of
shape ``self.output_shape``. To be implemented by subclasses.
Parameters
----------
input : Theano tensor
The input minibatch to convolve
**kwargs
Any additional keyword argume... |
Symbolically convolves `input` with ``self.W``, producing an output of
shape ``self.output_shape``. To be implemented by subclasses.
Parameters
----------
input : Theano tensor
The input minibatch to convolve
**kwargs
Any additional keyword argume... | def convolve(self, input, **kwargs):
"""
Symbolically convolves `input` with ``self.W``, producing an output of
shape ``self.output_shape``. To be implemented by subclasses.
Parameters
----------
input : Theano tensor
The input minibatch to convolve
**... | [
"def",
"convolve",
"(",
"self",
",",
"input",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"BaseConvLayer does not implement the \"",
"\"convolve() method. You will want to \"",
"\"use a subclass such as Conv2DLayer.\"",
")"
] | [
544,
4
] | [
562,
72
] | python | en | ['en', 'error', 'th'] | False |
DropoutLayer.__init__ | (self, incoming, p, rescale=False, **kwargs) |
:param p: probability of setting the output of a node to 0. Should be a tf placeholder
|
:param p: probability of setting the output of a node to 0. Should be a tf placeholder
| def __init__(self, incoming, p, rescale=False, **kwargs):
"""
:param p: probability of setting the output of a node to 0. Should be a tf placeholder
"""
super(DropoutLayer, self).__init__(incoming, **kwargs)
self.p = p
self.rescale = rescale | [
"def",
"__init__",
"(",
"self",
",",
"incoming",
",",
"p",
",",
"rescale",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"DropoutLayer",
",",
"self",
")",
".",
"__init__",
"(",
"incoming",
",",
"*",
"*",
"kwargs",
")",
"self",
".",... | [
709,
4
] | [
715,
30
] | python | en | ['en', 'error', 'th'] | False |
DropoutLayer.get_output_for | (self, input, deterministic=False, **kwargs) |
Parameters
----------
input : tensor
output from the previous layer
deterministic : bool
If true dropout and scaling is disabled, see notes
|
Parameters
----------
input : tensor
output from the previous layer
deterministic : bool
If true dropout and scaling is disabled, see notes
| def get_output_for(self, input, deterministic=False, **kwargs):
"""
Parameters
----------
input : tensor
output from the previous layer
deterministic : bool
If true dropout and scaling is disabled, see notes
"""
if deterministic or self.p =... | [
"def",
"get_output_for",
"(",
"self",
",",
"input",
",",
"deterministic",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"deterministic",
"or",
"self",
".",
"p",
"==",
"0",
":",
"return",
"input",
"else",
":",
"# I don't know what this is for. Tensor... | [
717,
4
] | [
735,
62
] | python | en | ['en', 'error', 'th'] | False |
LSTMLayer.step | (self, hcprev, x) |
Incoming gate: i(t) = f_i(x(t) @ W_xi + h(t-1) @ W_hi + w_ci * c(t-1) + b_i)
Forget gate: f(t) = f_f(x(t) @ W_xf + h(t-1) @ W_hf + w_cf * c(t-1) + b_f)
Cell gate: c(t) = f(t) * c(t - 1) + i(t) * f_c(x(t) @ W_xc + h(t-1) @ W_hc + b_c)
Out gate: ... |
Incoming gate: i(t) = f_i(x(t) | def step(self, hcprev, x):
"""
Incoming gate: i(t) = f_i(x(t) @ W_xi + h(t-1) @ W_hi + w_ci * c(t-1) + b_i)
Forget gate: f(t) = f_f(x(t) @ W_xf + h(t-1) @ W_hf + w_cf * c(t-1) + b_f)
Cell gate: c(t) = f(t) * c(t - 1) + i(t) * f_c(x(t) @ W_xc + h(t-1) @ W_hc ... | [
"def",
"step",
"(",
"self",
",",
"hcprev",
",",
"x",
")",
":",
"hprev",
"=",
"hcprev",
"[",
":",
",",
":",
"self",
".",
"num_units",
"]",
"cprev",
"=",
"hcprev",
"[",
":",
",",
"self",
".",
"num_units",
":",
"]",
"if",
"self",
".",
"layer_normali... | [
1494,
4
] | [
1529,
47
] | python | en | ['en', 'error', 'th'] | False |
glob | (pathname, recursive=False) | Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files ... | Return a list of paths matching a pathname pattern. | def glob(pathname, recursive=False):
"""Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is ... | [
"def",
"glob",
"(",
"pathname",
",",
"recursive",
"=",
"False",
")",
":",
"return",
"list",
"(",
"iglob",
"(",
"pathname",
",",
"recursive",
"=",
"recursive",
")",
")"
] | [
15,
0
] | [
26,
53
] | python | en | ['en', 'en', 'en'] | True |
iglob | (pathname, recursive=False) | Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' wi... | Return an iterator which yields the paths matching a pathname pattern. | def iglob(pathname, recursive=False):
"""Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
... | [
"def",
"iglob",
"(",
"pathname",
",",
"recursive",
"=",
"False",
")",
":",
"it",
"=",
"_iglob",
"(",
"pathname",
",",
"recursive",
")",
"if",
"recursive",
"and",
"_isrecursive",
"(",
"pathname",
")",
":",
"s",
"=",
"next",
"(",
"it",
")",
"# skip empty... | [
29,
0
] | [
44,
13
] | python | en | ['en', 'en', 'en'] | True |
escape | (pathname) | Escape all special characters.
| Escape all special characters.
| def escape(pathname):
"""Escape all special characters.
"""
# Escaping is done by wrapping any of "*?[" between square brackets.
# Metacharacters do not work in the drive part and shouldn't be escaped.
drive, pathname = os.path.splitdrive(pathname)
if isinstance(pathname, bytes):
pathnam... | [
"def",
"escape",
"(",
"pathname",
")",
":",
"# Escaping is done by wrapping any of \"*?[\" between square brackets.",
"# Metacharacters do not work in the drive part and shouldn't be escaped.",
"drive",
",",
"pathname",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"pathname",
... | [
163,
0
] | [
173,
27
] | python | en | ['en', 'en', 'en'] | True |
format_command_result | (
command_args, # type: List[str]
command_output, # type: Text
) | Format command information for logging. | Format command information for logging. | def format_command_result(
command_args, # type: List[str]
command_output, # type: Text
):
# type: (...) -> str
"""Format command information for logging."""
command_desc = format_command_args(command_args)
text = 'Command arguments: {}\n'.format(command_desc)
if not command_output:
... | [
"def",
"format_command_result",
"(",
"command_args",
",",
"# type: List[str]",
"command_output",
",",
"# type: Text",
")",
":",
"# type: (...) -> str",
"command_desc",
"=",
"format_command_args",
"(",
"command_args",
")",
"text",
"=",
"'Command arguments: {}\\n'",
".",
"f... | [
18,
0
] | [
36,
15
] | python | en | ['en', 'da', 'en'] | True |
get_legacy_build_wheel_path | (
names, # type: List[str]
temp_dir, # type: str
name, # type: str
command_args, # type: List[str]
command_output, # type: Text
) | Return the path to the wheel in the temporary build directory. | Return the path to the wheel in the temporary build directory. | def get_legacy_build_wheel_path(
names, # type: List[str]
temp_dir, # type: str
name, # type: str
command_args, # type: List[str]
command_output, # type: Text
):
# type: (...) -> Optional[str]
"""Return the path to the wheel in the temporary build directory."""
# Sort for determinis... | [
"def",
"get_legacy_build_wheel_path",
"(",
"names",
",",
"# type: List[str]",
"temp_dir",
",",
"# type: str",
"name",
",",
"# type: str",
"command_args",
",",
"# type: List[str]",
"command_output",
",",
"# type: Text",
")",
":",
"# type: (...) -> Optional[str]",
"# Sort for... | [
39,
0
] | [
66,
43
] | python | en | ['en', 'en', 'en'] | True |
build_wheel_legacy | (
name, # type: str
setup_py_path, # type: str
source_dir, # type: str
global_options, # type: List[str]
build_options, # type: List[str]
tempd, # type: str
) | Build one unpacked package using the "legacy" build process.
Returns path to wheel if successfully built. Otherwise, returns None.
| Build one unpacked package using the "legacy" build process. | def build_wheel_legacy(
name, # type: str
setup_py_path, # type: str
source_dir, # type: str
global_options, # type: List[str]
build_options, # type: List[str]
tempd, # type: str
):
# type: (...) -> Optional[str]
"""Build one unpacked package using the "legacy" build process.
... | [
"def",
"build_wheel_legacy",
"(",
"name",
",",
"# type: str",
"setup_py_path",
",",
"# type: str",
"source_dir",
",",
"# type: str",
"global_options",
",",
"# type: List[str]",
"build_options",
",",
"# type: List[str]",
"tempd",
",",
"# type: str",
")",
":",
"# type: (.... | [
69,
0
] | [
112,
25
] | python | en | ['en', 'en', 'en'] | True |
Deserializer | (stream_or_string, **options) |
Deserialize a stream or string of JSON data.
|
Deserialize a stream or string of JSON data.
| def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
if not isinstance(stream_or_string, (bytes, six.string_types)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.d... | [
"def",
"Deserializer",
"(",
"stream_or_string",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"isinstance",
"(",
"stream_or_string",
",",
"(",
"bytes",
",",
"six",
".",
"string_types",
")",
")",
":",
"stream_or_string",
"=",
"stream_or_string",
".",
"read... | [
70,
0
] | [
86,
85
] | python | en | ['en', 'error', 'th'] | False |
import_string | (dotted_path) |
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
|
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
| def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look ... | [
"def",
"import_string",
"(",
"dotted_path",
")",
":",
"try",
":",
"module_path",
",",
"class_name",
"=",
"dotted_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":",
"msg",
"=",
"\"%s doesn't look like a module path\"",
"%",
"dotted_path... | [
8,
0
] | [
26,
69
] | python | en | ['en', 'error', 'th'] | False |
autodiscover_modules | (*args, **kwargs) |
Auto-discover INSTALLED_APPS modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
You may provide a register_to keyword parameter as a way to access a
registry. This register_to object must have a _registry instance variable
to acc... |
Auto-discover INSTALLED_APPS modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want. | def autodiscover_modules(*args, **kwargs):
"""
Auto-discover INSTALLED_APPS modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
You may provide a register_to keyword parameter as a way to access a
registry. This register_to object ... | [
"def",
"autodiscover_modules",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"apps",
"import",
"apps",
"register_to",
"=",
"kwargs",
".",
"get",
"(",
"'register_to'",
")",
"for",
"app_config",
"in",
"apps",
".",
"get_app_confi... | [
29,
0
] | [
62,
25
] | python | en | ['en', 'error', 'th'] | False |
module_dir | (module) |
Find the name of the directory that contains a module, if possible.
Raise ValueError otherwise, e.g. for namespace packages that are split
over several directories.
|
Find the name of the directory that contains a module, if possible. | def module_dir(module):
"""
Find the name of the directory that contains a module, if possible.
Raise ValueError otherwise, e.g. for namespace packages that are split
over several directories.
"""
# Convert to list because _NamespacePath does not support indexing on 3.3.
paths = list(getatt... | [
"def",
"module_dir",
"(",
"module",
")",
":",
"# Convert to list because _NamespacePath does not support indexing on 3.3.",
"paths",
"=",
"list",
"(",
"getattr",
"(",
"module",
",",
"'__path__'",
",",
"[",
"]",
")",
")",
"if",
"len",
"(",
"paths",
")",
"==",
"1"... | [
149,
0
] | [
164,
73
] | python | en | ['en', 'error', 'th'] | False |
Clip.make_labels | (self, values) | Creates widgets from raw clipboard i.e. for each character in the
list that is provided by Clipboard.paste()
| Creates widgets from raw clipboard i.e. for each character in the
list that is provided by Clipboard.paste()
| def make_labels(self, values):
"""Creates widgets from raw clipboard i.e. for each character in the
list that is provided by Clipboard.paste()
"""
print(repr(values))
for value in values:
label = Label(text=value, size_hint_y=None, height=30)
self.ids.cont... | [
"def",
"make_labels",
"(",
"self",
",",
"values",
")",
":",
"print",
"(",
"repr",
"(",
"values",
")",
")",
"for",
"value",
"in",
"values",
":",
"label",
"=",
"Label",
"(",
"text",
"=",
"value",
",",
"size_hint_y",
"=",
"None",
",",
"height",
"=",
"... | [
43,
4
] | [
50,
48
] | python | en | ['en', 'en', 'en'] | True |
Clip.make_pretty_labels | (self, values) | Creates widgets from a list of values made by splitting clipboard
by the default OS line separator. Useful when copying columns of data.
| Creates widgets from a list of values made by splitting clipboard
by the default OS line separator. Useful when copying columns of data.
| def make_pretty_labels(self, values):
"""Creates widgets from a list of values made by splitting clipboard
by the default OS line separator. Useful when copying columns of data.
"""
print(repr(values))
for value in values.split(os.linesep):
label = Label(text=value, s... | [
"def",
"make_pretty_labels",
"(",
"self",
",",
"values",
")",
":",
"print",
"(",
"repr",
"(",
"values",
")",
")",
"for",
"value",
"in",
"values",
".",
"split",
"(",
"os",
".",
"linesep",
")",
":",
"label",
"=",
"Label",
"(",
"text",
"=",
"value",
"... | [
52,
4
] | [
59,
48
] | python | en | ['en', 'en', 'en'] | True |
all_frames | (im, func=None) |
Applies a given function to all frames in an image or a list of images.
The frames are returned as a list of separate images.
:param im: An image, or a list of images.
:param func: The function to apply to all of the image frames.
:returns: A list of images.
|
Applies a given function to all frames in an image or a list of images.
The frames are returned as a list of separate images. | def all_frames(im, func=None):
"""
Applies a given function to all frames in an image or a list of images.
The frames are returned as a list of separate images.
:param im: An image, or a list of images.
:param func: The function to apply to all of the image frames.
:returns: A list of images.
... | [
"def",
"all_frames",
"(",
"im",
",",
"func",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"im",
",",
"list",
")",
":",
"im",
"=",
"[",
"im",
"]",
"ims",
"=",
"[",
"]",
"for",
"imSequence",
"in",
"im",
":",
"current",
"=",
"imSequence",
... | [
55,
0
] | [
74,
52
] | python | en | ['en', 'error', 'th'] | False |
PostGISAdapter.__init__ | (self, obj, geography=False) |
Initialize on the spatial object.
|
Initialize on the spatial object.
| def __init__(self, obj, geography=False):
"""
Initialize on the spatial object.
"""
self.is_geometry = isinstance(obj, (Geometry, PostGISAdapter))
# Getting the WKB (in string form, to allow easy pickling of
# the adaptor) and the SRID from the geometry or raster.
... | [
"def",
"__init__",
"(",
"self",
",",
"obj",
",",
"geography",
"=",
"False",
")",
":",
"self",
".",
"is_geometry",
"=",
"isinstance",
"(",
"obj",
",",
"(",
"Geometry",
",",
"PostGISAdapter",
")",
")",
"# Getting the WKB (in string form, to allow easy pickling of",
... | [
13,
4
] | [
28,
34
] | python | en | ['en', 'error', 'th'] | False |
PostGISAdapter.prepare | (self, conn) |
This method allows escaping the binary in the style required by the
server's `standard_conforming_string` setting.
|
This method allows escaping the binary in the style required by the
server's `standard_conforming_string` setting.
| def prepare(self, conn):
"""
This method allows escaping the binary in the style required by the
server's `standard_conforming_string` setting.
"""
if self.is_geometry:
self._adapter.prepare(conn) | [
"def",
"prepare",
"(",
"self",
",",
"conn",
")",
":",
"if",
"self",
".",
"is_geometry",
":",
"self",
".",
"_adapter",
".",
"prepare",
"(",
"conn",
")"
] | [
48,
4
] | [
54,
39
] | python | en | ['en', 'error', 'th'] | False |
PostGISAdapter.getquoted | (self) |
Return a properly quoted string for use in PostgreSQL/PostGIS.
|
Return a properly quoted string for use in PostgreSQL/PostGIS.
| def getquoted(self):
"""
Return a properly quoted string for use in PostgreSQL/PostGIS.
"""
if self.is_geometry:
# Psycopg will figure out whether to use E'\\000' or '\000'.
return str('%s(%s)' % (
'ST_GeogFromWKB' if self.geography else 'ST_GeomFr... | [
"def",
"getquoted",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_geometry",
":",
"# Psycopg will figure out whether to use E'\\\\000' or '\\000'.",
"return",
"str",
"(",
"'%s(%s)'",
"%",
"(",
"'ST_GeogFromWKB'",
"if",
"self",
".",
"geography",
"else",
"'ST_GeomFromEW... | [
56,
4
] | [
68,
45
] | python | en | ['en', 'error', 'th'] | False |
generate_user_access_token | () |
Generate a Twitter API connection with access for a specific user.
Requires the user to view the browser URI that is automatically opened,
then manually enter the pin in the command-line in order to generate
the access token.
:return: tweepy.OAuthHandler instance, with User Access Token set.
|
Generate a Twitter API connection with access for a specific user. | def generate_user_access_token():
"""
Generate a Twitter API connection with access for a specific user.
Requires the user to view the browser URI that is automatically opened,
then manually enter the pin in the command-line in order to generate
the access token.
:return: tweepy.OAuthHandler i... | [
"def",
"generate_user_access_token",
"(",
")",
":",
"auth",
"=",
"tweepy",
".",
"OAuthHandler",
"(",
"CONSUMER_KEY",
",",
"CONSUMER_SECRET",
")",
"print",
"(",
"\"You need to authorize the application. Opening page in browser...\\n\"",
")",
"auth_url",
"=",
"auth",
".",
... | [
10,
0
] | [
34,
15
] | python | en | ['en', 'error', 'th'] | False |
fix_upload_links | (data: TableData, message_table: TableName) |
Because the URLs for uploaded files encode the realm ID of the
organization being imported (which is only determined at import
time), we need to rewrite the URLs of links to uploaded files
during the import process.
|
Because the URLs for uploaded files encode the realm ID of the
organization being imported (which is only determined at import
time), we need to rewrite the URLs of links to uploaded files
during the import process.
| def fix_upload_links(data: TableData, message_table: TableName) -> None:
"""
Because the URLs for uploaded files encode the realm ID of the
organization being imported (which is only determined at import
time), we need to rewrite the URLs of links to uploaded files
during the import process.
"""... | [
"def",
"fix_upload_links",
"(",
"data",
":",
"TableData",
",",
"message_table",
":",
"TableName",
")",
"->",
"None",
":",
"for",
"message",
"in",
"data",
"[",
"message_table",
"]",
":",
"if",
"message",
"[",
"\"has_attachment\"",
"]",
"is",
"True",
":",
"f... | [
158,
0
] | [
173,
25
] | python | en | ['en', 'error', 'th'] | False |
create_subscription_events | (data: TableData, realm_id: int) |
When the export data doesn't contain the table `zerver_realmauditlog`,
this function creates RealmAuditLog objects for `subscription_created`
type event for all the existing Stream subscriptions.
This is needed for all the export tools which do not include the
table `zerver_realmauditlog` (Slack, ... |
When the export data doesn't contain the table `zerver_realmauditlog`,
this function creates RealmAuditLog objects for `subscription_created`
type event for all the existing Stream subscriptions. | def create_subscription_events(data: TableData, realm_id: int) -> None:
"""
When the export data doesn't contain the table `zerver_realmauditlog`,
this function creates RealmAuditLog objects for `subscription_created`
type event for all the existing Stream subscriptions.
This is needed for all the ... | [
"def",
"create_subscription_events",
"(",
"data",
":",
"TableData",
",",
"realm_id",
":",
"int",
")",
"->",
"None",
":",
"all_subscription_logs",
"=",
"[",
"]",
"event_last_message_id",
"=",
"get_last_message_id",
"(",
")",
"event_time",
"=",
"timezone_now",
"(",
... | [
176,
0
] | [
216,
60
] | python | en | ['en', 'error', 'th'] | False |
fix_service_tokens | (data: TableData, table: TableName) |
The tokens in the services are created by 'generate_api_key'.
As the tokens are unique, they should be re-created for the imports.
|
The tokens in the services are created by 'generate_api_key'.
As the tokens are unique, they should be re-created for the imports.
| def fix_service_tokens(data: TableData, table: TableName) -> None:
"""
The tokens in the services are created by 'generate_api_key'.
As the tokens are unique, they should be re-created for the imports.
"""
for item in data[table]:
item["token"] = generate_api_key() | [
"def",
"fix_service_tokens",
"(",
"data",
":",
"TableData",
",",
"table",
":",
"TableName",
")",
"->",
"None",
":",
"for",
"item",
"in",
"data",
"[",
"table",
"]",
":",
"item",
"[",
"\"token\"",
"]",
"=",
"generate_api_key",
"(",
")"
] | [
219,
0
] | [
225,
42
] | python | en | ['en', 'error', 'th'] | False |
process_huddle_hash | (data: TableData, table: TableName) |
Build new huddle hashes with the updated ids of the users
|
Build new huddle hashes with the updated ids of the users
| def process_huddle_hash(data: TableData, table: TableName) -> None:
"""
Build new huddle hashes with the updated ids of the users
"""
for huddle in data[table]:
user_id_list = id_map_to_list["huddle_to_user_list"][huddle["id"]]
huddle["huddle_hash"] = get_huddle_hash(user_id_list) | [
"def",
"process_huddle_hash",
"(",
"data",
":",
"TableData",
",",
"table",
":",
"TableName",
")",
"->",
"None",
":",
"for",
"huddle",
"in",
"data",
"[",
"table",
"]",
":",
"user_id_list",
"=",
"id_map_to_list",
"[",
"\"huddle_to_user_list\"",
"]",
"[",
"hudd... | [
228,
0
] | [
234,
61
] | python | en | ['en', 'error', 'th'] | False |
get_huddles_from_subscription | (data: TableData, table: TableName) |
Extract the IDs of the user_profiles involved in a huddle from the subscription object
This helps to generate a unique huddle hash from the updated user_profile ids
|
Extract the IDs of the user_profiles involved in a huddle from the subscription object
This helps to generate a unique huddle hash from the updated user_profile ids
| def get_huddles_from_subscription(data: TableData, table: TableName) -> None:
"""
Extract the IDs of the user_profiles involved in a huddle from the subscription object
This helps to generate a unique huddle hash from the updated user_profile ids
"""
id_map_to_list["huddle_to_user_list"] = {
... | [
"def",
"get_huddles_from_subscription",
"(",
"data",
":",
"TableData",
",",
"table",
":",
"TableName",
")",
"->",
"None",
":",
"id_map_to_list",
"[",
"\"huddle_to_user_list\"",
"]",
"=",
"{",
"value",
":",
"[",
"]",
"for",
"value",
"in",
"ID_MAP",
"[",
"\"re... | [
237,
0
] | [
249,
100
] | python | en | ['en', 'error', 'th'] | False |
fix_customprofilefield | (data: TableData) |
In CustomProfileField with 'field_type' like 'USER', the IDs need to be
re-mapped.
|
In CustomProfileField with 'field_type' like 'USER', the IDs need to be
re-mapped.
| def fix_customprofilefield(data: TableData) -> None:
"""
In CustomProfileField with 'field_type' like 'USER', the IDs need to be
re-mapped.
"""
field_type_USER_id_list = []
for item in data["zerver_customprofilefield"]:
if item["field_type"] == CustomProfileField.USER:
field_... | [
"def",
"fix_customprofilefield",
"(",
"data",
":",
"TableData",
")",
"->",
"None",
":",
"field_type_USER_id_list",
"=",
"[",
"]",
"for",
"item",
"in",
"data",
"[",
"\"zerver_customprofilefield\"",
"]",
":",
"if",
"item",
"[",
"\"field_type\"",
"]",
"==",
"Cust... | [
252,
0
] | [
272,
62
] | python | en | ['en', 'error', 'th'] | False |
fix_message_rendered_content | (
realm: Realm, sender_map: Dict[int, Record], messages: List[Record]
) |
This function sets the rendered_content of all the messages
after the messages have been imported from a non-Zulip platform.
|
This function sets the rendered_content of all the messages
after the messages have been imported from a non-Zulip platform.
| def fix_message_rendered_content(
realm: Realm, sender_map: Dict[int, Record], messages: List[Record]
) -> None:
"""
This function sets the rendered_content of all the messages
after the messages have been imported from a non-Zulip platform.
"""
for message in messages:
if message["rende... | [
"def",
"fix_message_rendered_content",
"(",
"realm",
":",
"Realm",
",",
"sender_map",
":",
"Dict",
"[",
"int",
",",
"Record",
"]",
",",
"messages",
":",
"List",
"[",
"Record",
"]",
")",
"->",
"None",
":",
"for",
"message",
"in",
"messages",
":",
"if",
... | [
275,
0
] | [
361,
13
] | python | en | ['en', 'error', 'th'] | False |
current_table_ids | (data: TableData, table: TableName) |
Returns the ids present in the current table
|
Returns the ids present in the current table
| def current_table_ids(data: TableData, table: TableName) -> List[int]:
"""
Returns the ids present in the current table
"""
id_list = []
for item in data[table]:
id_list.append(item["id"])
return id_list | [
"def",
"current_table_ids",
"(",
"data",
":",
"TableData",
",",
"table",
":",
"TableName",
")",
"->",
"List",
"[",
"int",
"]",
":",
"id_list",
"=",
"[",
"]",
"for",
"item",
"in",
"data",
"[",
"table",
"]",
":",
"id_list",
".",
"append",
"(",
"item",
... | [
364,
0
] | [
371,
18
] | python | en | ['en', 'error', 'th'] | False |
allocate_ids | (model_class: Any, count: int) |
Increases the sequence number for a given table by the amount of objects being
imported into that table. Hence, this gives a reserved range of IDs to import the
converted Slack objects into the tables.
|
Increases the sequence number for a given table by the amount of objects being
imported into that table. Hence, this gives a reserved range of IDs to import the
converted Slack objects into the tables.
| def allocate_ids(model_class: Any, count: int) -> List[int]:
"""
Increases the sequence number for a given table by the amount of objects being
imported into that table. Hence, this gives a reserved range of IDs to import the
converted Slack objects into the tables.
"""
conn = connection.cursor(... | [
"def",
"allocate_ids",
"(",
"model_class",
":",
"Any",
",",
"count",
":",
"int",
")",
"->",
"List",
"[",
"int",
"]",
":",
"conn",
"=",
"connection",
".",
"cursor",
"(",
")",
"sequence",
"=",
"idseq",
"(",
"model_class",
")",
"conn",
".",
"execute",
"... | [
384,
0
] | [
396,
38
] | python | en | ['en', 'error', 'th'] | False |
convert_to_id_fields | (data: TableData, table: TableName, field_name: Field) |
When Django gives us dict objects via model_to_dict, the foreign
key fields are `foo`, but we want `foo_id` for the bulk insert.
This function handles the simple case where we simply rename
the fields. For cases where we need to munge ids in the
database, see re_map_foreign_keys.
|
When Django gives us dict objects via model_to_dict, the foreign
key fields are `foo`, but we want `foo_id` for the bulk insert.
This function handles the simple case where we simply rename
the fields. For cases where we need to munge ids in the
database, see re_map_foreign_keys.
| def convert_to_id_fields(data: TableData, table: TableName, field_name: Field) -> None:
"""
When Django gives us dict objects via model_to_dict, the foreign
key fields are `foo`, but we want `foo_id` for the bulk insert.
This function handles the simple case where we simply rename
the fields. For c... | [
"def",
"convert_to_id_fields",
"(",
"data",
":",
"TableData",
",",
"table",
":",
"TableName",
",",
"field_name",
":",
"Field",
")",
"->",
"None",
":",
"for",
"item",
"in",
"data",
"[",
"table",
"]",
":",
"item",
"[",
"field_name",
"+",
"\"_id\"",
"]",
... | [
399,
0
] | [
409,
28
] | python | en | ['en', 'error', 'th'] | False |
re_map_foreign_keys | (
data: TableData,
table: TableName,
field_name: Field,
related_table: TableName,
verbose: bool = False,
id_field: bool = False,
recipient_field: bool = False,
reaction_field: bool = False,
) |
This is a wrapper function for all the realm data tables
and only avatar and attachment records need to be passed through the internal function
because of the difference in data format (TableData corresponding to realm data tables
and List[Record] corresponding to the avatar and attachment records)
... |
This is a wrapper function for all the realm data tables
and only avatar and attachment records need to be passed through the internal function
because of the difference in data format (TableData corresponding to realm data tables
and List[Record] corresponding to the avatar and attachment records)
... | def re_map_foreign_keys(
data: TableData,
table: TableName,
field_name: Field,
related_table: TableName,
verbose: bool = False,
id_field: bool = False,
recipient_field: bool = False,
reaction_field: bool = False,
) -> None:
"""
This is a wrapper function for all the realm data ta... | [
"def",
"re_map_foreign_keys",
"(",
"data",
":",
"TableData",
",",
"table",
":",
"TableName",
",",
"field_name",
":",
"Field",
",",
"related_table",
":",
"TableName",
",",
"verbose",
":",
"bool",
"=",
"False",
",",
"id_field",
":",
"bool",
"=",
"False",
","... | [
412,
0
] | [
441,
5
] | python | en | ['en', 'error', 'th'] | False |
re_map_foreign_keys_internal | (
data_table: List[Record],
table: TableName,
field_name: Field,
related_table: TableName,
verbose: bool = False,
id_field: bool = False,
recipient_field: bool = False,
reaction_field: bool = False,
) |
We occasionally need to assign new ids to rows during the
import/export process, to accommodate things like existing rows
already being in tables. See bulk_import_client for more context.
The tricky part is making sure that foreign key references
are in sync with the new ids, and this fixer funct... |
We occasionally need to assign new ids to rows during the
import/export process, to accommodate things like existing rows
already being in tables. See bulk_import_client for more context. | def re_map_foreign_keys_internal(
data_table: List[Record],
table: TableName,
field_name: Field,
related_table: TableName,
verbose: bool = False,
id_field: bool = False,
recipient_field: bool = False,
reaction_field: bool = False,
) -> None:
"""
We occasionally need to assign new... | [
"def",
"re_map_foreign_keys_internal",
"(",
"data_table",
":",
"List",
"[",
"Record",
"]",
",",
"table",
":",
"TableName",
",",
"field_name",
":",
"Field",
",",
"related_table",
":",
"TableName",
",",
"verbose",
":",
"bool",
"=",
"False",
",",
"id_field",
":... | [
444,
0
] | [
500,
41
] | python | en | ['en', 'error', 'th'] | False |
re_map_foreign_keys_many_to_many | (
data: TableData,
table: TableName,
field_name: Field,
related_table: TableName,
verbose: bool = False,
) |
We need to assign new ids to rows during the import/export
process.
The tricky part is making sure that foreign key references
are in sync with the new ids, and this wrapper function does
the re-mapping only for ManyToMany fields.
|
We need to assign new ids to rows during the import/export
process. | def re_map_foreign_keys_many_to_many(
data: TableData,
table: TableName,
field_name: Field,
related_table: TableName,
verbose: bool = False,
) -> None:
"""
We need to assign new ids to rows during the import/export
process.
The tricky part is making sure that foreign key references
... | [
"def",
"re_map_foreign_keys_many_to_many",
"(",
"data",
":",
"TableData",
",",
"table",
":",
"TableName",
",",
"field_name",
":",
"Field",
",",
"related_table",
":",
"TableName",
",",
"verbose",
":",
"bool",
"=",
"False",
",",
")",
"->",
"None",
":",
"for",
... | [
503,
0
] | [
524,
28
] | python | en | ['en', 'error', 'th'] | False |
re_map_foreign_keys_many_to_many_internal | (
table: TableName,
field_name: Field,
related_table: TableName,
old_id_list: List[int],
verbose: bool = False,
) |
This is an internal function for tables with ManyToMany fields,
which takes the old ID list of the ManyToMany relation and returns the
new updated ID list.
|
This is an internal function for tables with ManyToMany fields,
which takes the old ID list of the ManyToMany relation and returns the
new updated ID list.
| def re_map_foreign_keys_many_to_many_internal(
table: TableName,
field_name: Field,
related_table: TableName,
old_id_list: List[int],
verbose: bool = False,
) -> List[int]:
"""
This is an internal function for tables with ManyToMany fields,
which takes the old ID list of the ManyToMany r... | [
"def",
"re_map_foreign_keys_many_to_many_internal",
"(",
"table",
":",
"TableName",
",",
"field_name",
":",
"Field",
",",
"related_table",
":",
"TableName",
",",
"old_id_list",
":",
"List",
"[",
"int",
"]",
",",
"verbose",
":",
"bool",
"=",
"False",
",",
")",
... | [
527,
0
] | [
551,
22
] | python | en | ['en', 'error', 'th'] | False |
fix_realm_authentication_bitfield | (data: TableData, table: TableName, field_name: Field) | Used to fixup the authentication_methods bitfield to be a string | Used to fixup the authentication_methods bitfield to be a string | def fix_realm_authentication_bitfield(data: TableData, table: TableName, field_name: Field) -> None:
"""Used to fixup the authentication_methods bitfield to be a string"""
for item in data[table]:
values_as_bitstring = "".join("1" if field[1] else "0" for field in item[field_name])
values_as_int... | [
"def",
"fix_realm_authentication_bitfield",
"(",
"data",
":",
"TableData",
",",
"table",
":",
"TableName",
",",
"field_name",
":",
"Field",
")",
"->",
"None",
":",
"for",
"item",
"in",
"data",
"[",
"table",
"]",
":",
"values_as_bitstring",
"=",
"\"\"",
".",
... | [
560,
0
] | [
565,
40
] | python | en | ['en', 'en', 'en'] | True |
remove_denormalized_recipient_column_from_data | (data: TableData) |
The recipient column shouldn't be imported, we'll set the correct values
when Recipient table gets imported.
|
The recipient column shouldn't be imported, we'll set the correct values
when Recipient table gets imported.
| def remove_denormalized_recipient_column_from_data(data: TableData) -> None:
"""
The recipient column shouldn't be imported, we'll set the correct values
when Recipient table gets imported.
"""
for stream_dict in data["zerver_stream"]:
if "recipient" in stream_dict:
del stream_di... | [
"def",
"remove_denormalized_recipient_column_from_data",
"(",
"data",
":",
"TableData",
")",
"->",
"None",
":",
"for",
"stream_dict",
"in",
"data",
"[",
"\"zerver_stream\"",
"]",
":",
"if",
"\"recipient\"",
"in",
"stream_dict",
":",
"del",
"stream_dict",
"[",
"\"r... | [
568,
0
] | [
583,
40
] | python | en | ['en', 'error', 'th'] | False |
get_db_table | (model_class: Any) | E.g. (RealmDomain -> 'zerver_realmdomain') | E.g. (RealmDomain -> 'zerver_realmdomain') | def get_db_table(model_class: Any) -> str:
"""E.g. (RealmDomain -> 'zerver_realmdomain')"""
return model_class._meta.db_table | [
"def",
"get_db_table",
"(",
"model_class",
":",
"Any",
")",
"->",
"str",
":",
"return",
"model_class",
".",
"_meta",
".",
"db_table"
] | [
586,
0
] | [
588,
37
] | python | de | ['de', 'mg', 'ur'] | False |
get_incoming_message_ids | (import_dir: Path, sort_by_date: bool) |
This function reads in our entire collection of message
ids, which can be millions of integers for some installations.
And then we sort the list. This is necessary to ensure
that the sort order of incoming ids matches the sort order
of date_sent, which isn't always guaranteed by our
utilities ... |
This function reads in our entire collection of message
ids, which can be millions of integers for some installations.
And then we sort the list. This is necessary to ensure
that the sort order of incoming ids matches the sort order
of date_sent, which isn't always guaranteed by our
utilities ... | def get_incoming_message_ids(import_dir: Path, sort_by_date: bool) -> List[int]:
"""
This function reads in our entire collection of message
ids, which can be millions of integers for some installations.
And then we sort the list. This is necessary to ensure
that the sort order of incoming ids matc... | [
"def",
"get_incoming_message_ids",
"(",
"import_dir",
":",
"Path",
",",
"sort_by_date",
":",
"bool",
")",
"->",
"List",
"[",
"int",
"]",
":",
"if",
"sort_by_date",
":",
"tups",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"=",
"[",
"]... | [
1277,
0
] | [
1332,
22
] | python | en | ['en', 'error', 'th'] | False |
log_handler | (handler: Any) | Override tornado's logging. | Override tornado's logging. | def log_handler(handler: Any) -> None:
"""Override tornado's logging."""
# log only errors (status >= 500)
if handler.get_status() >= 500:
access_log.error(
'{} {}'.format(handler.get_status(), handler._request_summary())
) | [
"def",
"log_handler",
"(",
"handler",
":",
"Any",
")",
"->",
"None",
":",
"# log only errors (status >= 500)",
"if",
"handler",
".",
"get_status",
"(",
")",
">=",
"500",
":",
"access_log",
".",
"error",
"(",
"'{} {}'",
".",
"format",
"(",
"handler",
".",
"... | [
164,
0
] | [
170,
9
] | python | en | ['en', 'nl', 'pt'] | False |
truncate_colormap | (cmap, minval=0.0, maxval=1.0, n=256) | Remove extreme colors from a colormap. | Remove extreme colors from a colormap. | def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=256):
"""Remove extreme colors from a colormap."""
new_cmap = colors.LinearSegmentedColormap.from_list(
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
cmap(np.linspace(minval, maxval, n)))
return new_cmap | [
"def",
"truncate_colormap",
"(",
"cmap",
",",
"minval",
"=",
"0.0",
",",
"maxval",
"=",
"1.0",
",",
"n",
"=",
"256",
")",
":",
"new_cmap",
"=",
"colors",
".",
"LinearSegmentedColormap",
".",
"from_list",
"(",
"'trunc({n},{a:.2f},{b:.2f})'",
".",
"format",
"(... | [
40,
0
] | [
45,
19
] | python | en | ['en', 'en', 'en'] | True |
gencolor_generator | (n, cmap='Set1') | Color generator intended to work with qualitative color scales. | Color generator intended to work with qualitative color scales. | def gencolor_generator(n, cmap='Set1'):
""" Color generator intended to work with qualitative color scales."""
# don't use more than 9 discrete colors
n_colors = min(n, 9)
cmap = colormap.get_cmap(cmap, n_colors)
colors = cmap(range(n_colors))
for i in range(n):
yield colors[i % n_colors... | [
"def",
"gencolor_generator",
"(",
"n",
",",
"cmap",
"=",
"'Set1'",
")",
":",
"# don't use more than 9 discrete colors",
"n_colors",
"=",
"min",
"(",
"n",
",",
"9",
")",
"cmap",
"=",
"colormap",
".",
"get_cmap",
"(",
"cmap",
",",
"n_colors",
")",
"colors",
... | [
48,
0
] | [
55,
34
] | python | en | ['en', 'en', 'en'] | True |
_plot_map | (plotfunc) |
Decorator for common salem.Map plotting logic
|
Decorator for common salem.Map plotting logic
| def _plot_map(plotfunc):
"""
Decorator for common salem.Map plotting logic
"""
commondoc = """
Parameters
----------
gdirs : [] or GlacierDirectory, required
A single GlacierDirectory or a list of gdirs to plot.
ax : matplotlib axes object, optional
If None, uses own axi... | [
"def",
"_plot_map",
"(",
"plotfunc",
")",
":",
"commondoc",
"=",
"\"\"\"\n\n Parameters\n ----------\n gdirs : [] or GlacierDirectory, required\n A single GlacierDirectory or a list of gdirs to plot.\n ax : matplotlib axes object, optional\n If None, uses own axis\n smap... | [
76,
0
] | [
194,
22
] | python | en | ['en', 'error', 'th'] | False |
plot_googlemap | (gdirs, ax=None, figsize=None) | Plots the glacier(s) over a googlemap. | Plots the glacier(s) over a googlemap. | def plot_googlemap(gdirs, ax=None, figsize=None):
"""Plots the glacier(s) over a googlemap."""
dofig = False
if ax is None:
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
dofig = True
gdirs = utils.tolist(gdirs)
xx, yy = [], []
for gdir in gdirs:
x... | [
"def",
"plot_googlemap",
"(",
"gdirs",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
")",
":",
"dofig",
"=",
"False",
"if",
"ax",
"is",
"None",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"ax",
"=",
"fig",
"... | [
197,
0
] | [
232,
26
] | python | en | ['en', 'en', 'en'] | True |
plot_raster | (gdirs, var_name=None, cmap='viridis', ax=None, smap=None) | Plot any raster from the gridded_data file. | Plot any raster from the gridded_data file. | def plot_raster(gdirs, var_name=None, cmap='viridis', ax=None, smap=None):
"""Plot any raster from the gridded_data file."""
# Files
gdir = gdirs[0]
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
var = nc.variables[var_name]
data = var[:]
description = var.long_... | [
"def",
"plot_raster",
"(",
"gdirs",
",",
"var_name",
"=",
"None",
",",
"cmap",
"=",
"'viridis'",
",",
"ax",
"=",
"None",
",",
"smap",
"=",
"None",
")",
":",
"# Files",
"gdir",
"=",
"gdirs",
"[",
"0",
"]",
"with",
"utils",
".",
"ncDataset",
"(",
"gd... | [
236,
0
] | [
270,
69
] | python | en | ['en', 'en', 'en'] | True |
plot_domain | (gdirs, ax=None, smap=None, use_netcdf=False) | Plot the glacier directory.
Parameters
----------
gdirs
ax
smap
use_netcdf : bool
use output of glacier_masks instead of geotiff DEM
| Plot the glacier directory. | def plot_domain(gdirs, ax=None, smap=None, use_netcdf=False):
"""Plot the glacier directory.
Parameters
----------
gdirs
ax
smap
use_netcdf : bool
use output of glacier_masks instead of geotiff DEM
"""
# Files
gdir = gdirs[0]
if use_netcdf:
with utils.ncData... | [
"def",
"plot_domain",
"(",
"gdirs",
",",
"ax",
"=",
"None",
",",
"smap",
"=",
"None",
",",
"use_netcdf",
"=",
"False",
")",
":",
"# Files",
"gdir",
"=",
"gdirs",
"[",
"0",
"]",
"if",
"use_netcdf",
":",
"with",
"utils",
".",
"ncDataset",
"(",
"gdir",
... | [
274,
0
] | [
320,
38
] | python | en | ['en', 'it', 'en'] | True |
plot_centerlines | (gdirs, ax=None, smap=None, use_flowlines=False,
add_downstream=False, lines_cmap='Set1',
add_line_index=False, use_model_flowlines=False) | Plots the centerlines of a glacier directory. | Plots the centerlines of a glacier directory. | def plot_centerlines(gdirs, ax=None, smap=None, use_flowlines=False,
add_downstream=False, lines_cmap='Set1',
add_line_index=False, use_model_flowlines=False):
"""Plots the centerlines of a glacier directory."""
if add_downstream and not use_flowlines:
raise Va... | [
"def",
"plot_centerlines",
"(",
"gdirs",
",",
"ax",
"=",
"None",
",",
"smap",
"=",
"None",
",",
"use_flowlines",
"=",
"False",
",",
"add_downstream",
"=",
"False",
",",
"lines_cmap",
"=",
"'Set1'",
",",
"add_line_index",
"=",
"False",
",",
"use_model_flowlin... | [
324,
0
] | [
387,
38
] | python | en | ['en', 'es', 'en'] | True |
plot_catchment_areas | (gdirs, ax=None, smap=None, lines_cmap='Set1',
mask_cmap='Set2') | Plots the catchments out of a glacier directory.
| Plots the catchments out of a glacier directory.
| def plot_catchment_areas(gdirs, ax=None, smap=None, lines_cmap='Set1',
mask_cmap='Set2'):
"""Plots the catchments out of a glacier directory.
"""
gdir = gdirs[0]
if len(gdirs) > 1:
raise NotImplementedError('Cannot plot a list of gdirs (yet)')
with utils.ncDataset(... | [
"def",
"plot_catchment_areas",
"(",
"gdirs",
",",
"ax",
"=",
"None",
",",
"smap",
"=",
"None",
",",
"lines_cmap",
"=",
"'Set1'",
",",
"mask_cmap",
"=",
"'Set2'",
")",
":",
"gdir",
"=",
"gdirs",
"[",
"0",
"]",
"if",
"len",
"(",
"gdirs",
")",
">",
"1... | [
391,
0
] | [
432,
13
] | python | en | ['en', 'en', 'en'] | True |
plot_catchment_width | (gdirs, ax=None, smap=None, corrected=False,
add_intersects=False, add_touches=False,
lines_cmap='Set1') | Plots the catchment widths out of a glacier directory.
| Plots the catchment widths out of a glacier directory.
| def plot_catchment_width(gdirs, ax=None, smap=None, corrected=False,
add_intersects=False, add_touches=False,
lines_cmap='Set1'):
"""Plots the catchment widths out of a glacier directory.
"""
gdir = gdirs[0]
with utils.ncDataset(gdir.get_filepath('gridd... | [
"def",
"plot_catchment_width",
"(",
"gdirs",
",",
"ax",
"=",
"None",
",",
"smap",
"=",
"None",
",",
"corrected",
"=",
"False",
",",
"add_intersects",
"=",
"False",
",",
"add_touches",
"=",
"False",
",",
"lines_cmap",
"=",
"'Set1'",
")",
":",
"gdir",
"=",... | [
436,
0
] | [
505,
13
] | python | en | ['en', 'en', 'en'] | True |
plot_inversion | (gdirs, ax=None, smap=None, linewidth=3, vmax=None) | Plots the result of the inversion out of a glacier directory. | Plots the result of the inversion out of a glacier directory. | def plot_inversion(gdirs, ax=None, smap=None, linewidth=3, vmax=None):
"""Plots the result of the inversion out of a glacier directory."""
gdir = gdirs[0]
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
topo = nc.variables['topo'][:]
# Dirty optim
try:
smap.set_topog... | [
"def",
"plot_inversion",
"(",
"gdirs",
",",
"ax",
"=",
"None",
",",
"smap",
"=",
"None",
",",
"linewidth",
"=",
"3",
",",
"vmax",
"=",
"None",
")",
":",
"gdir",
"=",
"gdirs",
"[",
"0",
"]",
"with",
"utils",
".",
"ncDataset",
"(",
"gdir",
".",
"ge... | [
509,
0
] | [
561,
76
] | python | en | ['en', 'en', 'en'] | True |
plot_distributed_thickness | (gdirs, ax=None, smap=None, varname_suffix='') | Plots the result of the inversion out of a glacier directory.
Method: 'alt' or 'interp'
| Plots the result of the inversion out of a glacier directory. | def plot_distributed_thickness(gdirs, ax=None, smap=None, varname_suffix=''):
"""Plots the result of the inversion out of a glacier directory.
Method: 'alt' or 'interp'
"""
gdir = gdirs[0]
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
topo = nc.variables['topo'][:]
s... | [
"def",
"plot_distributed_thickness",
"(",
"gdirs",
",",
"ax",
"=",
"None",
",",
"smap",
"=",
"None",
",",
"varname_suffix",
"=",
"''",
")",
":",
"gdir",
"=",
"gdirs",
"[",
"0",
"]",
"with",
"utils",
".",
"ncDataset",
"(",
"gdir",
".",
"get_filepath",
"... | [
565,
0
] | [
609,
51
] | python | en | ['en', 'en', 'en'] | True |
plot_modeloutput_map | (gdirs, ax=None, smap=None, model=None,
vmax=None, linewidth=3, filesuffix='',
modelyr=None) | Plots the result of the model output. | Plots the result of the model output. | def plot_modeloutput_map(gdirs, ax=None, smap=None, model=None,
vmax=None, linewidth=3, filesuffix='',
modelyr=None):
"""Plots the result of the model output."""
gdir = gdirs[0]
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
topo = n... | [
"def",
"plot_modeloutput_map",
"(",
"gdirs",
",",
"ax",
"=",
"None",
",",
"smap",
"=",
"None",
",",
"model",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"linewidth",
"=",
"3",
",",
"filesuffix",
"=",
"''",
",",
"modelyr",
"=",
"None",
")",
":",
"gd... | [
613,
0
] | [
676,
74
] | python | en | ['en', 'en', 'en'] | True |
plot_modeloutput_section | (model=None, ax=None, title='') | Plots the result of the model output along the flowline.
Parameters
----------
model: obj
either a FlowlineModel or a list of model flowlines.
fig
title
| Plots the result of the model output along the flowline. | def plot_modeloutput_section(model=None, ax=None, title=''):
"""Plots the result of the model output along the flowline.
Parameters
----------
model: obj
either a FlowlineModel or a list of model flowlines.
fig
title
"""
try:
fls = model.fls
except AttributeError:
... | [
"def",
"plot_modeloutput_section",
"(",
"model",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"title",
"=",
"''",
")",
":",
"try",
":",
"fls",
"=",
"model",
".",
"fls",
"except",
"AttributeError",
":",
"fls",
"=",
"model",
"if",
"ax",
"is",
"None",
":",... | [
679,
0
] | [
781,
28
] | python | en | ['en', 'en', 'en'] | True |
plot_modeloutput_section_withtrib | (model=None, fig=None, title='') | Plots the result of the model output along the flowline.
Parameters
----------
model: obj
either a FlowlineModel or a list of model flowlines.
fig
title
| Plots the result of the model output along the flowline. | def plot_modeloutput_section_withtrib(model=None, fig=None, title=''):
"""Plots the result of the model output along the flowline.
Parameters
----------
model: obj
either a FlowlineModel or a list of model flowlines.
fig
title
"""
try:
fls = model.fls
except Attribu... | [
"def",
"plot_modeloutput_section_withtrib",
"(",
"model",
"=",
"None",
",",
"fig",
"=",
"None",
",",
"title",
"=",
"''",
")",
":",
"try",
":",
"fls",
"=",
"model",
".",
"fls",
"except",
"AttributeError",
":",
"fls",
"=",
"model",
"n_tribs",
"=",
"len",
... | [
784,
0
] | [
875,
22
] | python | en | ['en', 'en', 'en'] | True |
ExpandXcodeVariables | (string, expansions) | Expands Xcode-style $(VARIABLES) in string per the expansions dict.
In some rare cases, it is appropriate to expand Xcode variables when a
project file is generated. For any substring $(VAR) in string, if VAR is a
key in the expansions dict, $(VAR) will be replaced with expansions[VAR].
Any $(VAR) substring i... | Expands Xcode-style $(VARIABLES) in string per the expansions dict. | def ExpandXcodeVariables(string, expansions):
"""Expands Xcode-style $(VARIABLES) in string per the expansions dict.
In some rare cases, it is appropriate to expand Xcode variables when a
project file is generated. For any substring $(VAR) in string, if VAR is a
key in the expansions dict, $(VAR) will be re... | [
"def",
"ExpandXcodeVariables",
"(",
"string",
",",
"expansions",
")",
":",
"matches",
"=",
"_xcode_variable_re",
".",
"findall",
"(",
"string",
")",
"if",
"matches",
"is",
"None",
":",
"return",
"string",
"matches",
".",
"reverse",
"(",
")",
"for",
"match",
... | [
564,
0
] | [
587,
17
] | python | en | ['en', 'en', 'en'] | True |
EscapeXcodeDefine | (s) | We must escape the defines that we give to XCode so that it knows not to
split on spaces and to respect backslash and quote literals. However, we
must not quote the define, or Xcode will incorrectly interpret variables
especially $(inherited). | We must escape the defines that we give to XCode so that it knows not to
split on spaces and to respect backslash and quote literals. However, we
must not quote the define, or Xcode will incorrectly interpret variables
especially $(inherited). | def EscapeXcodeDefine(s):
"""We must escape the defines that we give to XCode so that it knows not to
split on spaces and to respect backslash and quote literals. However, we
must not quote the define, or Xcode will incorrectly interpret variables
especially $(inherited)."""
return re.sub(_xcode_... | [
"def",
"EscapeXcodeDefine",
"(",
"s",
")",
":",
"return",
"re",
".",
"sub",
"(",
"_xcode_define_re",
",",
"r\"\\\\\\1\"",
",",
"s",
")"
] | [
593,
0
] | [
598,
47
] | python | en | ['en', 'en', 'en'] | True |
load_provinces | () | Loads list of provinces from API | Loads list of provinces from API | def load_provinces():
'''Loads list of provinces from API'''
return pd.read_json('https://api.covid19tracker.ca/provinces') | [
"def",
"load_provinces",
"(",
")",
":",
"return",
"pd",
".",
"read_json",
"(",
"'https://api.covid19tracker.ca/provinces'",
")"
] | [
19,
0
] | [
21,
66
] | python | en | ['en', 'en', 'en'] | True |
load_data | (province_code, population) | Loads provincial case data w/ provided province code | Loads provincial case data w/ provided province code | def load_data(province_code, population):
'''Loads provincial case data w/ provided province code'''
df = pd.json_normalize(
pd.read_json(f'https://api.covid19tracker.ca/reports/province/{province_code.lower()}')['data']
)
df['active_cases'] = df['change_cases'].rolling(14).sum()
df['active... | [
"def",
"load_data",
"(",
"province_code",
",",
"population",
")",
":",
"df",
"=",
"pd",
".",
"json_normalize",
"(",
"pd",
".",
"read_json",
"(",
"f'https://api.covid19tracker.ca/reports/province/{province_code.lower()}'",
")",
"[",
"'data'",
"]",
")",
"df",
"[",
"... | [
25,
0
] | [
37,
13
] | python | en | ['en', 'en', 'en'] | True |
generate_hero_card | (title, subtitle) | Generates HTML string for card | Generates HTML string for card | def generate_hero_card(title, subtitle):
'''Generates HTML string for card'''
return f'''
<div style='text-align: center'>
<h1 style='margin-top: 0; padding-top: 0.2rem;'>{title}</h1>
<h2 style='margin-top: 0; padding-top: 0'>{subtitle}</h2>
</div>
''' | [
"def",
"generate_hero_card",
"(",
"title",
",",
"subtitle",
")",
":",
"return",
"f'''\n <div style='text-align: center'>\n <h1 style='margin-top: 0; padding-top: 0.2rem;'>{title}</h1>\n <h2 style='margin-top: 0; padding-top: 0'>{subtitle}</h2>\n </div>\n '''"... | [
41,
0
] | [
48,
7
] | python | en | ['en', 'en', 'en'] | True |
extract_packages | (package_names) | Extract zipfile contents to disk and add to import path | Extract zipfile contents to disk and add to import path | def extract_packages(package_names):
"""Extract zipfile contents to disk and add to import path"""
# Set a safe extraction dir
extraction_tmpdir = tempfile.mkdtemp()
atexit.register(lambda: shutil.rmtree(
extraction_tmpdir, ignore_errors=True))
pkg_resources.set_extraction_path(extraction_t... | [
"def",
"extract_packages",
"(",
"package_names",
")",
":",
"# Set a safe extraction dir",
"extraction_tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"atexit",
".",
"register",
"(",
"lambda",
":",
"shutil",
".",
"rmtree",
"(",
"extraction_tmpdir",
",",
"ignore... | [
32,
0
] | [
54,
52
] | python | en | ['en', 'en', 'en'] | True |
sort_wheels | (whls) | Sorts a list of wheels deterministically. | Sorts a list of wheels deterministically. | def sort_wheels(whls):
"""Sorts a list of wheels deterministically."""
return sorted(whls, key=lambda w: w.distribution() + '_' + w.version()) | [
"def",
"sort_wheels",
"(",
"whls",
")",
":",
"return",
"sorted",
"(",
"whls",
",",
"key",
"=",
"lambda",
"w",
":",
"w",
".",
"distribution",
"(",
")",
"+",
"'_'",
"+",
"w",
".",
"version",
"(",
")",
")"
] | [
107,
0
] | [
109,
73
] | python | en | ['en', 'en', 'en'] | True |
determine_possible_extras | (whls) | Determines the list of possible "extras" for each .whl
The possibility of an extra is determined by looking at its
additional requirements, and determinine whether they are
satisfied by the complete list of available wheels.
Args:
whls: a list of Wheel objects
Returns:
a dict that is keyed by the W... | Determines the list of possible "extras" for each .whl | def determine_possible_extras(whls):
"""Determines the list of possible "extras" for each .whl
The possibility of an extra is determined by looking at its
additional requirements, and determinine whether they are
satisfied by the complete list of available wheels.
Args:
whls: a list of Wheel objects
... | [
"def",
"determine_possible_extras",
"(",
"whls",
")",
":",
"whl_map",
"=",
"{",
"whl",
".",
"distribution",
"(",
")",
":",
"whl",
"for",
"whl",
"in",
"whls",
"}",
"# TODO(mattmoor): Consider memoizing if this recursion ever becomes",
"# expensive enough to warrant it.",
... | [
111,
0
] | [
163,
3
] | python | en | ['en', 'en', 'en'] | True |
parse_bed6 | (fname, progress_report=False, forceStrand=None,
generated_by="common.gff_gtf_tools.parse_gff_v3(v%s)" \
"" % str(ver),
preserve_source=False, stripChr=False, splitChar="\t") | read a bed6 file and convert it into a set of 'regions'
forceStrand overrides any strand information in the bedfile. Acceptable values
are '-' or '+'. | read a bed6 file and convert it into a set of 'regions'
forceStrand overrides any strand information in the bedfile. Acceptable values
are '-' or '+'. | def parse_bed6(fname, progress_report=False, forceStrand=None,
generated_by="common.gff_gtf_tools.parse_gff_v3(v%s)" \
"" % str(ver),
preserve_source=False, stripChr=False, splitChar="\t"):
""" read a bed6 file and convert it into a set of 'regions'
... | [
"def",
"parse_bed6",
"(",
"fname",
",",
"progress_report",
"=",
"False",
",",
"forceStrand",
"=",
"None",
",",
"generated_by",
"=",
"\"common.gff_gtf_tools.parse_gff_v3(v%s)\"",
"\"\"",
"%",
"str",
"(",
"ver",
")",
",",
"preserve_source",
"=",
"False",
",",
"str... | [
60,
0
] | [
161,
40
] | python | en | ['en', 'en', 'en'] | True |
parse_gff_gtf | (fname, skip_fasta=True, force_type=None,
progress_report=False, fixID=True, fixName=True,
generated_by="common.gff_gtf_tools.parse_gff_v3(v%s)" \
"" % str(ver),
preserve_source=False, stripChr=False, splitChar="\t") | read a gff or gtf file and convert it into a set of 'regions'
skip_fasta controls what to do with fasta sequences stored at the end of
gff files, force_type controls whether to autodetect the type from the gff
file or whether to assume a known filetype. fixID forces each regions to
include an i... | read a gff or gtf file and convert it into a set of 'regions'
skip_fasta controls what to do with fasta sequences stored at the end of
gff files, force_type controls whether to autodetect the type from the gff
file or whether to assume a known filetype. fixID forces each regions to
include an i... | def parse_gff_gtf(fname, skip_fasta=True, force_type=None,
progress_report=False, fixID=True, fixName=True,
generated_by="common.gff_gtf_tools.parse_gff_v3(v%s)" \
"" % str(ver),
preserve_source=False, stripChr=False, splitChar="\t"):
... | [
"def",
"parse_gff_gtf",
"(",
"fname",
",",
"skip_fasta",
"=",
"True",
",",
"force_type",
"=",
"None",
",",
"progress_report",
"=",
"False",
",",
"fixID",
"=",
"True",
",",
"fixName",
"=",
"True",
",",
"generated_by",
"=",
"\"common.gff_gtf_tools.parse_gff_v3(v%s... | [
163,
0
] | [
368,
40
] | python | en | ['en', 'en', 'en'] | True |
mergeAnnotations | (input_filenames, logger, filetype="gff3",
overwrite_strand_list=None, generated_by=None) | merges two or more annotations, optionally overwriting strnad info | merges two or more annotations, optionally overwriting strnad info | def mergeAnnotations(input_filenames, logger, filetype="gff3",
overwrite_strand_list=None, generated_by=None):
""" merges two or more annotations, optionally overwriting strnad info """
new_annotation=None
annotations=[]
i=0
while i<len(input_filenames):
filename = input_filenames... | [
"def",
"mergeAnnotations",
"(",
"input_filenames",
",",
"logger",
",",
"filetype",
"=",
"\"gff3\"",
",",
"overwrite_strand_list",
"=",
"None",
",",
"generated_by",
"=",
"None",
")",
":",
"new_annotation",
"=",
"None",
"annotations",
"=",
"[",
"]",
"i",
"=",
... | [
1167,
0
] | [
1211,
26
] | python | en | ['en', 'en', 'en'] | True |
overwrite_strand | (full_annotation, newstrand, logger) | takes a full annotation region and overwrites the strand information
This overwrite *all* strand information. Use carefully! | takes a full annotation region and overwrites the strand information
This overwrite *all* strand information. Use carefully! | def overwrite_strand(full_annotation, newstrand, logger):
""" takes a full annotation region and overwrites the strand information
This overwrite *all* strand information. Use carefully!"""
if type(full_annotation) is not dict:
raise TypeError("Please supply a full annotation dictiona... | [
"def",
"overwrite_strand",
"(",
"full_annotation",
",",
"newstrand",
",",
"logger",
")",
":",
"if",
"type",
"(",
"full_annotation",
")",
"is",
"not",
"dict",
":",
"raise",
"TypeError",
"(",
"\"Please supply a full annotation dictionary in order \"",
"\"to overwrite the ... | [
1213,
0
] | [
1244,
27
] | python | en | ['en', 'en', 'en'] | True |
annotation.__init__ | (self, fname, skip_fasta=True, filetype=None, verbose=False,
forceGene_ID=True, forceTranscript_ID=True, generated_by=None,
existing_annotation_headerlines=None, preserve_source=False,
stripChr=False, featureNameKey=None, forceStrand=None) | class constructor: this takes the filename of the gff or gtf file
and reads the data from it into the class attributes. Filename should
be a string and point to a file that exists. skip_fasta is passed to
the parsing options where appropriate and filetype controls whether to
assume a p... | class constructor: this takes the filename of the gff or gtf file
and reads the data from it into the class attributes. Filename should
be a string and point to a file that exists. skip_fasta is passed to
the parsing options where appropriate and filetype controls whether to
assume a p... | def __init__(self, fname, skip_fasta=True, filetype=None, verbose=False,
forceGene_ID=True, forceTranscript_ID=True, generated_by=None,
existing_annotation_headerlines=None, preserve_source=False,
stripChr=False, featureNameKey=None, forceStrand=None):
... | [
"def",
"__init__",
"(",
"self",
",",
"fname",
",",
"skip_fasta",
"=",
"True",
",",
"filetype",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"forceGene_ID",
"=",
"True",
",",
"forceTranscript_ID",
"=",
"True",
",",
"generated_by",
"=",
"None",
",",
"ex... | [
381,
4
] | [
577,
50
] | python | en | ['en', 'en', 'en'] | True |
annotation.__gen_ordering_array | (self) | generates the main numpy array for working with the annotation | generates the main numpy array for working with the annotation | def __gen_ordering_array(self):
"""generates the main numpy array for working with the annotation """
tuplelist=[]
for region_type in self._full_annotation.keys():
try:
for each_region in self._full_annotation[region_type]:
... | [
"def",
"__gen_ordering_array",
"(",
"self",
")",
":",
"tuplelist",
"=",
"[",
"]",
"for",
"region_type",
"in",
"self",
".",
"_full_annotation",
".",
"keys",
"(",
")",
":",
"try",
":",
"for",
"each_region",
"in",
"self",
".",
"_full_annotation",
"[",
"region... | [
580,
4
] | [
607,
59
] | python | en | ['en', 'en', 'en'] | True |
annotation.__region_to_tuple | (self, thisregion, region_type, region_id,
specifyNameID=None) | build a tuple appropriate for the ordering array from a region
This should contain 7 elements, see the __ordering_array_dtype | build a tuple appropriate for the ordering array from a region
This should contain 7 elements, see the __ordering_array_dtype | def __region_to_tuple(self, thisregion, region_type, region_id,
specifyNameID=None):
""" build a tuple appropriate for the ordering array from a region
This should contain 7 elements, see the __ordering_array_dtype"""
thisid=None
... | [
"def",
"__region_to_tuple",
"(",
"self",
",",
"thisregion",
",",
"region_type",
",",
"region_id",
",",
"specifyNameID",
"=",
"None",
")",
":",
"thisid",
"=",
"None",
"if",
"specifyNameID",
"is",
"not",
"None",
":",
"if",
"specifyNameID",
"in",
"thisregion",
... | [
609,
4
] | [
634,
26
] | python | en | ['en', 'en', 'en'] | True |
annotation.set_nameKey | (self, newNameKey) | sets a new keyword value for the 'name' column for ordering_array | sets a new keyword value for the 'name' column for ordering_array | def set_nameKey(self, newNameKey):
""" sets a new keyword value for the 'name' column for ordering_array"""
self.featureNameKey = newNameKey
self._ordering_array = self.__gen_ordering_array() | [
"def",
"set_nameKey",
"(",
"self",
",",
"newNameKey",
")",
":",
"self",
".",
"featureNameKey",
"=",
"newNameKey",
"self",
".",
"_ordering_array",
"=",
"self",
".",
"__gen_ordering_array",
"(",
")"
] | [
636,
4
] | [
641,
58
] | python | en | ['en', 'en', 'en'] | True |
annotation.set_feature | (self, feature_str) | set the feature type you're interested in | set the feature type you're interested in | def set_feature(self, feature_str):
""" set the feature type you're interested in """
if type(feature_str) is not str:
msg = "Feature type should be a string. Available " \
"features are: %s" % ", ".join(self._featurelist)
raise TypeError(msg)
... | [
"def",
"set_feature",
"(",
"self",
",",
"feature_str",
")",
":",
"if",
"type",
"(",
"feature_str",
")",
"is",
"not",
"str",
":",
"msg",
"=",
"\"Feature type should be a string. Available \"",
"\"features are: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"self",
".",
... | [
643,
4
] | [
659,
96
] | python | en | ['en', 'en', 'en'] | True |
annotation.clear_feature_selection | (self) | clears the variables defining the current feature selection | clears the variables defining the current feature selection | def clear_feature_selection(self):
""" clears the variables defining the current feature selection """
self.current_feature=None
self._feature_index=None | [
"def",
"clear_feature_selection",
"(",
"self",
")",
":",
"self",
".",
"current_feature",
"=",
"None",
"self",
".",
"_feature_index",
"=",
"None"
] | [
661,
4
] | [
666,
32
] | python | en | ['en', 'en', 'en'] | True |
annotation.set_region | (self, region_rep, start=None, stop=None, strand=None) | set the feature region you're interested in.
Input can either be a 'region' instance or a string that will be parsed
into a 'region' instance. See
parsing_routines.general_classes_and_functions.py for details on the
input for the 'region' constructor.
| set the feature region you're interested in.
Input can either be a 'region' instance or a string that will be parsed
into a 'region' instance. See
parsing_routines.general_classes_and_functions.py for details on the
input for the 'region' constructor.
| def set_region(self, region_rep, start=None, stop=None, strand=None):
""" set the feature region you're interested in.
Input can either be a 'region' instance or a string that will be parsed
into a 'region' instance. See
parsing_routines.general_classes_and_functions... | [
"def",
"set_region",
"(",
"self",
",",
"region_rep",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"strand",
"=",
"None",
")",
":",
"this_region",
"=",
"generic_set_region",
"(",
"region_rep",
",",
"start",
",",
"stop",
",",
"strand",
")",
... | [
668,
4
] | [
720,
37
] | python | en | ['en', 'en', 'en'] | True |
annotation.clear_region_selection | (self) | clears the variables defining the current feature selection | clears the variables defining the current feature selection | def clear_region_selection(self):
""" clears the variables defining the current feature selection """
self.current_region=None
self._region_index=None | [
"def",
"clear_region_selection",
"(",
"self",
")",
":",
"self",
".",
"current_region",
"=",
"None",
"self",
".",
"_region_index",
"=",
"None"
] | [
722,
4
] | [
727,
31
] | python | en | ['en', 'en', 'en'] | True |
annotation.set_name_selection | (self, name_str) | set the name(s) of the feature(s) your are interested in | set the name(s) of the feature(s) your are interested in | def set_name_selection(self, name_str):
""" set the name(s) of the feature(s) your are interested in """
if type(name_str) is list or type(name_str) is numpy.ndarray:
newlist = []
for name in name_str:
newlist.append(name.lower())
# uniqueify... | [
"def",
"set_name_selection",
"(",
"self",
",",
"name_str",
")",
":",
"if",
"type",
"(",
"name_str",
")",
"is",
"list",
"or",
"type",
"(",
"name_str",
")",
"is",
"numpy",
".",
"ndarray",
":",
"newlist",
"=",
"[",
"]",
"for",
"name",
"in",
"name_str",
... | [
729,
4
] | [
752,
32
] | python | en | ['en', 'en', 'en'] | True |
annotation.clear_name_selection | (self) | clears the variables defining the current name selection | clears the variables defining the current name selection | def clear_name_selection(self):
""" clears the variables defining the current name selection """
self.current_name=None
self._name_index=None | [
"def",
"clear_name_selection",
"(",
"self",
")",
":",
"self",
".",
"current_name",
"=",
"None",
"self",
".",
"_name_index",
"=",
"None"
] | [
754,
4
] | [
759,
29
] | python | en | ['en', 'en', 'en'] | True |
annotation.set_attribute_filters | (self, this_dict) | filters regions for only those with a given attribute value | filters regions for only those with a given attribute value | def set_attribute_filters(self, this_dict):
""" filters regions for only those with a given attribute value"""
if type(this_dict) is not dict:
msg = "Attribute filters should be a dictionary of the form: " \
"{atribute_name:value, ... }."
raise... | [
"def",
"set_attribute_filters",
"(",
"self",
",",
"this_dict",
")",
":",
"if",
"type",
"(",
"this_dict",
")",
"is",
"not",
"dict",
":",
"msg",
"=",
"\"Attribute filters should be a dictionary of the form: \"",
"\"{atribute_name:value, ... }.\"",
"raise",
"TypeError",
"(... | [
761,
4
] | [
769,
41
] | python | en | ['en', 'en', 'en'] | True |
annotation.clear_attribute_filter | (self) | clears the variables defining the current feature selection | clears the variables defining the current feature selection | def clear_attribute_filter(self):
""" clears the variables defining the current feature selection """
self.current_attributes=None | [
"def",
"clear_attribute_filter",
"(",
"self",
")",
":",
"self",
".",
"current_attributes",
"=",
"None"
] | [
771,
4
] | [
775,
36
] | python | en | ['en', 'en', 'en'] | True |
annotation.clear_all | (self) | clears all the selectors and filter options | clears all the selectors and filter options | def clear_all(self):
""" clears all the selectors and filter options """
self.current_feature=None
self._feature_index=None
self.current_region=None
self._region_index=None
self.current_name=None
self._name_index=None
self.current_attribu... | [
"def",
"clear_all",
"(",
"self",
")",
":",
"self",
".",
"current_feature",
"=",
"None",
"self",
".",
"_feature_index",
"=",
"None",
"self",
".",
"current_region",
"=",
"None",
"self",
".",
"_region_index",
"=",
"None",
"self",
".",
"current_name",
"=",
"No... | [
777,
4
] | [
787,
36
] | python | en | ['en', 'en', 'en'] | True |
annotation.__build_final_index | (self) | return a combined index based on feature & region indexes | return a combined index based on feature & region indexes | def __build_final_index(self):
""" return a combined index based on feature & region indexes """
indexes = [numpy.arange(len(self._ordering_array["start"]))]
if self._region_index is not None:
indexes.append(self._region_index)
if self._feature_index is not ... | [
"def",
"__build_final_index",
"(",
"self",
")",
":",
"indexes",
"=",
"[",
"numpy",
".",
"arange",
"(",
"len",
"(",
"self",
".",
"_ordering_array",
"[",
"\"start\"",
"]",
")",
")",
"]",
"if",
"self",
".",
"_region_index",
"is",
"not",
"None",
":",
"inde... | [
789,
4
] | [
809,
25
] | python | en | ['en', 'en', 'en'] | True |
annotation.get_selection | (self, match_case=False, return_indexes=False) | return the selected annotations based on feature & region indexes | return the selected annotations based on feature & region indexes | def get_selection(self, match_case=False, return_indexes=False):
""" return the selected annotations based on feature & region indexes """
final_ind = self.__build_final_index()
selection = self._ordering_array[final_ind]
selected_regions=[]
i=0
for sele... | [
"def",
"get_selection",
"(",
"self",
",",
"match_case",
"=",
"False",
",",
"return_indexes",
"=",
"False",
")",
":",
"final_ind",
"=",
"self",
".",
"__build_final_index",
"(",
")",
"selection",
"=",
"self",
".",
"_ordering_array",
"[",
"final_ind",
"]",
"sel... | [
811,
4
] | [
845,
32
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.