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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
number_format | (value, decimal_pos=None, use_l10n=None, force_grouping=False) |
Formats a numeric value using localization settings
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
|
Formats a numeric value using localization settings | def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
"""
Formats a numeric value using localization settings
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
if use_l10n or (us... | [
"def",
"number_format",
"(",
"value",
",",
"decimal_pos",
"=",
"None",
",",
"use_l10n",
"=",
"None",
",",
"force_grouping",
"=",
"False",
")",
":",
"if",
"use_l10n",
"or",
"(",
"use_l10n",
"is",
"None",
"and",
"settings",
".",
"USE_L10N",
")",
":",
"lang... | [
174,
0
] | [
192,
5
] | python | en | ['en', 'error', 'th'] | False |
localize | (value, use_l10n=None) |
Checks if value is a localizable type (date, number...) and returns it
formatted as a string using current locale format.
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
|
Checks if value is a localizable type (date, number...) and returns it
formatted as a string using current locale format. | def localize(value, use_l10n=None):
"""
Checks if value is a localizable type (date, number...) and returns it
formatted as a string using current locale format.
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
... | [
"def",
"localize",
"(",
"value",
",",
"use_l10n",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"# Handle strings first for performance reasons.",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
... | [
195,
0
] | [
215,
16
] | python | en | ['en', 'error', 'th'] | False |
localize_input | (value, default=None) |
Checks if an input value is a localizable type and returns it
formatted with the appropriate formatting string of the current locale.
|
Checks if an input value is a localizable type and returns it
formatted with the appropriate formatting string of the current locale.
| def localize_input(value, default=None):
"""
Checks if an input value is a localizable type and returns it
formatted with the appropriate formatting string of the current locale.
"""
if isinstance(value, six.string_types): # Handle strings first for performance reasons.
return value
eli... | [
"def",
"localize_input",
"(",
"value",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"# Handle strings first for performance reasons.",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
"... | [
218,
0
] | [
240,
16
] | python | en | ['en', 'error', 'th'] | False |
sanitize_separators | (value) |
Sanitizes a value according to the current decimal and
thousand separator setting. Used with form field input.
|
Sanitizes a value according to the current decimal and
thousand separator setting. Used with form field input.
| def sanitize_separators(value):
"""
Sanitizes a value according to the current decimal and
thousand separator setting. Used with form field input.
"""
if settings.USE_L10N and isinstance(value, six.string_types):
parts = []
decimal_separator = get_format('DECIMAL_SEPARATOR')
... | [
"def",
"sanitize_separators",
"(",
"value",
")",
":",
"if",
"settings",
".",
"USE_L10N",
"and",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"parts",
"=",
"[",
"]",
"decimal_separator",
"=",
"get_format",
"(",
"'DECIMAL_SEPARATOR'",
... | [
243,
0
] | [
265,
16
] | python | en | ['en', 'error', 'th'] | False |
Query.garbage_collect | (cls) |
Deletes all Query records that have no daily hits or editors picks
|
Deletes all Query records that have no daily hits or editors picks
| def garbage_collect(cls):
"""
Deletes all Query records that have no daily hits or editors picks
"""
extra_filter_kwargs = {'editors_picks__isnull': True, } if hasattr(cls, 'editors_picks') \
else {}
cls.objects.filter(daily_hits__isnull=True, **extra_filter_kwargs).d... | [
"def",
"garbage_collect",
"(",
"cls",
")",
":",
"extra_filter_kwargs",
"=",
"{",
"'editors_picks__isnull'",
":",
"True",
",",
"}",
"if",
"hasattr",
"(",
"cls",
",",
"'editors_picks'",
")",
"else",
"{",
"}",
"cls",
".",
"objects",
".",
"filter",
"(",
"daily... | [
35,
4
] | [
41,
83
] | python | en | ['en', 'error', 'th'] | False |
QueryDailyHits.garbage_collect | (cls, days=None) |
Deletes all QueryDailyHits records that are older than a set number of days
|
Deletes all QueryDailyHits records that are older than a set number of days
| def garbage_collect(cls, days=None):
"""
Deletes all QueryDailyHits records that are older than a set number of days
"""
days = getattr(settings, 'WAGTAILSEARCH_HITS_MAX_AGE', 7) if days is None else days
min_date = timezone.now().date() - datetime.timedelta(days)
cls.ob... | [
"def",
"garbage_collect",
"(",
"cls",
",",
"days",
"=",
"None",
")",
":",
"days",
"=",
"getattr",
"(",
"settings",
",",
"'WAGTAILSEARCH_HITS_MAX_AGE'",
",",
"7",
")",
"if",
"days",
"is",
"None",
"else",
"days",
"min_date",
"=",
"timezone",
".",
"now",
"(... | [
61,
4
] | [
68,
54
] | python | en | ['en', 'error', 'th'] | False |
parse_distutils_args | (args) | Parse provided arguments, returning an object that has the
matched arguments.
Any unknown arguments are ignored.
| Parse provided arguments, returning an object that has the
matched arguments. | def parse_distutils_args(args):
# type: (List[str]) -> Dict[str, str]
"""Parse provided arguments, returning an object that has the
matched arguments.
Any unknown arguments are ignored.
"""
result = {}
for arg in args:
try:
_, match = _distutils_getopt.getopt(args=[arg])... | [
"def",
"parse_distutils_args",
"(",
"args",
")",
":",
"# type: (List[str]) -> Dict[str, str]",
"result",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"try",
":",
"_",
",",
"match",
"=",
"_distutils_getopt",
".",
"getopt",
"(",
"args",
"=",
"[",
"arg",
"... | [
29,
0
] | [
47,
17
] | python | en | ['en', 'en', 'en'] | True |
get_connection | (using=None) |
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
|
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
| def get_connection(using=None):
"""
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
"""
if using is None:
using = DEFAULT_DB_ALIAS
return connections[using] | [
"def",
"get_connection",
"(",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"None",
":",
"using",
"=",
"DEFAULT_DB_ALIAS",
"return",
"connections",
"[",
"using",
"]"
] | [
13,
0
] | [
20,
29
] | python | en | ['en', 'error', 'th'] | False |
get_autocommit | (using=None) |
Get the autocommit status of the connection.
|
Get the autocommit status of the connection.
| def get_autocommit(using=None):
"""
Get the autocommit status of the connection.
"""
return get_connection(using).get_autocommit() | [
"def",
"get_autocommit",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"get_autocommit",
"(",
")"
] | [
23,
0
] | [
27,
49
] | python | en | ['en', 'error', 'th'] | False |
set_autocommit | (autocommit, using=None) |
Set the autocommit status of the connection.
|
Set the autocommit status of the connection.
| def set_autocommit(autocommit, using=None):
"""
Set the autocommit status of the connection.
"""
return get_connection(using).set_autocommit(autocommit) | [
"def",
"set_autocommit",
"(",
"autocommit",
",",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"set_autocommit",
"(",
"autocommit",
")"
] | [
30,
0
] | [
34,
59
] | python | en | ['en', 'error', 'th'] | False |
commit | (using=None) |
Commits a transaction.
|
Commits a transaction.
| def commit(using=None):
"""
Commits a transaction.
"""
get_connection(using).commit() | [
"def",
"commit",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"commit",
"(",
")"
] | [
37,
0
] | [
41,
34
] | python | en | ['en', 'error', 'th'] | False |
rollback | (using=None) |
Rolls back a transaction.
|
Rolls back a transaction.
| def rollback(using=None):
"""
Rolls back a transaction.
"""
get_connection(using).rollback() | [
"def",
"rollback",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"rollback",
"(",
")"
] | [
44,
0
] | [
48,
36
] | python | en | ['en', 'error', 'th'] | False |
savepoint | (using=None) |
Creates a savepoint (if supported and required by the backend) inside the
current transaction. Returns an identifier for the savepoint that will be
used for the subsequent rollback or commit.
|
Creates a savepoint (if supported and required by the backend) inside the
current transaction. Returns an identifier for the savepoint that will be
used for the subsequent rollback or commit.
| def savepoint(using=None):
"""
Creates a savepoint (if supported and required by the backend) inside the
current transaction. Returns an identifier for the savepoint that will be
used for the subsequent rollback or commit.
"""
return get_connection(using).savepoint() | [
"def",
"savepoint",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"savepoint",
"(",
")"
] | [
51,
0
] | [
57,
44
] | python | en | ['en', 'error', 'th'] | False |
savepoint_rollback | (sid, using=None) |
Rolls back the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
|
Rolls back the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
| def savepoint_rollback(sid, using=None):
"""
Rolls back the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
"""
get_connection(using).savepoint_rollback(sid) | [
"def",
"savepoint_rollback",
"(",
"sid",
",",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"savepoint_rollback",
"(",
"sid",
")"
] | [
60,
0
] | [
65,
49
] | python | en | ['en', 'error', 'th'] | False |
savepoint_commit | (sid, using=None) |
Commits the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
|
Commits the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
| def savepoint_commit(sid, using=None):
"""
Commits the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
"""
get_connection(using).savepoint_commit(sid) | [
"def",
"savepoint_commit",
"(",
"sid",
",",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"savepoint_commit",
"(",
"sid",
")"
] | [
68,
0
] | [
73,
47
] | python | en | ['en', 'error', 'th'] | False |
clean_savepoints | (using=None) |
Resets the counter used to generate unique savepoint ids in this thread.
|
Resets the counter used to generate unique savepoint ids in this thread.
| def clean_savepoints(using=None):
"""
Resets the counter used to generate unique savepoint ids in this thread.
"""
get_connection(using).clean_savepoints() | [
"def",
"clean_savepoints",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"clean_savepoints",
"(",
")"
] | [
76,
0
] | [
80,
44
] | python | en | ['en', 'error', 'th'] | False |
get_rollback | (using=None) |
Gets the "needs rollback" flag -- for *advanced use* only.
|
Gets the "needs rollback" flag -- for *advanced use* only.
| def get_rollback(using=None):
"""
Gets the "needs rollback" flag -- for *advanced use* only.
"""
return get_connection(using).get_rollback() | [
"def",
"get_rollback",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"get_rollback",
"(",
")"
] | [
83,
0
] | [
87,
47
] | python | en | ['en', 'error', 'th'] | False |
set_rollback | (rollback, using=None) |
Sets or unsets the "needs rollback" flag -- for *advanced use* only.
When `rollback` is `True`, it triggers a rollback when exiting the
innermost enclosing atomic block that has `savepoint=True` (that's the
default). Use this to force a rollback without raising an exception.
When `rollback` is `F... |
Sets or unsets the "needs rollback" flag -- for *advanced use* only. | def set_rollback(rollback, using=None):
"""
Sets or unsets the "needs rollback" flag -- for *advanced use* only.
When `rollback` is `True`, it triggers a rollback when exiting the
innermost enclosing atomic block that has `savepoint=True` (that's the
default). Use this to force a rollback without r... | [
"def",
"set_rollback",
"(",
"rollback",
",",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"set_rollback",
"(",
"rollback",
")"
] | [
90,
0
] | [
102,
55
] | python | en | ['en', 'error', 'th'] | False |
on_commit | (func, using=None) |
Register `func` to be called when the current transaction is committed.
If the current transaction is rolled back, `func` will not be called.
|
Register `func` to be called when the current transaction is committed.
If the current transaction is rolled back, `func` will not be called.
| def on_commit(func, using=None):
"""
Register `func` to be called when the current transaction is committed.
If the current transaction is rolled back, `func` will not be called.
"""
get_connection(using).on_commit(func) | [
"def",
"on_commit",
"(",
"func",
",",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"on_commit",
"(",
"func",
")"
] | [
105,
0
] | [
110,
41
] | python | en | ['en', 'error', 'th'] | False |
get_rendition_or_not_found | (image, specs) |
Tries to get / create the rendition for the image or renders a not-found image if it does not exist.
:param image: AbstractImage
:param specs: str or Filter
:return: Rendition
|
Tries to get / create the rendition for the image or renders a not-found image if it does not exist. | def get_rendition_or_not_found(image, specs):
"""
Tries to get / create the rendition for the image or renders a not-found image if it does not exist.
:param image: AbstractImage
:param specs: str or Filter
:return: Rendition
"""
try:
return image.get_rendition(specs)
except Sou... | [
"def",
"get_rendition_or_not_found",
"(",
"image",
",",
"specs",
")",
":",
"try",
":",
"return",
"image",
".",
"get_rendition",
"(",
"specs",
")",
"except",
"SourceImageIOError",
":",
"# Image file is (probably) missing from /media/original_images - generate a dummy",
"# re... | [
3,
0
] | [
20,
24
] | python | en | ['en', 'error', 'th'] | False |
FootballEnvCore.reset | (self, inc=1) | Reset environment for a new episode using a given config. | Reset environment for a new episode using a given config. | def reset(self, inc=1):
"""Reset environment for a new episode using a given config."""
self._episode_start = timeit.default_timer()
self._action_set = football_action_set.get_action_set(self._config)
trace = observation_processor.ObservationProcessor(self._config)
self._cumulative_reward = 0
se... | [
"def",
"reset",
"(",
"self",
",",
"inc",
"=",
"1",
")",
":",
"self",
".",
"_episode_start",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"self",
".",
"_action_set",
"=",
"football_action_set",
".",
"get_action_set",
"(",
"self",
".",
"_config",
")",
"t... | [
83,
2
] | [
94,
15
] | python | en | ['en', 'en', 'en'] | True |
FootballEnvCore._retrieve_observation | (self) | Constructs observations exposed by the environment.
Returns whether game
is on or not.
| Constructs observations exposed by the environment. | def _retrieve_observation(self):
"""Constructs observations exposed by the environment.
Returns whether game
is on or not.
"""
info = self._env.get_info()
result = {}
if self._env.game_config.render:
frame = self._env.get_frame()
frame = np.frombuffer(frame, dtype=np.uint8)
... | [
"def",
"_retrieve_observation",
"(",
"self",
")",
":",
"info",
"=",
"self",
".",
"_env",
".",
"get_info",
"(",
")",
"result",
"=",
"{",
"}",
"if",
"self",
".",
"_env",
".",
"game_config",
".",
"render",
":",
"frame",
"=",
"self",
".",
"_env",
".",
... | [
236,
2
] | [
288,
26
] | python | en | ['en', 'en', 'en'] | True |
FootballEnvCore._convert_players_observation | (self, players, name, result) | Converts internal players representation to the public one.
Internal representation comes directly from gameplayfootball engine.
Public representation is part of environment observations.
Args:
players: collection of team players to convert.
name: name of the team being converted (left_t... | Converts internal players representation to the public one. | def _convert_players_observation(self, players, name, result):
"""Converts internal players representation to the public one.
Internal representation comes directly from gameplayfootball engine.
Public representation is part of environment observations.
Args:
players: collection of team pl... | [
"def",
"_convert_players_observation",
"(",
"self",
",",
"players",
",",
"name",
",",
"result",
")",
":",
"positions",
"=",
"[",
"]",
"directions",
"=",
"[",
"]",
"tired_factors",
"=",
"[",
"]",
"active",
"=",
"[",
"]",
"yellow_cards",
"=",
"[",
"]",
"... | [
290,
2
] | [
324,
53
] | python | en | ['en', 'en', 'en'] | True |
FootballEnvCore.observation | (self) | Returns the current observation of the game. | Returns the current observation of the game. | def observation(self):
"""Returns the current observation of the game."""
assert (self._env.state == GameState.game_running or
self._env.state == GameState.game_done), (
'reset() must be called before observation()')
return copy.deepcopy(self._observation) | [
"def",
"observation",
"(",
"self",
")",
":",
"assert",
"(",
"self",
".",
"_env",
".",
"state",
"==",
"GameState",
".",
"game_running",
"or",
"self",
".",
"_env",
".",
"state",
"==",
"GameState",
".",
"game_done",
")",
",",
"(",
"'reset() must be called bef... | [
326,
2
] | [
331,
43
] | python | en | ['en', 'en', 'en'] | True |
get_current_request | () | Returns the current HttpRequest object; this should only be used by
logging frameworks, which have no other access to the current
request. All other codepaths should pass through the current
request object, rather than rely on this thread-local global.
| Returns the current HttpRequest object; this should only be used by
logging frameworks, which have no other access to the current
request. All other codepaths should pass through the current
request object, rather than rely on this thread-local global. | def get_current_request() -> Optional[HttpRequest]:
"""Returns the current HttpRequest object; this should only be used by
logging frameworks, which have no other access to the current
request. All other codepaths should pass through the current
request object, rather than rely on this thread-local glo... | [
"def",
"get_current_request",
"(",
")",
"->",
"Optional",
"[",
"HttpRequest",
"]",
":",
"return",
"getattr",
"(",
"local",
",",
"\"request\"",
",",
"None",
")"
] | [
397,
0
] | [
404,
42
] | python | en | ['en', 'en', 'en'] | True |
_REQ.__init__ | (
self,
whence: Optional[str] = None,
*,
converter: Optional[Callable[[str], ResultT]] = None,
default: Union[_NotSpecified, ResultT, None] = NotSpecified,
json_validator: Optional[Validator[ResultT]] = None,
str_validator: Optional[Validator[ResultT]] = None,
... | whence: the name of the request variable that should be used
for this parameter. Defaults to a request variable of the
same name as the parameter.
converter: a function that takes a string and returns a new
value. If specified, this will be called on the request
variable value... | whence: the name of the request variable that should be used
for this parameter. Defaults to a request variable of the
same name as the parameter. | def __init__(
self,
whence: Optional[str] = None,
*,
converter: Optional[Callable[[str], ResultT]] = None,
default: Union[_NotSpecified, ResultT, None] = NotSpecified,
json_validator: Optional[Validator[ResultT]] = None,
str_validator: Optional[Validator[ResultT]]... | [
"def",
"__init__",
"(",
"self",
",",
"whence",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"*",
",",
"converter",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"str",
"]",
",",
"ResultT",
"]",
"]",
"=",
"None",
",",
"default",
":",
"Union",
... | [
79,
4
] | [
138,
68
] | python | en | ['en', 'en', 'en'] | True |
InvertedPlanarFlow.get_param_size | (n_dims) |
:param n_dims: The dimension of the distribution to be transformed by the flow
:return: (int) The dimension of the parameter space for this flow, n_dims + n_dims + 1
|
:param n_dims: The dimension of the distribution to be transformed by the flow
:return: (int) The dimension of the parameter space for this flow, n_dims + n_dims + 1
| def get_param_size(n_dims):
"""
:param n_dims: The dimension of the distribution to be transformed by the flow
:return: (int) The dimension of the parameter space for this flow, n_dims + n_dims + 1
"""
return n_dims + n_dims + 1 | [
"def",
"get_param_size",
"(",
"n_dims",
")",
":",
"return",
"n_dims",
"+",
"n_dims",
"+",
"1"
] | [
32,
4
] | [
37,
34
] | python | en | ['en', 'error', 'th'] | False |
InvertedPlanarFlow._u_circ | (u, w) |
To ensure invertibility of the flow, the following condition needs to hold: w_t * u >= -1
:return: The transformed u
|
To ensure invertibility of the flow, the following condition needs to hold: w_t * u >= -1
:return: The transformed u
| def _u_circ(u, w):
"""
To ensure invertibility of the flow, the following condition needs to hold: w_t * u >= -1
:return: The transformed u
"""
wtu = tf.reduce_sum(w*u, 1, keepdims=True)
m_wtu = -1. + tf.nn.softplus(wtu) + 1e-3
norm_w_squared = tf.reduce_sum(w**2,... | [
"def",
"_u_circ",
"(",
"u",
",",
"w",
")",
":",
"wtu",
"=",
"tf",
".",
"reduce_sum",
"(",
"w",
"*",
"u",
",",
"1",
",",
"keepdims",
"=",
"True",
")",
"m_wtu",
"=",
"-",
"1.",
"+",
"tf",
".",
"nn",
".",
"softplus",
"(",
"wtu",
")",
"+",
"1e-... | [
40,
4
] | [
48,
51
] | python | en | ['en', 'error', 'th'] | False |
InvertedPlanarFlow._wzb | (self, z) |
Computes w_t * z + b
|
Computes w_t * z + b
| def _wzb(self, z):
"""
Computes w_t * z + b
"""
return tf.reduce_sum(self._w * z, 1, keepdims=True) + self._b | [
"def",
"_wzb",
"(",
"self",
",",
"z",
")",
":",
"return",
"tf",
".",
"reduce_sum",
"(",
"self",
".",
"_w",
"*",
"z",
",",
"1",
",",
"keepdims",
"=",
"True",
")",
"+",
"self",
".",
"_b"
] | [
50,
4
] | [
54,
69
] | python | en | ['en', 'error', 'th'] | False |
InvertedPlanarFlow._der_tanh | (z) |
Computes the derivative of hyperbolic tangent
|
Computes the derivative of hyperbolic tangent
| def _der_tanh(z):
"""
Computes the derivative of hyperbolic tangent
"""
return 1. - tf.tanh(z) ** 2 | [
"def",
"_der_tanh",
"(",
"z",
")",
":",
"return",
"1.",
"-",
"tf",
".",
"tanh",
"(",
"z",
")",
"**",
"2"
] | [
57,
4
] | [
61,
35
] | python | en | ['en', 'error', 'th'] | False |
InvertedPlanarFlow._inverse | (self, z) |
Runs a backward pass through the bijector
Also checks for whether the flow is actually invertible
|
Runs a backward pass through the bijector
Also checks for whether the flow is actually invertible
| def _inverse(self, z):
"""
Runs a backward pass through the bijector
Also checks for whether the flow is actually invertible
"""
z = InvertedPlanarFlow._handle_input_dimensionality(z)
uw = tf.reduce_sum(self._w * self._u, 1)
invertible = tf.assert_greater_equal(uw... | [
"def",
"_inverse",
"(",
"self",
",",
"z",
")",
":",
"z",
"=",
"InvertedPlanarFlow",
".",
"_handle_input_dimensionality",
"(",
"z",
")",
"uw",
"=",
"tf",
".",
"reduce_sum",
"(",
"self",
".",
"_w",
"*",
"self",
".",
"_u",
",",
"1",
")",
"invertible",
"... | [
63,
4
] | [
72,
54
] | python | en | ['en', 'error', 'th'] | False |
InvertedPlanarFlow.forward | (self, x) |
We don't require sampling and it would be slow, therefore it is not implemented
:raise NotImplementedError:
|
We don't require sampling and it would be slow, therefore it is not implemented | def forward(self, x):
"""
We don't require sampling and it would be slow, therefore it is not implemented
:raise NotImplementedError:
"""
raise NotImplementedError() | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
74,
4
] | [
80,
35
] | python | en | ['en', 'error', 'th'] | False |
InvertedPlanarFlow._ildj | (self, z) |
Computes the ln of the absolute determinant of the jacobian
|
Computes the ln of the absolute determinant of the jacobian
| def _ildj(self, z):
"""
Computes the ln of the absolute determinant of the jacobian
"""
z = InvertedPlanarFlow._handle_input_dimensionality(z)
psi = self._der_tanh(self._wzb(z)) * self._w
det_grad = 1. + tf.reduce_sum(self._u * psi, 1, keepdims=True)
return tf.log... | [
"def",
"_ildj",
"(",
"self",
",",
"z",
")",
":",
"z",
"=",
"InvertedPlanarFlow",
".",
"_handle_input_dimensionality",
"(",
"z",
")",
"psi",
"=",
"self",
".",
"_der_tanh",
"(",
"self",
".",
"_wzb",
"(",
"z",
")",
")",
"*",
"self",
".",
"_w",
"det_grad... | [
82,
4
] | [
89,
39
] | python | en | ['en', 'error', 'th'] | False |
update_realmauditlog_values | (apps: StateApps, schema_editor: DatabaseSchemaEditor) |
This migration fixes two issues with the RealmAuditLog format for certain event types:
* The notifications_stream and signup_notifications_stream fields had the
Stream objects passed into `ujson.dumps()` and thus marshalled as a giant
JSON object, when the intent was to store the stream ID.
* T... |
This migration fixes two issues with the RealmAuditLog format for certain event types:
* The notifications_stream and signup_notifications_stream fields had the
Stream objects passed into `ujson.dumps()` and thus marshalled as a giant
JSON object, when the intent was to store the stream ID.
* T... | def update_realmauditlog_values(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""
This migration fixes two issues with the RealmAuditLog format for certain event types:
* The notifications_stream and signup_notifications_stream fields had the
Stream objects passed into `ujson.dumps()`... | [
"def",
"update_realmauditlog_values",
"(",
"apps",
":",
"StateApps",
",",
"schema_editor",
":",
"DatabaseSchemaEditor",
")",
"->",
"None",
":",
"RealmAuditLog",
"=",
"apps",
".",
"get_model",
"(",
"\"zerver\"",
",",
"\"RealmAuditLog\"",
")",
"# Constants from models.p... | [
9,
0
] | [
105,
45
] | python | en | ['en', 'error', 'th'] | False |
Collection.get_view_restrictions | (self) | Return a query set of all collection view restrictions that apply to this collection | Return a query set of all collection view restrictions that apply to this collection | def get_view_restrictions(self):
"""Return a query set of all collection view restrictions that apply to this collection"""
return CollectionViewRestriction.objects.filter(collection__in=self.get_ancestors(inclusive=True)) | [
"def",
"get_view_restrictions",
"(",
"self",
")",
":",
"return",
"CollectionViewRestriction",
".",
"objects",
".",
"filter",
"(",
"collection__in",
"=",
"self",
".",
"get_ancestors",
"(",
"inclusive",
"=",
"True",
")",
")"
] | [
65,
4
] | [
67,
106
] | python | en | ['en', 'en', 'en'] | True |
Collection.get_indented_name | (self, indentation_start_depth=2, html=False) |
Renders this Collection's name as a formatted string that displays its hierarchical depth via indentation.
If indentation_start_depth is supplied, the Collection's depth is rendered relative to that depth.
indentation_start_depth defaults to 2, the depth of the first non-Root Collection.
... |
Renders this Collection's name as a formatted string that displays its hierarchical depth via indentation.
If indentation_start_depth is supplied, the Collection's depth is rendered relative to that depth.
indentation_start_depth defaults to 2, the depth of the first non-Root Collection.
... | def get_indented_name(self, indentation_start_depth=2, html=False):
"""
Renders this Collection's name as a formatted string that displays its hierarchical depth via indentation.
If indentation_start_depth is supplied, the Collection's depth is rendered relative to that depth.
indentatio... | [
"def",
"get_indented_name",
"(",
"self",
",",
"indentation_start_depth",
"=",
"2",
",",
"html",
"=",
"False",
")",
":",
"display_depth",
"=",
"self",
".",
"depth",
"-",
"indentation_start_depth",
"# A Collection with a display depth of 0 or less (Root's can be -1), should h... | [
69,
4
] | [
95,
68
] | python | en | ['en', 'error', 'th'] | False |
configrunner.test_store_load_configrunner_pipeline | (self) | check if model dumps have all been created | check if model dumps have all been created | def test_store_load_configrunner_pipeline(self):
logger.configure(log_directory=config.DATA_DIR, prefix=EXP_PREFIX)
test_dir = os.path.join(logger.log_directory, logger.prefix)
if os.path.exists(test_dir):
shutil.rmtree(test_dir)
keys_of_interest = ['task_name', 'estimator', 'simulator', 'n_obs... | [
"def",
"test_store_load_configrunner_pipeline",
"(",
"self",
")",
":",
"logger",
".",
"configure",
"(",
"log_directory",
"=",
"config",
".",
"DATA_DIR",
",",
"prefix",
"=",
"EXP_PREFIX",
")",
"test_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"logger",
".... | [
21,
2
] | [
61,
51
] | python | en | ['en', 'en', 'en'] | True |
get_static_prefix | (parser, token) |
Populates a template variable with the static prefix,
``settings.STATIC_URL``.
Usage::
{% get_static_prefix [as varname] %}
Examples::
{% get_static_prefix %}
{% get_static_prefix as static_prefix %}
|
Populates a template variable with the static prefix,
``settings.STATIC_URL``. | def get_static_prefix(parser, token):
"""
Populates a template variable with the static prefix,
``settings.STATIC_URL``.
Usage::
{% get_static_prefix [as varname] %}
Examples::
{% get_static_prefix %}
{% get_static_prefix as static_prefix %}
"""
return PrefixNode.... | [
"def",
"get_static_prefix",
"(",
"parser",
",",
"token",
")",
":",
"return",
"PrefixNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
",",
"\"STATIC_URL\"",
")"
] | [
56,
0
] | [
70,
63
] | python | en | ['en', 'error', 'th'] | False |
get_media_prefix | (parser, token) |
Populates a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
|
Populates a template variable with the media prefix,
``settings.MEDIA_URL``. | def get_media_prefix(parser, token):
"""
Populates a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
"""
return PrefixNode.handle_... | [
"def",
"get_media_prefix",
"(",
"parser",
",",
"token",
")",
":",
"return",
"PrefixNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
",",
"\"MEDIA_URL\"",
")"
] | [
74,
0
] | [
88,
62
] | python | en | ['en', 'error', 'th'] | False |
do_static | (parser, token) |
Joins the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_with_path as varname %}
... |
Joins the given path with the STATIC_URL setting. | def do_static(parser, token):
"""
Joins the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% stati... | [
"def",
"do_static",
"(",
"parser",
",",
"token",
")",
":",
"return",
"StaticNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
")"
] | [
142,
0
] | [
157,
49
] | python | en | ['en', 'error', 'th'] | False |
static | (path) |
Given a relative path to a static asset, return the absolute path to the
asset.
|
Given a relative path to a static asset, return the absolute path to the
asset.
| def static(path):
"""
Given a relative path to a static asset, return the absolute path to the
asset.
"""
return StaticNode.handle_simple(path) | [
"def",
"static",
"(",
"path",
")",
":",
"return",
"StaticNode",
".",
"handle_simple",
"(",
"path",
")"
] | [
160,
0
] | [
165,
41
] | python | en | ['en', 'error', 'th'] | False |
PrefixNode.handle_token | (cls, parser, token, name) |
Class method to parse prefix node and return a Node.
|
Class method to parse prefix node and return a Node.
| def handle_token(cls, parser, token, name):
"""
Class method to parse prefix node and return a Node.
"""
# token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
tokens = token.contents.split()
if len(tokens) > 1 and tok... | [
"def",
"handle_token",
"(",
"cls",
",",
"parser",
",",
"token",
",",
"name",
")",
":",
"# token.split_contents() isn't useful here because tags using this method don't accept variable as arguments",
"tokens",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
... | [
22,
4
] | [
35,
33
] | python | en | ['en', 'error', 'th'] | False |
StaticNode.handle_token | (cls, parser, token) |
Class method to parse prefix node and return a Node.
|
Class method to parse prefix node and return a Node.
| def handle_token(cls, parser, token):
"""
Class method to parse prefix node and return a Node.
"""
bits = token.split_contents()
if len(bits) < 2:
raise template.TemplateSyntaxError(
"'%s' takes at least one argument (path to file)" % bits[0])
... | [
"def",
"handle_token",
"(",
"cls",
",",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"'%s' takes at least one ... | [
121,
4
] | [
138,
33
] | python | en | ['en', 'error', 'th'] | False |
get_field_clean_name | (label) |
Converts a user entered field label to a template and JSON safe ascii value to be used
as the internal key (clean name) for the field.
|
Converts a user entered field label to a template and JSON safe ascii value to be used
as the internal key (clean name) for the field.
| def get_field_clean_name(label):
"""
Converts a user entered field label to a template and JSON safe ascii value to be used
as the internal key (clean name) for the field.
"""
return safe_snake_case(label) | [
"def",
"get_field_clean_name",
"(",
"label",
")",
":",
"return",
"safe_snake_case",
"(",
"label",
")"
] | [
10,
0
] | [
15,
33
] | python | en | ['en', 'error', 'th'] | False |
get_forms_for_user | (user) |
Return a queryset of form pages that this user is allowed to access the submissions for
|
Return a queryset of form pages that this user is allowed to access the submissions for
| def get_forms_for_user(user):
"""
Return a queryset of form pages that this user is allowed to access the submissions for
"""
editable_forms = UserPagePermissionsProxy(user).editable_pages()
editable_forms = editable_forms.filter(content_type__in=get_form_types())
# Apply hooks
for fn in ho... | [
"def",
"get_forms_for_user",
"(",
"user",
")",
":",
"editable_forms",
"=",
"UserPagePermissionsProxy",
"(",
"user",
")",
".",
"editable_pages",
"(",
")",
"editable_forms",
"=",
"editable_forms",
".",
"filter",
"(",
"content_type__in",
"=",
"get_form_types",
"(",
"... | [
33,
0
] | [
44,
25
] | python | en | ['en', 'error', 'th'] | False |
_eventlet_serve | (sock, handle, concurrency) |
Serve requests forever.
This code is nearly identical to ``eventlet.convenience.serve`` except
that it attempts to join the pool at the end, which allows for gunicorn
graceful shutdowns.
|
Serve requests forever. | def _eventlet_serve(sock, handle, concurrency):
"""
Serve requests forever.
This code is nearly identical to ``eventlet.convenience.serve`` except
that it attempts to join the pool at the end, which allows for gunicorn
graceful shutdowns.
"""
pool = eventlet.greenpool.GreenPool(concurrency)... | [
"def",
"_eventlet_serve",
"(",
"sock",
",",
"handle",
",",
"concurrency",
")",
":",
"pool",
"=",
"eventlet",
".",
"greenpool",
".",
"GreenPool",
"(",
"concurrency",
")",
"server_gt",
"=",
"eventlet",
".",
"greenthread",
".",
"getcurrent",
"(",
")",
"while",
... | [
39,
0
] | [
59,
18
] | python | en | ['en', 'error', 'th'] | False |
_eventlet_stop | (client, server, conn) |
Stop a greenlet handling a request and close its connection.
This code is lifted from eventlet so as not to depend on undocumented
functions in the library.
|
Stop a greenlet handling a request and close its connection. | def _eventlet_stop(client, server, conn):
"""
Stop a greenlet handling a request and close its connection.
This code is lifted from eventlet so as not to depend on undocumented
functions in the library.
"""
try:
try:
client.wait()
finally:
conn.close()
... | [
"def",
"_eventlet_stop",
"(",
"client",
",",
"server",
",",
"conn",
")",
":",
"try",
":",
"try",
":",
"client",
".",
"wait",
"(",
")",
"finally",
":",
"conn",
".",
"close",
"(",
")",
"except",
"greenlet",
".",
"GreenletExit",
":",
"pass",
"except",
"... | [
62,
0
] | [
77,
49
] | python | en | ['en', 'error', 'th'] | False |
fast_computation | (fastQ) | Function for turning on/off GPyTorch fast computation features.
Parameters
----------
fastQ : bool
If True, gpytorch fast computation features will be utilized. Modified
settings include: (1) fast_pred_var, (2) fast_pred_samples,
(3) covar_root_decomposition, (4) log_p... | Function for turning on/off GPyTorch fast computation features.
Parameters
----------
fastQ : bool
If True, gpytorch fast computation features will be utilized. Modified
settings include: (1) fast_pred_var, (2) fast_pred_samples,
(3) covar_root_decomposition, (4) log_p... | def fast_computation(fastQ):
"""Function for turning on/off GPyTorch fast computation features.
Parameters
----------
fastQ : bool
If True, gpytorch fast computation features will be utilized. Modified
settings include: (1) fast_pred_var, (2) fast_pred_samples,
(3)... | [
"def",
"fast_computation",
"(",
"fastQ",
")",
":",
"gpytorch",
".",
"settings",
".",
"fast_pred_var",
".",
"_state",
"=",
"fastQ",
"gpytorch",
".",
"settings",
".",
"fast_pred_samples",
".",
"_state",
"=",
"fastQ",
"gpytorch",
".",
"settings",
".",
"fast_compu... | [
149,
0
] | [
171,
53
] | python | en | ['en', 'en', 'en'] | True |
gp_model.__init__ | (self, X, y, likelihood, gpu=False, nu=2.5,
lengthscale_prior=None, outputscale_prior=None
) |
Parameters
----------
X : torch.tensor
Training domain values.
y : torch.tensor
Training response values.
likelihood : (gpytorch.likelihoods)
Model likelihood.
gpu : bool
Use GPUs (if available) to run gaussian pr... |
Parameters
----------
X : torch.tensor
Training domain values.
y : torch.tensor
Training response values.
likelihood : (gpytorch.likelihoods)
Model likelihood.
gpu : bool
Use GPUs (if available) to run gaussian pr... | def __init__(self, X, y, likelihood, gpu=False, nu=2.5,
lengthscale_prior=None, outputscale_prior=None
):
"""
Parameters
----------
X : torch.tensor
Training domain values.
y : torch.tensor
Training response value... | [
"def",
"__init__",
"(",
"self",
",",
"X",
",",
"y",
",",
"likelihood",
",",
"gpu",
"=",
"False",
",",
"nu",
"=",
"2.5",
",",
"lengthscale_prior",
"=",
"None",
",",
"outputscale_prior",
"=",
"None",
")",
":",
"super",
"(",
"gp_model",
",",
"self",
")"... | [
23,
4
] | [
84,
51
] | python | en | ['en', 'ja', 'th'] | False |
gp_model.forward | (self, x) |
Parameters
----------
x : torch.tensor
Domain points which define multivariate normal distribution.
Returns
----------
gpytorch.MultivariateNormal
Multivariate normal distribution.
|
Parameters
----------
x : torch.tensor
Domain points which define multivariate normal distribution.
Returns
----------
gpytorch.MultivariateNormal
Multivariate normal distribution.
| def forward(self, x):
"""
Parameters
----------
x : torch.tensor
Domain points which define multivariate normal distribution.
Returns
----------
gpytorch.MultivariateNormal
Multivariate normal distribution.
"""
... | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"mean_x",
"=",
"self",
".",
"mean_module",
"(",
"x",
")",
"covar_x",
"=",
"self",
".",
"covar_module",
"(",
"x",
")",
"return",
"MultivariateNormal",
"(",
"mean_x",
",",
"covar_x",
")"
] | [
87,
4
] | [
103,
50
] | python | en | ['en', 'ja', 'th'] | False |
random_forest.__init__ | (self, n_jobs=-1, random_state=10, n_estimators=500,
max_features='auto', max_depth=None, min_samples_leaf=1,
min_samples_split=2) |
Parameters
----------
n_jobs : int
Number of processers to use.
random_state : int
Insures identical data returns an identical ensemble of regression
trees.
n_estimators : int
Number of weak estimators to include in ensem... |
Parameters
----------
n_jobs : int
Number of processers to use.
random_state : int
Insures identical data returns an identical ensemble of regression
trees.
n_estimators : int
Number of weak estimators to include in ensem... | def __init__(self, n_jobs=-1, random_state=10, n_estimators=500,
max_features='auto', max_depth=None, min_samples_leaf=1,
min_samples_split=2):
"""
Parameters
----------
n_jobs : int
Number of processers to use.
random_state : int
Insures ... | [
"def",
"__init__",
"(",
"self",
",",
"n_jobs",
"=",
"-",
"1",
",",
"random_state",
"=",
"10",
",",
"n_estimators",
"=",
"500",
",",
"max_features",
"=",
"'auto'",
",",
"max_depth",
"=",
"None",
",",
"min_samples_leaf",
"=",
"1",
",",
"min_samples_split",
... | [
116,
4
] | [
147,
45
] | python | en | ['en', 'ja', 'th'] | False |
Config.features | (self) | returns a list of enabled license features | returns a list of enabled license features | def features(self):
"""returns a list of enabled license features"""
return [k for k, v in self.license_info.get('features', {}).items() if v] | [
"def",
"features",
"(",
"self",
")",
":",
"return",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"license_info",
".",
"get",
"(",
"'features'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
"if",
"v",
"]"
] | [
27,
4
] | [
29,
81
] | python | en | ['en', 'en', 'en'] | True |
TestBlockingTasks.test_long_buf | (self) | subprocess (tast) became blocked and blocks parent (shellexec)
if exchange buffer (PIPE) is full because of wait() | subprocess (tast) became blocked and blocks parent (shellexec)
if exchange buffer (PIPE) is full because of wait() | def test_long_buf(self):
""" subprocess (tast) became blocked and blocks parent (shellexec)
if exchange buffer (PIPE) is full because of wait() """
file_name = temp_file()
if is_windows():
task = "type "
buf_len = 2 ** 10 * 4 # 4K
else:
task =... | [
"def",
"test_long_buf",
"(",
"self",
")",
":",
"file_name",
"=",
"temp_file",
"(",
")",
"if",
"is_windows",
"(",
")",
":",
"task",
"=",
"\"type \"",
"buf_len",
"=",
"2",
"**",
"10",
"*",
"4",
"# 4K",
"else",
":",
"task",
"=",
"\"tail \"",
"buf_len",
... | [
34,
4
] | [
54,
31
] | python | en | ['en', 'su', 'en'] | True |
with_metaclass | (meta, *bases) |
Create a base class with a metaclass.
|
Create a base class with a metaclass.
| def with_metaclass(meta, *bases):
# type: (Type[Any], Tuple[Type[Any], ...]) -> Any
"""
Create a base class with a metaclass.
"""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual me... | [
"def",
"with_metaclass",
"(",
"meta",
",",
"*",
"bases",
")",
":",
"# type: (Type[Any], Tuple[Type[Any], ...]) -> Any",
"# This requires a bit of explanation: the basic idea is to make a dummy",
"# metaclass for one level of class instantiation that replaces itself with",
"# the actual metac... | [
24,
0
] | [
37,
61
] | python | en | ['en', 'error', 'th'] | False |
resolve_relation | (scope_model, relation) |
Transform relation into a model or fully-qualified model string of the form
"app_label.ModelName", relative to scope_model.
The relation argument can be:
* RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case
the model argument will be returned.
* A bare model name wi... |
Transform relation into a model or fully-qualified model string of the form
"app_label.ModelName", relative to scope_model. | def resolve_relation(scope_model, relation):
"""
Transform relation into a model or fully-qualified model string of the form
"app_label.ModelName", relative to scope_model.
The relation argument can be:
* RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case
the model arg... | [
"def",
"resolve_relation",
"(",
"scope_model",
",",
"relation",
")",
":",
"# Check for recursive relations",
"if",
"relation",
"==",
"RECURSIVE_RELATIONSHIP_CONSTANT",
":",
"relation",
"=",
"scope_model",
"# Look for an \"app.Model\" relation",
"if",
"isinstance",
"(",
"rel... | [
41,
0
] | [
63,
19
] | python | en | ['en', 'error', 'th'] | False |
lazy_related_operation | (function, model, *related_models, **kwargs) |
Schedule `function` to be called once `model` and all `related_models`
have been imported and registered with the app registry. `function` will
be called with the newly-loaded model classes as its positional arguments,
plus any optional keyword arguments.
The `model` argument must be a model class... |
Schedule `function` to be called once `model` and all `related_models`
have been imported and registered with the app registry. `function` will
be called with the newly-loaded model classes as its positional arguments,
plus any optional keyword arguments. | def lazy_related_operation(function, model, *related_models, **kwargs):
"""
Schedule `function` to be called once `model` and all `related_models`
have been imported and registered with the app registry. `function` will
be called with the newly-loaded model classes as its positional arguments,
plus ... | [
"def",
"lazy_related_operation",
"(",
"function",
",",
"model",
",",
"*",
"related_models",
",",
"*",
"*",
"kwargs",
")",
":",
"models",
"=",
"[",
"model",
"]",
"+",
"[",
"resolve_relation",
"(",
"model",
",",
"rel",
")",
"for",
"rel",
"in",
"related_mod... | [
66,
0
] | [
84,
78
] | python | en | ['en', 'error', 'th'] | False |
RelatedField._check_clashes | (self) |
Check accessor and reverse query name clashes.
|
Check accessor and reverse query name clashes.
| def _check_clashes(self):
"""
Check accessor and reverse query name clashes.
"""
from django.db.models.base import ModelBase
errors = []
opts = self.model._meta
# `f.remote_field.model` may be a string instead of a model. Skip if model name is
# not reso... | [
"def",
"_check_clashes",
"(",
"self",
")",
":",
"from",
"django",
".",
"db",
".",
"models",
".",
"base",
"import",
"ModelBase",
"errors",
"=",
"[",
"]",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"# `f.remote_field.model` may be a string instead of a model... | [
217,
4
] | [
311,
21
] | python | en | ['en', 'error', 'th'] | False |
RelatedField.get_forward_related_filter | (self, obj) |
Return the keyword arguments that when supplied to
self.model.object.filter(), would select all instances related through
this field to the remote obj. This is used to build the querysets
returned by related descriptors. obj is an instance of
self.related_field.model.
|
Return the keyword arguments that when supplied to
self.model.object.filter(), would select all instances related through
this field to the remote obj. This is used to build the querysets
returned by related descriptors. obj is an instance of
self.related_field.model.
| def get_forward_related_filter(self, obj):
"""
Return the keyword arguments that when supplied to
self.model.object.filter(), would select all instances related through
this field to the remote obj. This is used to build the querysets
returned by related descriptors. obj is an in... | [
"def",
"get_forward_related_filter",
"(",
"self",
",",
"obj",
")",
":",
"return",
"{",
"'%s__%s'",
"%",
"(",
"self",
".",
"name",
",",
"rh_field",
".",
"name",
")",
":",
"getattr",
"(",
"obj",
",",
"rh_field",
".",
"attname",
")",
"for",
"_",
",",
"r... | [
349,
4
] | [
360,
9
] | python | en | ['en', 'error', 'th'] | False |
RelatedField.get_reverse_related_filter | (self, obj) |
Complement to get_forward_related_filter(). Return the keyword
arguments that when passed to self.related_field.model.object.filter()
select all instances of self.related_field.model related through
this field to obj. obj is an instance of self.model.
|
Complement to get_forward_related_filter(). Return the keyword
arguments that when passed to self.related_field.model.object.filter()
select all instances of self.related_field.model related through
this field to obj. obj is an instance of self.model.
| def get_reverse_related_filter(self, obj):
"""
Complement to get_forward_related_filter(). Return the keyword
arguments that when passed to self.related_field.model.object.filter()
select all instances of self.related_field.model related through
this field to obj. obj is an insta... | [
"def",
"get_reverse_related_filter",
"(",
"self",
",",
"obj",
")",
":",
"base_filter",
"=",
"{",
"rh_field",
".",
"attname",
":",
"getattr",
"(",
"obj",
",",
"lh_field",
".",
"attname",
")",
"for",
"lh_field",
",",
"rh_field",
"in",
"self",
".",
"related_f... | [
362,
4
] | [
379,
21
] | python | en | ['en', 'error', 'th'] | False |
RelatedField.swappable_setting | (self) |
Get the setting that this is powered from for swapping, or None
if it's not swapped in / marked with swappable=False.
|
Get the setting that this is powered from for swapping, or None
if it's not swapped in / marked with swappable=False.
| def swappable_setting(self):
"""
Get the setting that this is powered from for swapping, or None
if it's not swapped in / marked with swappable=False.
"""
if self.swappable:
# Work out string form of "to"
if isinstance(self.remote_field.model, six.string_t... | [
"def",
"swappable_setting",
"(",
"self",
")",
":",
"if",
"self",
".",
"swappable",
":",
"# Work out string form of \"to\"",
"if",
"isinstance",
"(",
"self",
".",
"remote_field",
".",
"model",
",",
"six",
".",
"string_types",
")",
":",
"to_string",
"=",
"self",... | [
382,
4
] | [
394,
19
] | python | en | ['en', 'error', 'th'] | False |
RelatedField.get_limit_choices_to | (self) |
Return ``limit_choices_to`` for this model field.
If it is a callable, it will be invoked and the result will be
returned.
|
Return ``limit_choices_to`` for this model field. | def get_limit_choices_to(self):
"""
Return ``limit_choices_to`` for this model field.
If it is a callable, it will be invoked and the result will be
returned.
"""
if callable(self.remote_field.limit_choices_to):
return self.remote_field.limit_choices_to()
... | [
"def",
"get_limit_choices_to",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"self",
".",
"remote_field",
".",
"limit_choices_to",
")",
":",
"return",
"self",
".",
"remote_field",
".",
"limit_choices_to",
"(",
")",
"return",
"self",
".",
"remote_field",
".",
... | [
409,
4
] | [
418,
49
] | python | en | ['en', 'error', 'th'] | False |
RelatedField.formfield | (self, **kwargs) |
Pass ``limit_choices_to`` to the field being constructed.
Only passes it if there is a type that supports related fields.
This is a similar strategy used to pass the ``queryset`` to the field
being constructed.
|
Pass ``limit_choices_to`` to the field being constructed. | def formfield(self, **kwargs):
"""
Pass ``limit_choices_to`` to the field being constructed.
Only passes it if there is a type that supports related fields.
This is a similar strategy used to pass the ``queryset`` to the field
being constructed.
"""
defaults = {}... | [
"def",
"formfield",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
".",
"remote_field",
",",
"'get_related_field'",
")",
":",
"# If this is a callable, do not invoke it here. Just pass",
"# it in the defaults... | [
420,
4
] | [
438,
62
] | python | en | ['en', 'error', 'th'] | False |
RelatedField.related_query_name | (self) |
Define the name that can be used to identify this related object in a
table-spanning query.
|
Define the name that can be used to identify this related object in a
table-spanning query.
| def related_query_name(self):
"""
Define the name that can be used to identify this related object in a
table-spanning query.
"""
return self.remote_field.related_query_name or self.remote_field.related_name or self.opts.model_name | [
"def",
"related_query_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"remote_field",
".",
"related_query_name",
"or",
"self",
".",
"remote_field",
".",
"related_name",
"or",
"self",
".",
"opts",
".",
"model_name"
] | [
440,
4
] | [
445,
109
] | python | en | ['en', 'error', 'th'] | False |
RelatedField.target_field | (self) |
When filtering against this relation, returns the field on the remote
model against which the filtering should happen.
|
When filtering against this relation, returns the field on the remote
model against which the filtering should happen.
| def target_field(self):
"""
When filtering against this relation, returns the field on the remote
model against which the filtering should happen.
"""
target_fields = self.get_path_info()[-1].target_fields
if len(target_fields) > 1:
raise exceptions.FieldError... | [
"def",
"target_field",
"(",
"self",
")",
":",
"target_fields",
"=",
"self",
".",
"get_path_info",
"(",
")",
"[",
"-",
"1",
"]",
".",
"target_fields",
"if",
"len",
"(",
"target_fields",
")",
">",
"1",
":",
"raise",
"exceptions",
".",
"FieldError",
"(",
... | [
448,
4
] | [
457,
31
] | python | en | ['en', 'error', 'th'] | False |
ForeignObject.get_extra_descriptor_filter | (self, instance) |
Return an extra filter condition for related object fetching when
user does 'instance.fieldname', that is the extra filter is used in
the descriptor of the field.
The filter should be either a dict usable in .filter(**kwargs) call or
a Q-object. The condition will be ANDed toge... |
Return an extra filter condition for related object fetching when
user does 'instance.fieldname', that is the extra filter is used in
the descriptor of the field. | def get_extra_descriptor_filter(self, instance):
"""
Return an extra filter condition for related object fetching when
user does 'instance.fieldname', that is the extra filter is used in
the descriptor of the field.
The filter should be either a dict usable in .filter(**kwargs) ... | [
"def",
"get_extra_descriptor_filter",
"(",
"self",
",",
"instance",
")",
":",
"return",
"{",
"}"
] | [
689,
4
] | [
702,
17
] | python | en | ['en', 'error', 'th'] | False |
ForeignObject.get_extra_restriction | (self, where_class, alias, related_alias) |
Return a pair condition used for joining and subquery pushdown. The
condition is something that responds to as_sql(compiler, connection)
method.
Note that currently referring both the 'alias' and 'related_alias'
will not work in some conditions, like subquery pushdown.
... |
Return a pair condition used for joining and subquery pushdown. The
condition is something that responds to as_sql(compiler, connection)
method. | def get_extra_restriction(self, where_class, alias, related_alias):
"""
Return a pair condition used for joining and subquery pushdown. The
condition is something that responds to as_sql(compiler, connection)
method.
Note that currently referring both the 'alias' and 'related_al... | [
"def",
"get_extra_restriction",
"(",
"self",
",",
"where_class",
",",
"alias",
",",
"related_alias",
")",
":",
"return",
"None"
] | [
704,
4
] | [
716,
19
] | python | en | ['en', 'error', 'th'] | False |
ForeignObject.get_path_info | (self) |
Get path from this field to the related model.
|
Get path from this field to the related model.
| def get_path_info(self):
"""
Get path from this field to the related model.
"""
opts = self.remote_field.model._meta
from_opts = self.model._meta
return [PathInfo(from_opts, opts, self.foreign_related_fields, self, False, True)] | [
"def",
"get_path_info",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"remote_field",
".",
"model",
".",
"_meta",
"from_opts",
"=",
"self",
".",
"model",
".",
"_meta",
"return",
"[",
"PathInfo",
"(",
"from_opts",
",",
"opts",
",",
"self",
".",
"fore... | [
718,
4
] | [
724,
90
] | python | en | ['en', 'error', 'th'] | False |
ForeignObject.get_reverse_path_info | (self) |
Get path from the related model to this field's model.
|
Get path from the related model to this field's model.
| def get_reverse_path_info(self):
"""
Get path from the related model to this field's model.
"""
opts = self.model._meta
from_opts = self.remote_field.model._meta
pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.remote_field, not self.unique, False)]
return ... | [
"def",
"get_reverse_path_info",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"from_opts",
"=",
"self",
".",
"remote_field",
".",
"model",
".",
"_meta",
"pathinfos",
"=",
"[",
"PathInfo",
"(",
"from_opts",
",",
"opts",
",",
"(",... | [
726,
4
] | [
733,
24
] | python | en | ['en', 'error', 'th'] | False |
ForeignKey.get_reverse_path_info | (self) |
Get path from the related model to this field's model.
|
Get path from the related model to this field's model.
| def get_reverse_path_info(self):
"""
Get path from the related model to this field's model.
"""
opts = self.model._meta
from_opts = self.remote_field.model._meta
pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.remote_field, not self.unique, False)]
return ... | [
"def",
"get_reverse_path_info",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"from_opts",
"=",
"self",
".",
"remote_field",
".",
"model",
".",
"_meta",
"pathinfos",
"=",
"[",
"PathInfo",
"(",
"from_opts",
",",
"opts",
",",
"(",... | [
910,
4
] | [
917,
24
] | python | en | ['en', 'error', 'th'] | False |
ForeignKey.get_default | (self) | Here we check if the default value is an object and return the to_field if so. | Here we check if the default value is an object and return the to_field if so. | def get_default(self):
"Here we check if the default value is an object and return the to_field if so."
field_default = super(ForeignKey, self).get_default()
if isinstance(field_default, self.remote_field.model):
return getattr(field_default, self.target_field.attname)
return... | [
"def",
"get_default",
"(",
"self",
")",
":",
"field_default",
"=",
"super",
"(",
"ForeignKey",
",",
"self",
")",
".",
"get_default",
"(",
")",
"if",
"isinstance",
"(",
"field_default",
",",
"self",
".",
"remote_field",
".",
"model",
")",
":",
"return",
"... | [
949,
4
] | [
954,
28
] | python | en | ['en', 'en', 'en'] | True |
ManyToManyField._get_path_info | (self, direct=False) |
Called by both direct and indirect m2m traversal.
|
Called by both direct and indirect m2m traversal.
| def _get_path_info(self, direct=False):
"""
Called by both direct and indirect m2m traversal.
"""
pathinfos = []
int_model = self.remote_field.through
linkfield1 = int_model._meta.get_field(self.m2m_field_name())
linkfield2 = int_model._meta.get_field(self.m2m_rev... | [
"def",
"_get_path_info",
"(",
"self",
",",
"direct",
"=",
"False",
")",
":",
"pathinfos",
"=",
"[",
"]",
"int_model",
"=",
"self",
".",
"remote_field",
".",
"through",
"linkfield1",
"=",
"int_model",
".",
"_meta",
".",
"get_field",
"(",
"self",
".",
"m2m... | [
1519,
4
] | [
1549,
24
] | python | en | ['en', 'error', 'th'] | False |
ManyToManyField._get_m2m_db_table | (self, opts) |
Function that can be curried to provide the m2m table name for this
relation.
|
Function that can be curried to provide the m2m table name for this
relation.
| def _get_m2m_db_table(self, opts):
"""
Function that can be curried to provide the m2m table name for this
relation.
"""
if self.remote_field.through is not None:
return self.remote_field.through._meta.db_table
elif self.db_table:
return self.db_ta... | [
"def",
"_get_m2m_db_table",
"(",
"self",
",",
"opts",
")",
":",
"if",
"self",
".",
"remote_field",
".",
"through",
"is",
"not",
"None",
":",
"return",
"self",
".",
"remote_field",
".",
"through",
".",
"_meta",
".",
"db_table",
"elif",
"self",
".",
"db_ta... | [
1557,
4
] | [
1568,
88
] | python | en | ['en', 'error', 'th'] | False |
ManyToManyField._get_m2m_attr | (self, related, attr) |
Function that can be curried to provide the source accessor or DB
column name for the m2m table.
|
Function that can be curried to provide the source accessor or DB
column name for the m2m table.
| def _get_m2m_attr(self, related, attr):
"""
Function that can be curried to provide the source accessor or DB
column name for the m2m table.
"""
cache_attr = '_m2m_%s_cache' % attr
if hasattr(self, cache_attr):
return getattr(self, cache_attr)
if self.... | [
"def",
"_get_m2m_attr",
"(",
"self",
",",
"related",
",",
"attr",
")",
":",
"cache_attr",
"=",
"'_m2m_%s_cache'",
"%",
"attr",
"if",
"hasattr",
"(",
"self",
",",
"cache_attr",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"cache_attr",
")",
"if",
"sel... | [
1570,
4
] | [
1586,
48
] | python | en | ['en', 'error', 'th'] | False |
ManyToManyField._get_m2m_reverse_attr | (self, related, attr) |
Function that can be curried to provide the related accessor or DB
column name for the m2m table.
|
Function that can be curried to provide the related accessor or DB
column name for the m2m table.
| def _get_m2m_reverse_attr(self, related, attr):
"""
Function that can be curried to provide the related accessor or DB
column name for the m2m table.
"""
cache_attr = '_m2m_reverse_%s_cache' % attr
if hasattr(self, cache_attr):
return getattr(self, cache_attr)... | [
"def",
"_get_m2m_reverse_attr",
"(",
"self",
",",
"related",
",",
"attr",
")",
":",
"cache_attr",
"=",
"'_m2m_reverse_%s_cache'",
"%",
"attr",
"if",
"hasattr",
"(",
"self",
",",
"cache_attr",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"cache_attr",
")"... | [
1588,
4
] | [
1616,
40
] | python | en | ['en', 'error', 'th'] | False |
ManyToManyField.value_from_object | (self, obj) |
Return the value of this field in the given model instance.
|
Return the value of this field in the given model instance.
| def value_from_object(self, obj):
"""
Return the value of this field in the given model instance.
"""
if obj.pk is None:
return self.related_model.objects.none()
return getattr(obj, self.attname).all() | [
"def",
"value_from_object",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"pk",
"is",
"None",
":",
"return",
"self",
".",
"related_model",
".",
"objects",
".",
"none",
"(",
")",
"return",
"getattr",
"(",
"obj",
",",
"self",
".",
"attname",
")"... | [
1676,
4
] | [
1682,
47
] | python | en | ['en', 'error', 'th'] | False |
get_sticky_actions | (config) | Returns list of sticky actions for the currently used action set. | Returns list of sticky actions for the currently used action set. | def get_sticky_actions(config):
"""Returns list of sticky actions for the currently used action set."""
sticky_actions = []
for a in get_action_set(config):
if a._sticky:
sticky_actions.append(a)
return sticky_actions | [
"def",
"get_sticky_actions",
"(",
"config",
")",
":",
"sticky_actions",
"=",
"[",
"]",
"for",
"a",
"in",
"get_action_set",
"(",
"config",
")",
":",
"if",
"a",
".",
"_sticky",
":",
"sticky_actions",
".",
"append",
"(",
"a",
")",
"return",
"sticky_actions"
] | [
203,
0
] | [
209,
23
] | python | en | ['en', 'en', 'en'] | True |
TaskWorker.resolve_callable | (cls, task) |
Transform a dotted notation task into an imported, callable function, e.g.,
awx.main.tasks.delete_inventory
awx.main.tasks.RunProjectUpdate
|
Transform a dotted notation task into an imported, callable function, e.g., | def resolve_callable(cls, task):
"""
Transform a dotted notation task into an imported, callable function, e.g.,
awx.main.tasks.delete_inventory
awx.main.tasks.RunProjectUpdate
"""
if not task.startswith('awx.'):
raise ValueError('{} is not a valid awx task'.... | [
"def",
"resolve_callable",
"(",
"cls",
",",
"task",
")",
":",
"if",
"not",
"task",
".",
"startswith",
"(",
"'awx.'",
")",
":",
"raise",
"ValueError",
"(",
"'{} is not a valid awx task'",
".",
"format",
"(",
"task",
")",
")",
"module",
",",
"target",
"=",
... | [
28,
4
] | [
45,
20
] | python | en | ['en', 'error', 'th'] | False |
TaskWorker.run_callable | (self, body) |
Given some AMQP message, import the correct Python code and run it.
|
Given some AMQP message, import the correct Python code and run it.
| def run_callable(self, body):
"""
Given some AMQP message, import the correct Python code and run it.
"""
task = body['task']
uuid = body.get('uuid', '<unknown>')
args = body.get('args', [])
kwargs = body.get('kwargs', {})
if 'guid' in body:
Gu... | [
"def",
"run_callable",
"(",
"self",
",",
"body",
")",
":",
"task",
"=",
"body",
"[",
"'task'",
"]",
"uuid",
"=",
"body",
".",
"get",
"(",
"'uuid'",
",",
"'<unknown>'",
")",
"args",
"=",
"body",
".",
"get",
"(",
"'args'",
",",
"[",
"]",
")",
"kwar... | [
47,
4
] | [
64,
37
] | python | en | ['en', 'error', 'th'] | False |
TaskWorker.perform_work | (self, body) |
Import and run code for a task e.g.,
body = {
'args': [8],
'callbacks': [{
'args': [],
'kwargs': {}
'task': u'awx.main.tasks.handle_work_success'
}],
'errbacks': [{
'args': [],
... |
Import and run code for a task e.g., | def perform_work(self, body):
"""
Import and run code for a task e.g.,
body = {
'args': [8],
'callbacks': [{
'args': [],
'kwargs': {}
'task': u'awx.main.tasks.handle_work_success'
}],
'errbacks': [{
... | [
"def",
"perform_work",
"(",
"self",
",",
"body",
")",
":",
"settings",
".",
"__clean_on_fork__",
"(",
")",
"result",
"=",
"None",
"try",
":",
"result",
"=",
"self",
".",
"run_callable",
"(",
"body",
")",
"except",
"Exception",
"as",
"exc",
":",
"result",... | [
66,
4
] | [
124,
21
] | python | en | ['en', 'error', 'th'] | False |
slack_workspace_to_realm | (
domain_name: str,
realm_id: int,
user_list: List[ZerverFieldsT],
realm_subdomain: str,
slack_data_dir: str,
custom_emoji_list: ZerverFieldsT,
) |
Returns:
1. realm, converted realm data
2. slack_user_id_to_zulip_user_id, which is a dictionary to map from Slack user id to Zulip user id
3. slack_recipient_name_to_zulip_recipient_id, which is a dictionary to map from Slack recipient
name(channel names, mpim names, usernames, etc) to Zulip re... |
Returns:
1. realm, converted realm data
2. slack_user_id_to_zulip_user_id, which is a dictionary to map from Slack user id to Zulip user id
3. slack_recipient_name_to_zulip_recipient_id, which is a dictionary to map from Slack recipient
name(channel names, mpim names, usernames, etc) to Zulip re... | def slack_workspace_to_realm(
domain_name: str,
realm_id: int,
user_list: List[ZerverFieldsT],
realm_subdomain: str,
slack_data_dir: str,
custom_emoji_list: ZerverFieldsT,
) -> Tuple[
ZerverFieldsT,
SlackToZulipUserIDT,
SlackToZulipRecipientT,
AddedChannelsT,
AddedMPIMsT,
... | [
"def",
"slack_workspace_to_realm",
"(",
"domain_name",
":",
"str",
",",
"realm_id",
":",
"int",
",",
"user_list",
":",
"List",
"[",
"ZerverFieldsT",
"]",
",",
"realm_subdomain",
":",
"str",
",",
"slack_data_dir",
":",
"str",
",",
"custom_emoji_list",
":",
"Zer... | [
64,
0
] | [
134,
5
] | python | en | ['en', 'error', 'th'] | False |
users_to_zerver_userprofile | (
slack_data_dir: str, users: List[ZerverFieldsT], realm_id: int, timestamp: Any, domain_name: str
) |
Returns:
1. zerver_userprofile, which is a list of user profile
2. avatar_list, which is list to map avatars to Zulip avatard records.json
3. slack_user_id_to_zulip_user_id, which is a dictionary to map from Slack user ID to Zulip
user id
4. zerver_customprofilefield, which is a list of all ... |
Returns:
1. zerver_userprofile, which is a list of user profile
2. avatar_list, which is list to map avatars to Zulip avatard records.json
3. slack_user_id_to_zulip_user_id, which is a dictionary to map from Slack user ID to Zulip
user id
4. zerver_customprofilefield, which is a list of all ... | def users_to_zerver_userprofile(
slack_data_dir: str, users: List[ZerverFieldsT], realm_id: int, timestamp: Any, domain_name: str
) -> Tuple[
List[ZerverFieldsT],
List[ZerverFieldsT],
SlackToZulipUserIDT,
List[ZerverFieldsT],
List[ZerverFieldsT],
]:
"""
Returns:
1. zerver_userprofile... | [
"def",
"users_to_zerver_userprofile",
"(",
"slack_data_dir",
":",
"str",
",",
"users",
":",
"List",
"[",
"ZerverFieldsT",
"]",
",",
"realm_id",
":",
"int",
",",
"timestamp",
":",
"Any",
",",
"domain_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
... | [
161,
0
] | [
279,
5
] | python | en | ['en', 'error', 'th'] | False |
channels_to_zerver_stream | (
slack_data_dir: str,
realm_id: int,
realm: Dict[str, Any],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
zerver_userprofile: List[ZerverFieldsT],
) |
Returns:
1. realm, converted realm data
2. added_channels, which is a dictionary to map from channel name to channel id, Zulip stream_id
3. added_mpims, which is a dictionary to map from MPIM(multiparty IM) name to MPIM id, Zulip huddle_id
4. dm_members, which is a dictionary to map from DM id to t... |
Returns:
1. realm, converted realm data
2. added_channels, which is a dictionary to map from channel name to channel id, Zulip stream_id
3. added_mpims, which is a dictionary to map from MPIM(multiparty IM) name to MPIM id, Zulip huddle_id
4. dm_members, which is a dictionary to map from DM id to t... | def channels_to_zerver_stream(
slack_data_dir: str,
realm_id: int,
realm: Dict[str, Any],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
zerver_userprofile: List[ZerverFieldsT],
) -> Tuple[
Dict[str, List[ZerverFieldsT]], AddedChannelsT, AddedMPIMsT, DMMembersT, SlackToZulipRecipientT
]:
... | [
"def",
"channels_to_zerver_stream",
"(",
"slack_data_dir",
":",
"str",
",",
"realm_id",
":",
"int",
",",
"realm",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"slack_user_id_to_zulip_user_id",
":",
"SlackToZulipUserIDT",
",",
"zerver_userprofile",
":",
"List",
... | [
417,
0
] | [
585,
5
] | python | en | ['en', 'error', 'th'] | False |
process_long_term_idle_users | (
slack_data_dir: str,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
zerver_userprofile: List[ZerverFieldsT],
) | Algorithmically, we treat users who have sent at least 10 messages
or have sent a message within the last 60 days as active.
Everyone else is treated as long-term idle, which means they will
have a slightly slower first page load when coming back to
Zulip.
| Algorithmically, we treat users who have sent at least 10 messages
or have sent a message within the last 60 days as active.
Everyone else is treated as long-term idle, which means they will
have a slightly slower first page load when coming back to
Zulip.
| def process_long_term_idle_users(
slack_data_dir: str,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
zerver_userprofile: List[ZerverFieldsT],
) -> Set[int]:
"""Algorithmic... | [
"def",
"process_long_term_idle_users",
"(",
"slack_data_dir",
":",
"str",
",",
"users",
":",
"List",
"[",
"ZerverFieldsT",
"]",
",",
"slack_user_id_to_zulip_user_id",
":",
"SlackToZulipUserIDT",
",",
"added_channels",
":",
"AddedChannelsT",
",",
"added_mpims",
":",
"A... | [
604,
0
] | [
657,
25
] | python | en | ['en', 'en', 'en'] | True |
convert_slack_workspace_messages | (
slack_data_dir: str,
users: List[ZerverFieldsT],
realm_id: int,
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
realm: ZerverFi... |
Returns:
1. reactions, which is a list of the reactions
2. uploads, which is a list of uploads to be mapped in uploads records.json
3. attachment, which is a list of the attachments
|
Returns:
1. reactions, which is a list of the reactions
2. uploads, which is a list of uploads to be mapped in uploads records.json
3. attachment, which is a list of the attachments
| def convert_slack_workspace_messages(
slack_data_dir: str,
users: List[ZerverFieldsT],
realm_id: int,
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_memb... | [
"def",
"convert_slack_workspace_messages",
"(",
"slack_data_dir",
":",
"str",
",",
"users",
":",
"List",
"[",
"ZerverFieldsT",
"]",
",",
"realm_id",
":",
"int",
",",
"slack_user_id_to_zulip_user_id",
":",
"SlackToZulipUserIDT",
",",
"slack_recipient_name_to_zulip_recipien... | [
660,
0
] | [
750,
60
] | python | en | ['en', 'error', 'th'] | False |
get_messages_iterator | (
slack_data_dir: str,
added_channels: Dict[str, Any],
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
) | This function is an iterator that returns all the messages across
all Slack channels, in order by timestamp. It's important to
not read all the messages into memory at once, because for
large imports that can OOM kill. | This function is an iterator that returns all the messages across
all Slack channels, in order by timestamp. It's important to
not read all the messages into memory at once, because for
large imports that can OOM kill. | def get_messages_iterator(
slack_data_dir: str,
added_channels: Dict[str, Any],
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
) -> Iterator[ZerverFieldsT]:
"""This function is an iterator that returns all the messages across
all Slack channels, in order by timestamp. It's important to
n... | [
"def",
"get_messages_iterator",
"(",
"slack_data_dir",
":",
"str",
",",
"added_channels",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"added_mpims",
":",
"AddedMPIMsT",
",",
"dm_members",
":",
"DMMembersT",
",",
")",
"->",
"Iterator",
"[",
"ZerverFieldsT",
... | [
753,
0
] | [
799,
70
] | python | en | ['en', 'en', 'en'] | True |
channel_message_to_zerver_message | (
realm_id: int,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
all_messages: List[ZerverFieldsT],
zerver_realmemoji: List[ZerverFieldsT],
subscriber_map: Dict[int, Set[int]],
added_chan... |
Returns:
1. zerver_message, which is a list of the messages
2. zerver_usermessage, which is a list of the usermessages
3. zerver_attachment, which is a list of the attachments
4. uploads_list, which is a list of uploads to be mapped in uploads records.json
5. reaction_list, which is a list of a... |
Returns:
1. zerver_message, which is a list of the messages
2. zerver_usermessage, which is a list of the usermessages
3. zerver_attachment, which is a list of the attachments
4. uploads_list, which is a list of uploads to be mapped in uploads records.json
5. reaction_list, which is a list of a... | def channel_message_to_zerver_message(
realm_id: int,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
all_messages: List[ZerverFieldsT],
zerver_realmemoji: List[ZerverFieldsT],
subscriber_map... | [
"def",
"channel_message_to_zerver_message",
"(",
"realm_id",
":",
"int",
",",
"users",
":",
"List",
"[",
"ZerverFieldsT",
"]",
",",
"slack_user_id_to_zulip_user_id",
":",
"SlackToZulipUserIDT",
",",
"slack_recipient_name_to_zulip_recipient_id",
":",
"SlackToZulipRecipientT",
... | [
802,
0
] | [
971,
93
] | python | en | ['en', 'error', 'th'] | False |
Request.proxy_protocol | (self, line) | \
Detect, check and parse proxy protocol.
:raises: ForbiddenProxyRequest, InvalidProxyLine.
:return: True for proxy protocol line else False
| \
Detect, check and parse proxy protocol. | def proxy_protocol(self, line):
"""\
Detect, check and parse proxy protocol.
:raises: ForbiddenProxyRequest, InvalidProxyLine.
:return: True for proxy protocol line else False
"""
if not self.cfg.proxy_protocol:
return False
if self.req_number != 1:
... | [
"def",
"proxy_protocol",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"self",
".",
"cfg",
".",
"proxy_protocol",
":",
"return",
"False",
"if",
"self",
".",
"req_number",
"!=",
"1",
":",
"return",
"False",
"if",
"not",
"line",
".",
"startswith",
"("... | [
258,
4
] | [
277,
19
] | python | en | ['en', 'ja', 'hi'] | False |
register_serializer | (format, serializer_module, serializers=None) | Register a new serializer.
``serializer_module`` should be the fully qualified module name
for the serializer.
If ``serializers`` is provided, the registration will be added
to the provided dictionary.
If ``serializers`` is not provided, the registration will be made
directly into the global ... | Register a new serializer. | def register_serializer(format, serializer_module, serializers=None):
"""Register a new serializer.
``serializer_module`` should be the fully qualified module name
for the serializer.
If ``serializers`` is provided, the registration will be added
to the provided dictionary.
If ``serializers``... | [
"def",
"register_serializer",
"(",
"format",
",",
"serializer_module",
",",
"serializers",
"=",
"None",
")",
":",
"if",
"serializers",
"is",
"None",
"and",
"not",
"_serializers",
":",
"_load_serializers",
"(",
")",
"try",
":",
"module",
"=",
"importlib",
".",
... | [
53,
0
] | [
82,
36
] | python | en | ['en', 'en', 'en'] | True |
unregister_serializer | (format) | Unregister a given serializer. This is not a thread-safe operation. | Unregister a given serializer. This is not a thread-safe operation. | def unregister_serializer(format):
"Unregister a given serializer. This is not a thread-safe operation."
if not _serializers:
_load_serializers()
if format not in _serializers:
raise SerializerDoesNotExist(format)
del _serializers[format] | [
"def",
"unregister_serializer",
"(",
"format",
")",
":",
"if",
"not",
"_serializers",
":",
"_load_serializers",
"(",
")",
"if",
"format",
"not",
"in",
"_serializers",
":",
"raise",
"SerializerDoesNotExist",
"(",
"format",
")",
"del",
"_serializers",
"[",
"format... | [
85,
0
] | [
91,
28
] | python | en | ['en', 'en', 'en'] | True |
serialize | (format, queryset, **options) |
Serialize a queryset (or any iterator that returns database objects) using
a certain serializer.
|
Serialize a queryset (or any iterator that returns database objects) using
a certain serializer.
| def serialize(format, queryset, **options):
"""
Serialize a queryset (or any iterator that returns database objects) using
a certain serializer.
"""
s = get_serializer(format)()
s.serialize(queryset, **options)
return s.getvalue() | [
"def",
"serialize",
"(",
"format",
",",
"queryset",
",",
"*",
"*",
"options",
")",
":",
"s",
"=",
"get_serializer",
"(",
"format",
")",
"(",
")",
"s",
".",
"serialize",
"(",
"queryset",
",",
"*",
"*",
"options",
")",
"return",
"s",
".",
"getvalue",
... | [
122,
0
] | [
129,
23
] | python | en | ['en', 'error', 'th'] | False |
deserialize | (format, stream_or_string, **options) |
Deserialize a stream or a string. Returns an iterator that yields ``(obj,
m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* --
object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name :
list_of_related_objects}``.
|
Deserialize a stream or a string. Returns an iterator that yields ``(obj,
m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* --
object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name :
list_of_related_objects}``.
| def deserialize(format, stream_or_string, **options):
"""
Deserialize a stream or a string. Returns an iterator that yields ``(obj,
m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* --
object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name :
list_of_related_obje... | [
"def",
"deserialize",
"(",
"format",
",",
"stream_or_string",
",",
"*",
"*",
"options",
")",
":",
"d",
"=",
"get_deserializer",
"(",
"format",
")",
"return",
"d",
"(",
"stream_or_string",
",",
"*",
"*",
"options",
")"
] | [
132,
0
] | [
140,
41
] | python | en | ['en', 'error', 'th'] | False |
_load_serializers | () |
Register built-in and settings-defined serializers. This is done lazily so
that user code has a chance to (e.g.) set up custom settings without
needing to be careful of import order.
|
Register built-in and settings-defined serializers. This is done lazily so
that user code has a chance to (e.g.) set up custom settings without
needing to be careful of import order.
| def _load_serializers():
"""
Register built-in and settings-defined serializers. This is done lazily so
that user code has a chance to (e.g.) set up custom settings without
needing to be careful of import order.
"""
global _serializers
serializers = {}
for format in BUILTIN_SERIALIZERS:
... | [
"def",
"_load_serializers",
"(",
")",
":",
"global",
"_serializers",
"serializers",
"=",
"{",
"}",
"for",
"format",
"in",
"BUILTIN_SERIALIZERS",
":",
"register_serializer",
"(",
"format",
",",
"BUILTIN_SERIALIZERS",
"[",
"format",
"]",
",",
"serializers",
")",
"... | [
143,
0
] | [
156,
30
] | python | en | ['en', 'error', 'th'] | False |
sort_dependencies | (app_list) | Sort a list of (app_config, models) pairs into a single list of models.
The single list of models is sorted so that any model with a natural key
is serialized before a normal model, and any model with a natural key
dependency has it's dependencies serialized first.
| Sort a list of (app_config, models) pairs into a single list of models. | def sort_dependencies(app_list):
"""Sort a list of (app_config, models) pairs into a single list of models.
The single list of models is sorted so that any model with a natural key
is serialized before a normal model, and any model with a natural key
dependency has it's dependencies serialized first.
... | [
"def",
"sort_dependencies",
"(",
"app_list",
")",
":",
"# Process the list of models, and get the list of dependencies",
"model_dependencies",
"=",
"[",
"]",
"models",
"=",
"set",
"(",
")",
"for",
"app_config",
",",
"model_list",
"in",
"app_list",
":",
"if",
"model_li... | [
159,
0
] | [
238,
21
] | python | en | ['en', 'en', 'en'] | True |
_fixup_find_links | (find_links) | Ensure find-links option end-up being a list of strings. | Ensure find-links option end-up being a list of strings. | def _fixup_find_links(find_links):
"""Ensure find-links option end-up being a list of strings."""
if isinstance(find_links, str):
return find_links.split()
assert isinstance(find_links, (tuple, list))
return find_links | [
"def",
"_fixup_find_links",
"(",
"find_links",
")",
":",
"if",
"isinstance",
"(",
"find_links",
",",
"str",
")",
":",
"return",
"find_links",
".",
"split",
"(",
")",
"assert",
"isinstance",
"(",
"find_links",
",",
"(",
"tuple",
",",
"list",
")",
")",
"re... | [
13,
0
] | [
18,
21
] | python | en | ['en', 'en', 'en'] | True |
_legacy_fetch_build_egg | (dist, req) | Fetch an egg needed for building.
Legacy path using EasyInstall.
| Fetch an egg needed for building. | def _legacy_fetch_build_egg(dist, req):
"""Fetch an egg needed for building.
Legacy path using EasyInstall.
"""
tmp_dist = dist.__class__({'script_args': ['easy_install']})
opts = tmp_dist.get_option_dict('easy_install')
opts.clear()
opts.update(
(k, v)
for k, v in dist.get_... | [
"def",
"_legacy_fetch_build_egg",
"(",
"dist",
",",
"req",
")",
":",
"tmp_dist",
"=",
"dist",
".",
"__class__",
"(",
"{",
"'script_args'",
":",
"[",
"'easy_install'",
"]",
"}",
")",
"opts",
"=",
"tmp_dist",
".",
"get_option_dict",
"(",
"'easy_install'",
")",... | [
21,
0
] | [
50,
32
] | python | en | ['en', 'en', 'en'] | True |
fetch_build_egg | (dist, req) | Fetch an egg needed for building.
Use pip/wheel to fetch/build a wheel. | Fetch an egg needed for building. | def fetch_build_egg(dist, req):
"""Fetch an egg needed for building.
Use pip/wheel to fetch/build a wheel."""
# Check pip is available.
try:
pkg_resources.get_distribution('pip')
except pkg_resources.DistributionNotFound:
dist.announce(
'WARNING: The pip package is not a... | [
"def",
"fetch_build_egg",
"(",
"dist",
",",
"req",
")",
":",
"# Check pip is available.",
"try",
":",
"pkg_resources",
".",
"get_distribution",
"(",
"'pip'",
")",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
"dist",
".",
"announce",
"(",
"'WARNING:... | [
53,
0
] | [
135,
19
] | python | en | ['en', 'en', 'en'] | True |
strip_marker | (req) |
Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored.
|
Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored.
| def strip_marker(req):
"""
Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored.
"""
# create a copy to avoid mutating the input
req = pkg_resources.Requirement.parse(str(req))
req.marker ... | [
"def",
"strip_marker",
"(",
"req",
")",
":",
"# create a copy to avoid mutating the input",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"str",
"(",
"req",
")",
")",
"req",
".",
"marker",
"=",
"None",
"return",
"req"
] | [
138,
0
] | [
147,
14
] | python | en | ['en', 'error', 'th'] | False |
_get_instance_id | (from_dict, new_id, default='') | logic mostly duplicated with inventory_import command Command._get_instance_id
frozen in time here, for purposes of migrations
| logic mostly duplicated with inventory_import command Command._get_instance_id
frozen in time here, for purposes of migrations
| def _get_instance_id(from_dict, new_id, default=''):
"""logic mostly duplicated with inventory_import command Command._get_instance_id
frozen in time here, for purposes of migrations
"""
instance_id = default
for key in new_id.split('.'):
if not hasattr(from_dict, 'get'):
instanc... | [
"def",
"_get_instance_id",
"(",
"from_dict",
",",
"new_id",
",",
"default",
"=",
"''",
")",
":",
"instance_id",
"=",
"default",
"for",
"key",
"in",
"new_id",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"not",
"hasattr",
"(",
"from_dict",
",",
"'get'",
")... | [
10,
0
] | [
21,
34
] | python | en | ['en', 'en', 'en'] | True |
set_new_instance_id | (apps, source, new_id) | This methods adds an instance_id in cases where there was not one before | This methods adds an instance_id in cases where there was not one before | def set_new_instance_id(apps, source, new_id):
"""This methods adds an instance_id in cases where there was not one before"""
from django.conf import settings
id_from_settings = getattr(settings, '{}_INSTANCE_ID_VAR'.format(source.upper()))
if id_from_settings != new_id:
# User applied an insta... | [
"def",
"set_new_instance_id",
"(",
"apps",
",",
"source",
",",
"new_id",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"id_from_settings",
"=",
"getattr",
"(",
"settings",
",",
"'{}_INSTANCE_ID_VAR'",
".",
"format",
"(",
"source",
".",
"upper"... | [
42,
0
] | [
62,
106
] | python | en | ['en', 'en', 'en'] | True |
JMeterFunction.to_python | (self, arguments) | arguments -> (expression, stmts) | arguments -> (expression, stmts) | def to_python(self, arguments):
"""arguments -> (expression, stmts)"""
args = dict(zip(self.arg_names, arguments))
return self._compile(args) | [
"def",
"to_python",
"(",
"self",
",",
"arguments",
")",
":",
"args",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"arg_names",
",",
"arguments",
")",
")",
"return",
"self",
".",
"_compile",
"(",
"args",
")"
] | [
30,
4
] | [
33,
34
] | python | en | ['en', 'da', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.