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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
now | (parser, token) |
Display the date, formatted according to the given string.
Use the same format as PHP's ``date()`` function; see https://php.net/date
for all the possible values.
Sample usage::
It is {% now "jS F Y H:i" %}
|
Display the date, formatted according to the given string. | def now(parser, token):
"""
Display the date, formatted according to the given string.
Use the same format as PHP's ``date()`` function; see https://php.net/date
for all the possible values.
Sample usage::
It is {% now "jS F Y H:i" %}
"""
bits = token.split_contents()
asvar = ... | [
"def",
"now",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"asvar",
"=",
"None",
"if",
"len",
"(",
"bits",
")",
"==",
"4",
"and",
"bits",
"[",
"-",
"2",
"]",
"==",
"'as'",
":",
"asvar",
"=",
"bit... | [
1143,
0
] | [
1162,
40
] | python | en | ['en', 'error', 'th'] | False |
regroup | (parser, token) |
Regroup a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that
``musicians`` is a list of ``Musician`` objects that have ``name`` and
``instrument`` attributes, and you'd like to display a list that
looks like:
* Guitar:
... |
Regroup a list of alike objects by a common attribute. | def regroup(parser, token):
"""
Regroup a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that
``musicians`` is a list of ``Musician`` objects that have ``name`` and
``instrument`` attributes, and you'd like to display a list that
look... | [
"def",
"regroup",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"6",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'regroup' tag takes five arguments\"",
")",
"target",
"=",
... | [
1166,
0
] | [
1231,
52
] | python | en | ['en', 'error', 'th'] | False |
resetcycle | (parser, token) |
Reset a cycle tag.
If an argument is given, reset the last rendered cycle tag whose name
matches the argument, else reset the last rendered cycle tag (named or
unnamed).
|
Reset a cycle tag. | def resetcycle(parser, token):
"""
Reset a cycle tag.
If an argument is given, reset the last rendered cycle tag whose name
matches the argument, else reset the last rendered cycle tag (named or
unnamed).
"""
args = token.split_contents()
if len(args) > 2:
raise TemplateSyntaxE... | [
"def",
"resetcycle",
"(",
"parser",
",",
"token",
")",
":",
"args",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"%r tag accepts at most one argument.\"",
"%",
"args",
"["... | [
1235,
0
] | [
1257,
59
] | python | en | ['en', 'error', 'th'] | False |
spaceless | (parser, token) |
Remove whitespace between HTML tags, including tab and newline characters.
Example usage::
{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
This example returns this HTML::
<p><a href="foo/">Foo</a></p>
Only space be... |
Remove whitespace between HTML tags, including tab and newline characters. | def spaceless(parser, token):
"""
Remove whitespace between HTML tags, including tab and newline characters.
Example usage::
{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
This example returns this HTML::
<p><a href=... | [
"def",
"spaceless",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endspaceless'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"SpacelessNode",
"(",
"nodelist",
")"
] | [
1261,
0
] | [
1288,
34
] | python | en | ['en', 'error', 'th'] | False |
templatetag | (parser, token) |
Output one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
================== =======
Arg... |
Output one of the bits used to compose template tags. | def templatetag(parser, token):
"""
Output one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
... | [
"def",
"templatetag",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
... | [
1292,
0
] | [
1323,
31
] | python | en | ['en', 'error', 'th'] | False |
url | (parser, token) | r"""
Return an absolute URL matching the given view with its parameters.
This is a way to define links that aren't tied to a particular URL
configuration::
{% url "url_name" arg1 arg2 %}
or
{% url "url_name" name1=value1 name2=value2 %}
The first argument is a URL pattern na... | r"""
Return an absolute URL matching the given view with its parameters. | def url(parser, token):
r"""
Return an absolute URL matching the given view with its parameters.
This is a way to define links that aren't tied to a particular URL
configuration::
{% url "url_name" arg1 arg2 %}
or
{% url "url_name" name1=value1 name2=value2 %}
The first ... | [
"def",
"url",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes at least one argument, a URL pattern name.\"",
"%",
"bi... | [
1327,
0
] | [
1390,
49
] | python | cy | ['en', 'cy', 'hi'] | False |
verbatim | (parser, token) |
Stop the template engine from rendering the contents of this block tag.
Usage::
{% verbatim %}
{% don't process this %}
{% endverbatim %}
You can also designate a specific closing tag block (allowing the
unrendered use of ``{% endverbatim %}``)::
{% verbatim mybl... |
Stop the template engine from rendering the contents of this block tag. | def verbatim(parser, token):
"""
Stop the template engine from rendering the contents of this block tag.
Usage::
{% verbatim %}
{% don't process this %}
{% endverbatim %}
You can also designate a specific closing tag block (allowing the
unrendered use of ``{% endverbat... | [
"def",
"verbatim",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endverbatim'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"VerbatimNode",
"(",
"nodelist",
".",
"render",
"(",
"Co... | [
1394,
0
] | [
1413,
51
] | python | en | ['en', 'error', 'th'] | False |
widthratio | (parser, token) |
For creating bar charts and such. Calculate the ratio of a given value to a
maximum value, and then apply that ratio to a constant.
For example::
<img src="bar.png" alt="Bar"
height="10" width="{% widthratio this_value max_value max_width %}">
If ``this_value`` is 175, ``max_val... |
For creating bar charts and such. Calculate the ratio of a given value to a
maximum value, and then apply that ratio to a constant. | def widthratio(parser, token):
"""
For creating bar charts and such. Calculate the ratio of a given value to a
maximum value, and then apply that ratio to a constant.
For example::
<img src="bar.png" alt="Bar"
height="10" width="{% widthratio this_value max_value max_width %}">
... | [
"def",
"widthratio",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"4",
":",
"tag",
",",
"this_value_expr",
",",
"max_value_expr",
",",
"max_width",
"=",
"bits",
"asva... | [
1417,
0
] | [
1451,
38
] | python | en | ['en', 'error', 'th'] | False |
do_with | (parser, token) |
Add one or more values to the context (inside of this block) for caching
and easy access.
For example::
{% with total=person.some_sql_method %}
{{ total }} object{{ total|pluralize }}
{% endwith %}
Multiple values can be added to the context::
{% with foo=1 bar=2... |
Add one or more values to the context (inside of this block) for caching
and easy access. | def do_with(parser, token):
"""
Add one or more values to the context (inside of this block) for caching
and easy access.
For example::
{% with total=person.some_sql_method %}
{{ total }} object{{ total|pluralize }}
{% endwith %}
Multiple values can be added to the con... | [
"def",
"do_with",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"remaining_bits",
"=",
"bits",
"[",
"1",
":",
"]",
"extra_context",
"=",
"token_kwargs",
"(",
"remaining_bits",
",",
"parser",
",",
"support_leg... | [
1455,
0
] | [
1486,
70
] | python | en | ['en', 'error', 'th'] | False |
CycleNode.reset | (self, context) |
Reset the cycle iteration back to the beginning.
|
Reset the cycle iteration back to the beginning.
| def reset(self, context):
"""
Reset the cycle iteration back to the beginning.
"""
context.render_context[self] = itertools_cycle(self.cyclevars) | [
"def",
"reset",
"(",
"self",
",",
"context",
")",
":",
"context",
".",
"render_context",
"[",
"self",
"]",
"=",
"itertools_cycle",
"(",
"self",
".",
"cyclevars",
")"
] | [
89,
4
] | [
93,
70
] | python | en | ['en', 'error', 'th'] | False |
Agent.__init__ | (self,
actions,
height=80,
width=80,
channels=1,
discount=0.95,
loss="huber",
env="Breakout-v0",
model_dir=None) | Initializes the parameters of the model.
Args:
height: Height of the image
width: Width of the image
channels: Number of channels, history of past frame
discount: Discount_Factor for Q Learning update
| Initializes the parameters of the model. | def __init__(self,
actions,
height=80,
width=80,
channels=1,
discount=0.95,
loss="huber",
env="Breakout-v0",
model_dir=None):
""" Initializes the parameters of the model.
Args:
... | [
"def",
"__init__",
"(",
"self",
",",
"actions",
",",
"height",
"=",
"80",
",",
"width",
"=",
"80",
",",
"channels",
"=",
"1",
",",
"discount",
"=",
"0.95",
",",
"loss",
"=",
"\"huber\"",
",",
"env",
"=",
"\"Breakout-v0\"",
",",
"model_dir",
"=",
"Non... | [
47,
2
] | [
81,
28
] | python | en | ['en', 'en', 'en'] | True |
Agent.create_model | (
self,
lr,
type="vanilla",
rescale_value=255.0,
) | Builds the DQN Agent architecture.
Source:https://cs.corp.google.com/piper///depot/google3/third_party/py/
dopamine/agents/dqn/dqn_agent.py?q=DQN&dr=CSs&l=15
This initializes the model as per the specifications mentioned in the
DQN paper by Deepmind. This is a sequential model impleme... | Builds the DQN Agent architecture. | def create_model(
self,
lr,
type="vanilla",
rescale_value=255.0,
):
""" Builds the DQN Agent architecture.
Source:https://cs.corp.google.com/piper///depot/google3/third_party/py/
dopamine/agents/dqn/dqn_agent.py?q=DQN&dr=CSs&l=15
This initializes the model as per ... | [
"def",
"create_model",
"(",
"self",
",",
"lr",
",",
"type",
"=",
"\"vanilla\"",
",",
"rescale_value",
"=",
"255.0",
",",
")",
":",
"#with tf.device('/gpu:0'):",
"self",
".",
"image_frames",
"=",
"Input",
"(",
"shape",
"=",
"(",
"self",
".",
"height",
",",
... | [
83,
2
] | [
152,
21
] | python | en | ['en', 'en', 'en'] | True |
Agent.batch_train | (self,
curr_state,
next_state,
immediate_reward,
action,
done,
target,
type="Double") | Computes the TD Error for a given batch of tuples.
Here, we randomly sample episodes from the Experience buffer and use
this to train our model. This method computes this for a batch and
trains the model.
Args:
curr_state(array): Numpy array representing a... | Computes the TD Error for a given batch of tuples. | def batch_train(self,
curr_state,
next_state,
immediate_reward,
action,
done,
target,
type="Double"):
""" Computes the TD Error for a given batch of tuples.
Here, we randomly sa... | [
"def",
"batch_train",
"(",
"self",
",",
"curr_state",
",",
"next_state",
",",
"immediate_reward",
",",
"action",
",",
"done",
",",
"target",
",",
"type",
"=",
"\"Double\"",
")",
":",
"if",
"type",
"==",
"\"Double\"",
":",
"forward_action",
"=",
"np",
".",
... | [
154,
2
] | [
209,
23
] | python | en | ['en', 'en', 'en'] | True |
Agent.predict_action | (self, state) | Predict the action for a given state.
Args:
state(float): Numpy array
Return:
action(int): Discrete action to sample
| Predict the action for a given state. | def predict_action(self, state):
""" Predict the action for a given state.
Args:
state(float): Numpy array
Return:
action(int): Discrete action to sample
"""
#state = downsample_state(convert_greyscale(state))
#state = np.expand_dims(state, axis=0)
if np.ndim(state) == 3:
... | [
"def",
"predict_action",
"(",
"self",
",",
"state",
")",
":",
"#state = downsample_state(convert_greyscale(state))",
"#state = np.expand_dims(state, axis=0)",
"if",
"np",
".",
"ndim",
"(",
"state",
")",
"==",
"3",
":",
"state",
"=",
"np",
".",
"expand_dims",
"(",
... | [
211,
2
] | [
224,
47
] | python | en | ['en', 'en', 'en'] | True |
Agent.play | (self, env, directory, mode) | Returns the total reward for an episode of the game. | Returns the total reward for an episode of the game. | def play(self, env, directory, mode):
""" Returns the total reward for an episode of the game."""
steps = []
state = env.reset()
done = False
tot_reward = 0
actions = [0] * self.actions
while not done:
if mode != "Train":
s = env.render("rgb_array")
steps.append(s)
... | [
"def",
"play",
"(",
"self",
",",
"env",
",",
"directory",
",",
"mode",
")",
":",
"steps",
"=",
"[",
"]",
"state",
"=",
"env",
".",
"reset",
"(",
")",
"done",
"=",
"False",
"tot_reward",
"=",
"0",
"actions",
"=",
"[",
"0",
"]",
"*",
"self",
".",... | [
226,
2
] | [
250,
21
] | python | en | ['en', 'en', 'en'] | True |
WsgiToAsgi.__call__ | (self, scope, receive, send) |
ASGI application instantiation point.
We return a new WsgiToAsgiInstance here with the WSGI app
and the scope, ready to respond when it is __call__ed.
|
ASGI application instantiation point.
We return a new WsgiToAsgiInstance here with the WSGI app
and the scope, ready to respond when it is __call__ed.
| async def __call__(self, scope, receive, send):
"""
ASGI application instantiation point.
We return a new WsgiToAsgiInstance here with the WSGI app
and the scope, ready to respond when it is __call__ed.
"""
await WsgiToAsgiInstance(self.wsgi_application)(scope, receive, s... | [
"async",
"def",
"__call__",
"(",
"self",
",",
"scope",
",",
"receive",
",",
"send",
")",
":",
"await",
"WsgiToAsgiInstance",
"(",
"self",
".",
"wsgi_application",
")",
"(",
"scope",
",",
"receive",
",",
"send",
")"
] | [
14,
4
] | [
20,
77
] | python | en | ['en', 'error', 'th'] | False |
WsgiToAsgiInstance.build_environ | (self, scope, body) |
Builds a scope and request body into a WSGI environ object.
|
Builds a scope and request body into a WSGI environ object.
| def build_environ(self, scope, body):
"""
Builds a scope and request body into a WSGI environ object.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
"PATH_INFO": scope["path... | [
"def",
"build_environ",
"(",
"self",
",",
"scope",
",",
"body",
")",
":",
"environ",
"=",
"{",
"\"REQUEST_METHOD\"",
":",
"scope",
"[",
"\"method\"",
"]",
",",
"\"SCRIPT_NAME\"",
":",
"scope",
".",
"get",
"(",
"\"root_path\"",
",",
"\"\"",
")",
".",
"enc... | [
52,
4
] | [
95,
22
] | python | en | ['en', 'error', 'th'] | False |
WsgiToAsgiInstance.start_response | (self, status, response_headers, exc_info=None) |
WSGI start_response callable.
|
WSGI start_response callable.
| def start_response(self, status, response_headers, exc_info=None):
"""
WSGI start_response callable.
"""
# Don't allow re-calling once response has begun
if self.response_started:
raise exc_info[1].with_traceback(exc_info[2])
# Don't allow re-calling without e... | [
"def",
"start_response",
"(",
"self",
",",
"status",
",",
"response_headers",
",",
"exc_info",
"=",
"None",
")",
":",
"# Don't allow re-calling once response has begun",
"if",
"self",
".",
"response_started",
":",
"raise",
"exc_info",
"[",
"1",
"]",
".",
"with_tra... | [
97,
4
] | [
127,
9
] | python | en | ['en', 'error', 'th'] | False |
WsgiToAsgiInstance.run_wsgi_app | (self, body) |
Called in a subthread to run the WSGI app. We encapsulate like
this so that the start_response callable is called in the same thread.
|
Called in a subthread to run the WSGI app. We encapsulate like
this so that the start_response callable is called in the same thread.
| def run_wsgi_app(self, body):
"""
Called in a subthread to run the WSGI app. We encapsulate like
this so that the start_response callable is called in the same thread.
"""
# Translate the scope and incoming request body into a WSGI environ
environ = self.build_environ(sel... | [
"def",
"run_wsgi_app",
"(",
"self",
",",
"body",
")",
":",
"# Translate the scope and incoming request body into a WSGI environ",
"environ",
"=",
"self",
".",
"build_environ",
"(",
"self",
".",
"scope",
",",
"body",
")",
"# Run the WSGI app",
"bytes_sent",
"=",
"0",
... | [
130,
4
] | [
161,
54
] | python | en | ['en', 'error', 'th'] | False |
warn_if_run_as_root | () | Output a warning for sudo users on Unix.
In a virtual environment, sudo pip still writes to virtualenv.
On Windows, users may run pip as Administrator without issues.
This warning only applies to Unix root users outside of virtualenv.
| Output a warning for sudo users on Unix. | def warn_if_run_as_root() -> None:
"""Output a warning for sudo users on Unix.
In a virtual environment, sudo pip still writes to virtualenv.
On Windows, users may run pip as Administrator without issues.
This warning only applies to Unix root users outside of virtualenv.
"""
if running_under_v... | [
"def",
"warn_if_run_as_root",
"(",
")",
"->",
"None",
":",
"if",
"running_under_virtualenv",
"(",
")",
":",
"return",
"if",
"not",
"hasattr",
"(",
"os",
",",
"\"getuid\"",
")",
":",
"return",
"# On Windows, there are no \"system managed\" Python packages. Installing as"... | [
156,
0
] | [
182,
5
] | python | en | ['en', 'en', 'en'] | True |
with_cleanup | (func: Any) | Decorator for common logic related to managing temporary
directories.
| Decorator for common logic related to managing temporary
directories.
| def with_cleanup(func: Any) -> Any:
"""Decorator for common logic related to managing temporary
directories.
"""
def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
for t in KEEPABLE_TEMPDIR_TYPES:
registry.set_delete(t, False)
def wrapper(
self... | [
"def",
"with_cleanup",
"(",
"func",
":",
"Any",
")",
"->",
"Any",
":",
"def",
"configure_tempdir_registry",
"(",
"registry",
":",
"TempDirectoryTypeRegistry",
")",
"->",
"None",
":",
"for",
"t",
"in",
"KEEPABLE_TEMPDIR_TYPES",
":",
"registry",
".",
"set_delete",... | [
185,
0
] | [
210,
18
] | python | en | ['en', 'en', 'en'] | True |
SessionCommandMixin._get_index_urls | (cls, options: Values) | Return a list of index urls from user-provided options. | Return a list of index urls from user-provided options. | def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
"""Return a list of index urls from user-provided options."""
index_urls = []
if not getattr(options, "no_index", False):
url = getattr(options, "index_url", None)
if url:
index_urls.append(... | [
"def",
"_get_index_urls",
"(",
"cls",
",",
"options",
":",
"Values",
")",
"->",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
":",
"index_urls",
"=",
"[",
"]",
"if",
"not",
"getattr",
"(",
"options",
",",
"\"no_index\"",
",",
"False",
")",
":",
"url... | [
57,
4
] | [
68,
33
] | python | en | ['en', 'en', 'en'] | True |
SessionCommandMixin.get_default_session | (self, options: Values) | Get a default-managed session. | Get a default-managed session. | def get_default_session(self, options: Values) -> PipSession:
"""Get a default-managed session."""
if self._session is None:
self._session = self.enter_context(self._build_session(options))
# there's no type annotation on requests.Session, so it's
# automatically Cont... | [
"def",
"get_default_session",
"(",
"self",
",",
"options",
":",
"Values",
")",
"->",
"PipSession",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"self",
".",
"_session",
"=",
"self",
".",
"enter_context",
"(",
"self",
".",
"_build_session",
"(",
... | [
70,
4
] | [
78,
28
] | python | en | ['en', 'da', 'en'] | True |
IndexGroupCommand.handle_pip_version_check | (self, options: Values) |
Do the pip version check if not disabled.
This overrides the default behavior of not doing the check.
|
Do the pip version check if not disabled. | def handle_pip_version_check(self, options: Values) -> None:
"""
Do the pip version check if not disabled.
This overrides the default behavior of not doing the check.
"""
# Make sure the index_group options are present.
assert hasattr(options, "no_index")
if opt... | [
"def",
"handle_pip_version_check",
"(",
"self",
",",
"options",
":",
"Values",
")",
"->",
"None",
":",
"# Make sure the index_group options are present.",
"assert",
"hasattr",
"(",
"options",
",",
"\"no_index\"",
")",
"if",
"options",
".",
"disable_pip_version_check",
... | [
129,
4
] | [
146,
52
] | python | en | ['en', 'error', 'th'] | False |
RequirementCommand.determine_resolver_variant | (options: Values) | Determines which resolver should be used, based on the given options. | Determines which resolver should be used, based on the given options. | def determine_resolver_variant(options: Values) -> str:
"""Determines which resolver should be used, based on the given options."""
if "legacy-resolver" in options.deprecated_features_enabled:
return "legacy"
return "2020-resolver" | [
"def",
"determine_resolver_variant",
"(",
"options",
":",
"Values",
")",
"->",
"str",
":",
"if",
"\"legacy-resolver\"",
"in",
"options",
".",
"deprecated_features_enabled",
":",
"return",
"\"legacy\"",
"return",
"\"2020-resolver\""
] | [
220,
4
] | [
225,
30
] | python | en | ['en', 'en', 'en'] | True |
RequirementCommand.make_requirement_preparer | (
cls,
temp_build_dir: TempDirectory,
options: Values,
req_tracker: RequirementTracker,
session: PipSession,
finder: PackageFinder,
use_user_site: bool,
download_dir: Optional[str] = None,
) |
Create a RequirementPreparer instance for the given parameters.
|
Create a RequirementPreparer instance for the given parameters.
| def make_requirement_preparer(
cls,
temp_build_dir: TempDirectory,
options: Values,
req_tracker: RequirementTracker,
session: PipSession,
finder: PackageFinder,
use_user_site: bool,
download_dir: Optional[str] = None,
) -> RequirementPreparer:
... | [
"def",
"make_requirement_preparer",
"(",
"cls",
",",
"temp_build_dir",
":",
"TempDirectory",
",",
"options",
":",
"Values",
",",
"req_tracker",
":",
"RequirementTracker",
",",
"session",
":",
"PipSession",
",",
"finder",
":",
"PackageFinder",
",",
"use_user_site",
... | [
228,
4
] | [
275,
9
] | python | en | ['en', 'error', 'th'] | False |
RequirementCommand.make_resolver | (
cls,
preparer: RequirementPreparer,
finder: PackageFinder,
options: Values,
wheel_cache: Optional[WheelCache] = None,
use_user_site: bool = False,
ignore_installed: bool = True,
ignore_requires_python: bool = False,
force_reinstall: bool = False,... |
Create a Resolver instance for the given parameters.
|
Create a Resolver instance for the given parameters.
| def make_resolver(
cls,
preparer: RequirementPreparer,
finder: PackageFinder,
options: Values,
wheel_cache: Optional[WheelCache] = None,
use_user_site: bool = False,
ignore_installed: bool = True,
ignore_requires_python: bool = False,
force_reinsta... | [
"def",
"make_resolver",
"(",
"cls",
",",
"preparer",
":",
"RequirementPreparer",
",",
"finder",
":",
"PackageFinder",
",",
"options",
":",
"Values",
",",
"wheel_cache",
":",
"Optional",
"[",
"WheelCache",
"]",
"=",
"None",
",",
"use_user_site",
":",
"bool",
... | [
278,
4
] | [
334,
9
] | python | en | ['en', 'error', 'th'] | False |
RequirementCommand.get_requirements | (
self,
args: List[str],
options: Values,
finder: PackageFinder,
session: PipSession,
) |
Parse command-line arguments into the corresponding requirements.
|
Parse command-line arguments into the corresponding requirements.
| def get_requirements(
self,
args: List[str],
options: Values,
finder: PackageFinder,
session: PipSession,
) -> List[InstallRequirement]:
"""
Parse command-line arguments into the corresponding requirements.
"""
requirements: List[InstallRequire... | [
"def",
"get_requirements",
"(",
"self",
",",
"args",
":",
"List",
"[",
"str",
"]",
",",
"options",
":",
"Values",
",",
"finder",
":",
"PackageFinder",
",",
"session",
":",
"PipSession",
",",
")",
"->",
"List",
"[",
"InstallRequirement",
"]",
":",
"requir... | [
336,
4
] | [
413,
27
] | python | en | ['en', 'error', 'th'] | False |
RequirementCommand.trace_basic_info | (finder: PackageFinder) |
Trace basic information about the provided objects.
|
Trace basic information about the provided objects.
| def trace_basic_info(finder: PackageFinder) -> None:
"""
Trace basic information about the provided objects.
"""
# Display where finder is looking for packages
search_scope = finder.search_scope
locations = search_scope.get_formatted_locations()
if locations:
... | [
"def",
"trace_basic_info",
"(",
"finder",
":",
"PackageFinder",
")",
"->",
"None",
":",
"# Display where finder is looking for packages",
"search_scope",
"=",
"finder",
".",
"search_scope",
"locations",
"=",
"search_scope",
".",
"get_formatted_locations",
"(",
")",
"if"... | [
416,
4
] | [
424,
34
] | python | en | ['en', 'error', 'th'] | False |
RequirementCommand._build_package_finder | (
self,
options: Values,
session: PipSession,
target_python: Optional[TargetPython] = None,
ignore_requires_python: Optional[bool] = None,
) |
Create a package finder appropriate to this requirement command.
:param ignore_requires_python: Whether to ignore incompatible
"Requires-Python" values in links. Defaults to False.
|
Create a package finder appropriate to this requirement command. | def _build_package_finder(
self,
options: Values,
session: PipSession,
target_python: Optional[TargetPython] = None,
ignore_requires_python: Optional[bool] = None,
) -> PackageFinder:
"""
Create a package finder appropriate to this requirement command.
... | [
"def",
"_build_package_finder",
"(",
"self",
",",
"options",
":",
"Values",
",",
"session",
":",
"PipSession",
",",
"target_python",
":",
"Optional",
"[",
"TargetPython",
"]",
"=",
"None",
",",
"ignore_requires_python",
":",
"Optional",
"[",
"bool",
"]",
"=",
... | [
426,
4
] | [
452,
9
] | python | en | ['en', 'error', 'th'] | False |
_ConfigName | (context) | Return the short config name. | Return the short config name. | def _ConfigName(context):
"""Return the short config name."""
return '{}-config'.format(context.env['deployment']) | [
"def",
"_ConfigName",
"(",
"context",
")",
":",
"return",
"'{}-config'",
".",
"format",
"(",
"context",
".",
"env",
"[",
"'deployment'",
"]",
")"
] | [
63,
0
] | [
65,
54
] | python | en | ['en', 'en', 'en'] | True |
_ConfigUrl | (context) | Returns the full URL to the config, including hostname. | Returns the full URL to the config, including hostname. | def _ConfigUrl(context):
"""Returns the full URL to the config, including hostname."""
return '{endpoint}/projects/{project}/configs/{config}'.format(
endpoint=RTC_ENDPOINT,
project=context.env['project'],
config=_ConfigName(context)) | [
"def",
"_ConfigUrl",
"(",
"context",
")",
":",
"return",
"'{endpoint}/projects/{project}/configs/{config}'",
".",
"format",
"(",
"endpoint",
"=",
"RTC_ENDPOINT",
",",
"project",
"=",
"context",
".",
"env",
"[",
"'project'",
"]",
",",
"config",
"=",
"_ConfigName",
... | [
68,
0
] | [
73,
34
] | python | en | ['en', 'en', 'en'] | True |
_WaiterName | (context) | Returns the short waiter name. | Returns the short waiter name. | def _WaiterName(context):
"""Returns the short waiter name."""
# This name is only used for the DM manifest entry. The actual waiter name
# within RuntimeConfig is static, as it is scoped to the config resource.
return '{}-software'.format(context.env['deployment']) | [
"def",
"_WaiterName",
"(",
"context",
")",
":",
"# This name is only used for the DM manifest entry. The actual waiter name",
"# within RuntimeConfig is static, as it is scoped to the config resource.",
"return",
"'{}-software'",
".",
"format",
"(",
"context",
".",
"env",
"[",
"'de... | [
76,
0
] | [
80,
56
] | python | en | ['en', 'no', 'en'] | True |
_Timeout | (context) | Returns the timeout property or a default value if unspecified. | Returns the timeout property or a default value if unspecified. | def _Timeout(context):
"""Returns the timeout property or a default value if unspecified."""
timeout = context.properties.get('timeout', DEFAULT_TIMEOUT)
try:
return str(int(timeout))
except ValueError:
raise PropertyError('Invalid timeout value: {}'.format(timeout)) | [
"def",
"_Timeout",
"(",
"context",
")",
":",
"timeout",
"=",
"context",
".",
"properties",
".",
"get",
"(",
"'timeout'",
",",
"DEFAULT_TIMEOUT",
")",
"try",
":",
"return",
"str",
"(",
"int",
"(",
"timeout",
")",
")",
"except",
"ValueError",
":",
"raise",... | [
83,
0
] | [
89,
68
] | python | en | ['en', 'en', 'en'] | True |
_SuccessNumber | (context) | Returns the successNumber property or a default value if unspecified. | Returns the successNumber property or a default value if unspecified. | def _SuccessNumber(context):
"""Returns the successNumber property or a default value if unspecified."""
number = context.properties.get('successNumber', DEFAULT_SUCCESS_NUMBER)
try:
number = int(number)
if number < 1:
raise PropertyError('successNumber value must be greater than 0.')
return num... | [
"def",
"_SuccessNumber",
"(",
"context",
")",
":",
"number",
"=",
"context",
".",
"properties",
".",
"get",
"(",
"'successNumber'",
",",
"DEFAULT_SUCCESS_NUMBER",
")",
"try",
":",
"number",
"=",
"int",
"(",
"number",
")",
"if",
"number",
"<",
"1",
":",
"... | [
92,
0
] | [
101,
73
] | python | en | ['en', 'en', 'en'] | True |
_FailureNumber | (context) | Returns the failureNumber property or a default value if unspecified. | Returns the failureNumber property or a default value if unspecified. | def _FailureNumber(context):
"""Returns the failureNumber property or a default value if unspecified."""
number = context.properties.get('failureNumber', DEFAULT_FAILURE_NUMBER)
try:
number = int(number)
if number < 1:
raise PropertyError('failureNumber value must be greater than 0.')
return num... | [
"def",
"_FailureNumber",
"(",
"context",
")",
":",
"number",
"=",
"context",
".",
"properties",
".",
"get",
"(",
"'failureNumber'",
",",
"DEFAULT_FAILURE_NUMBER",
")",
"try",
":",
"number",
"=",
"int",
"(",
"number",
")",
"if",
"number",
"<",
"1",
":",
"... | [
104,
0
] | [
113,
73
] | python | en | ['en', 'en', 'en'] | True |
_WaiterDependsOn | (context) | Returns the waiterDependsOn property or an empty list if unspecified. | Returns the waiterDependsOn property or an empty list if unspecified. | def _WaiterDependsOn(context):
"""Returns the waiterDependsOn property or an empty list if unspecified."""
depends_on = context.properties.get('waiterDependsOn', [])
if not isinstance(depends_on, list):
raise PropertyError('waiterDependsOn must be a list: {}'.format(depends_on))
for item in depends_on:
... | [
"def",
"_WaiterDependsOn",
"(",
"context",
")",
":",
"depends_on",
"=",
"context",
".",
"properties",
".",
"get",
"(",
"'waiterDependsOn'",
",",
"[",
"]",
")",
"if",
"not",
"isinstance",
"(",
"depends_on",
",",
"list",
")",
":",
"raise",
"PropertyError",
"... | [
116,
0
] | [
127,
19
] | python | en | ['en', 'en', 'en'] | True |
_RuntimeConfig | (context) | Constructs a RuntimeConfig resource. | Constructs a RuntimeConfig resource. | def _RuntimeConfig(context):
"""Constructs a RuntimeConfig resource."""
deployment_name = context.env['deployment']
return {
'name': _ConfigName(context),
'type': 'runtimeconfig.v1beta1.config',
'properties': {
'config': _ConfigName(context),
'description': ('Holds software ... | [
"def",
"_RuntimeConfig",
"(",
"context",
")",
":",
"deployment_name",
"=",
"context",
".",
"env",
"[",
"'deployment'",
"]",
"return",
"{",
"'name'",
":",
"_ConfigName",
"(",
"context",
")",
",",
"'type'",
":",
"'runtimeconfig.v1beta1.config'",
",",
"'properties'... | [
130,
0
] | [
142,
3
] | python | en | ['en', 'en', 'en'] | True |
_Waiter | (context) | Constructs a waiter resource. | Constructs a waiter resource. | def _Waiter(context):
"""Constructs a waiter resource."""
waiter_timeout = _Timeout(context)
return {
'name': _WaiterName(context),
'type': 'runtimeconfig.v1beta1.waiter',
'metadata': {
'dependsOn': _WaiterDependsOn(context),
},
'properties': {
'parent': '$(ref.{... | [
"def",
"_Waiter",
"(",
"context",
")",
":",
"waiter_timeout",
"=",
"_Timeout",
"(",
"context",
")",
"return",
"{",
"'name'",
":",
"_WaiterName",
"(",
"context",
")",
",",
"'type'",
":",
"'runtimeconfig.v1beta1.waiter'",
",",
"'metadata'",
":",
"{",
"'dependsOn... | [
145,
0
] | [
172,
3
] | python | en | ['en', 'en', 'en'] | True |
GenerateConfig | (context) | Entry function to generate the DM config. | Entry function to generate the DM config. | def GenerateConfig(context):
"""Entry function to generate the DM config."""
content = {
'resources': [
_RuntimeConfig(context),
_Waiter(context),
],
'outputs': [
{
'name': 'config-url',
'value': _ConfigUrl(context)
},
{... | [
"def",
"GenerateConfig",
"(",
"context",
")",
":",
"content",
"=",
"{",
"'resources'",
":",
"[",
"_RuntimeConfig",
"(",
"context",
")",
",",
"_Waiter",
"(",
"context",
")",
",",
"]",
",",
"'outputs'",
":",
"[",
"{",
"'name'",
":",
"'config-url'",
",",
... | [
175,
0
] | [
193,
32
] | python | en | ['en', 'en', 'en'] | True |
save_isolate_table | (tables: Dict[str, pandas.DataFrame], filename: Path) |
Saves the parsed table as an Excel spreadsheet.
Parameters
----------
tables: Dict[str,pandas.DataFrame]
A mapping of sheet names to dataframes.
filename: str, pathlib.Path
The output file.
Returns
-------
|
Saves the parsed table as an Excel spreadsheet.
Parameters
----------
tables: Dict[str,pandas.DataFrame]
A mapping of sheet names to dataframes.
filename: str, pathlib.Path
The output file. | def save_isolate_table(tables: Dict[str, pandas.DataFrame], filename: Path) -> Path:
"""
Saves the parsed table as an Excel spreadsheet.
Parameters
----------
tables: Dict[str,pandas.DataFrame]
A mapping of sheet names to dataframes.
filename: str, pathlib.Path
The output file.
Returns
-------
"""
writ... | [
"def",
"save_isolate_table",
"(",
"tables",
":",
"Dict",
"[",
"str",
",",
"pandas",
".",
"DataFrame",
"]",
",",
"filename",
":",
"Path",
")",
"->",
"Path",
":",
"writer",
"=",
"pandas",
".",
"ExcelWriter",
"(",
"str",
"(",
"filename",
")",
")",
"includ... | [
13,
0
] | [
40,
16
] | python | en | ['en', 'error', 'th'] | False |
color_table_cells | (filename: Path) | Colors in the cells of the comparison table to highlight differences between samples.
Parameters
----------
filename: Path
Path to the excel file. The sheet containing the comparison table should be named 'variant comparison'.
| Colors in the cells of the comparison table to highlight differences between samples.
Parameters
----------
filename: Path
Path to the excel file. The sheet containing the comparison table should be named 'variant comparison'.
| def color_table_cells(filename: Path):
""" Colors in the cells of the comparison table to highlight differences between samples.
Parameters
----------
filename: Path
Path to the excel file. The sheet containing the comparison table should be named 'variant comparison'.
"""
workbook = openpyxl.load_workbook(... | [
"def",
"color_table_cells",
"(",
"filename",
":",
"Path",
")",
":",
"workbook",
"=",
"openpyxl",
".",
"load_workbook",
"(",
"filename",
"=",
"str",
"(",
"filename",
")",
")",
"worksheet",
"=",
"workbook",
"[",
"'variant comparison'",
"]",
"# There is an issue wi... | [
53,
0
] | [
77,
57
] | python | en | ['en', 'en', 'en'] | True |
get_accessible_tenants | (os_conf, auth_url,
region_name=None, insecure=True, cacert=None,
timeout=5) |
:param os_conf: openstack config
:param auth_url: auth url
:param region_name: region name
:param insecure: insecure allowed for https
:param cacert:
:param timeout:
:return: tenants, client
list of tenants
scoped or unscoped client -- v3 client
|
:param os_conf: openstack config
:param auth_url: auth url
:param region_name: region name
:param insecure: insecure allowed for https
:param cacert:
:param timeout:
:return: tenants, client
list of tenants
scoped or unscoped client -- v3 client
| def get_accessible_tenants(os_conf, auth_url,
region_name=None, insecure=True, cacert=None,
timeout=5):
"""
:param os_conf: openstack config
:param auth_url: auth url
:param region_name: region name
:param insecure: insecure allowed for https
... | [
"def",
"get_accessible_tenants",
"(",
"os_conf",
",",
"auth_url",
",",
"region_name",
"=",
"None",
",",
"insecure",
"=",
"True",
",",
"cacert",
"=",
"None",
",",
"timeout",
"=",
"5",
")",
":",
"keystone_client",
"=",
"get_keystone_client",
"(",
"auth_url",
"... | [
68,
0
] | [
158,
27
] | python | en | ['en', 'error', 'th'] | False |
cleanup_users_tenants | (users=None, tenants=None, dry_run=False) |
For each remote user, if not in keystone, remove locally
For each remote tenant, if not in keystone, remove corresponding
roles and the local tenant object
|
For each remote user, if not in keystone, remove locally
For each remote tenant, if not in keystone, remove corresponding
roles and the local tenant object
| def cleanup_users_tenants(users=None, tenants=None, dry_run=False):
"""
For each remote user, if not in keystone, remove locally
For each remote tenant, if not in keystone, remove corresponding
roles and the local tenant object
"""
# logger.debug("Cleaning up non-existent non-local users and te... | [
"def",
"cleanup_users_tenants",
"(",
"users",
"=",
"None",
",",
"tenants",
"=",
"None",
",",
"dry_run",
"=",
"False",
")",
":",
"# logger.debug(\"Cleaning up non-existent non-local users and tenants\")",
"logger",
".",
"warning",
"(",
"\"Starting cleanup\"",
")",
"opens... | [
251,
0
] | [
356,
15
] | python | en | ['en', 'error', 'th'] | False |
DatabaseFeatures._mysql_storage_engine | (self) | Internal method used in Django tests. Don't rely on this from your code | Internal method used in Django tests. Don't rely on this from your code | def _mysql_storage_engine(self):
"Internal method used in Django tests. Don't rely on this from your code"
return self.connection.mysql_server_data['default_storage_engine'] | [
"def",
"_mysql_storage_engine",
"(",
"self",
")",
":",
"return",
"self",
".",
"connection",
".",
"mysql_server_data",
"[",
"'default_storage_engine'",
"]"
] | [
106,
4
] | [
108,
74
] | python | en | ['en', 'en', 'en'] | True |
DatabaseFeatures.allows_auto_pk_0 | (self) |
Autoincrement primary key can be set to 0 if it doesn't generate new
autoincrement values.
|
Autoincrement primary key can be set to 0 if it doesn't generate new
autoincrement values.
| def allows_auto_pk_0(self):
"""
Autoincrement primary key can be set to 0 if it doesn't generate new
autoincrement values.
"""
return 'NO_AUTO_VALUE_ON_ZERO' in self.connection.sql_mode | [
"def",
"allows_auto_pk_0",
"(",
"self",
")",
":",
"return",
"'NO_AUTO_VALUE_ON_ZERO'",
"in",
"self",
".",
"connection",
".",
"sql_mode"
] | [
111,
4
] | [
116,
66
] | python | en | ['en', 'error', 'th'] | False |
DatabaseFeatures.can_introspect_foreign_keys | (self) | Confirm support for introspected foreign keys | Confirm support for introspected foreign keys | def can_introspect_foreign_keys(self):
"Confirm support for introspected foreign keys"
return self._mysql_storage_engine != 'MyISAM' | [
"def",
"can_introspect_foreign_keys",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mysql_storage_engine",
"!=",
"'MyISAM'"
] | [
123,
4
] | [
125,
53
] | python | en | ['en', 'en', 'en'] | True |
DatabaseFeatures.supports_transactions | (self) |
All storage engines except MyISAM support transactions.
|
All storage engines except MyISAM support transactions.
| def supports_transactions(self):
"""
All storage engines except MyISAM support transactions.
"""
return self._mysql_storage_engine != 'MyISAM' | [
"def",
"supports_transactions",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mysql_storage_engine",
"!=",
"'MyISAM'"
] | [
202,
4
] | [
206,
53
] | python | en | ['en', 'error', 'th'] | False |
NTLMConnectionPool.__init__ | (self, user, pw, authurl, *args, **kwargs) |
authurl is a random URL on the server that is protected by NTLM.
user is the Windows user, probably in the DOMAIN\\username format.
pw is the password for the user.
|
authurl is a random URL on the server that is protected by NTLM.
user is the Windows user, probably in the DOMAIN\\username format.
pw is the password for the user.
| def __init__(self, user, pw, authurl, *args, **kwargs):
"""
authurl is a random URL on the server that is protected by NTLM.
user is the Windows user, probably in the DOMAIN\\username format.
pw is the password for the user.
"""
super(NTLMConnectionPool, self).__init__(*a... | [
"def",
"__init__",
"(",
"self",
",",
"user",
",",
"pw",
",",
"authurl",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"NTLMConnectionPool",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"s... | [
33,
4
] | [
45,
20
] | python | en | ['en', 'error', 'th'] | False |
DatabaseValidation.check_field_type | (self, field, field_type) |
MySQL has the following field length restriction:
No character (varchar) fields can have a length exceeding 255
characters if they have a unique index on them.
MySQL doesn't support a database index on some data types.
|
MySQL has the following field length restriction:
No character (varchar) fields can have a length exceeding 255
characters if they have a unique index on them.
MySQL doesn't support a database index on some data types.
| def check_field_type(self, field, field_type):
"""
MySQL has the following field length restriction:
No character (varchar) fields can have a length exceeding 255
characters if they have a unique index on them.
MySQL doesn't support a database index on some data types.
""... | [
"def",
"check_field_type",
"(",
"self",
",",
"field",
",",
"field_type",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"(",
"field_type",
".",
"startswith",
"(",
"'varchar'",
")",
"and",
"field",
".",
"unique",
"and",
"(",
"field",
".",
"max_length",
"is",
... | [
32,
4
] | [
68,
21
] | python | en | ['en', 'error', 'th'] | False |
features_and_labels | (row_data) | Splits features and labels from feature dictionary.
Args:
row_data: Dictionary of CSV column names and tensor values.
Returns:
Dictionary of feature tensors and label tensor.
| Splits features and labels from feature dictionary. | def features_and_labels(row_data):
"""Splits features and labels from feature dictionary.
Args:
row_data: Dictionary of CSV column names and tensor values.
Returns:
Dictionary of feature tensors and label tensor.
"""
label = row_data.pop(LABEL_COLUMN)
return row_data, label | [
"def",
"features_and_labels",
"(",
"row_data",
")",
":",
"label",
"=",
"row_data",
".",
"pop",
"(",
"LABEL_COLUMN",
")",
"return",
"row_data",
",",
"label"
] | [
37,
0
] | [
47,
26
] | python | en | ['en', 'en', 'en'] | True |
load_dataset | (pattern, batch_size=1, mode='eval') | Loads dataset using the tf.data API from CSV files.
Args:
pattern: str, file pattern to glob into list of files.
batch_size: int, the number of examples per batch.
mode: 'train' | 'eval' to determine if training or evaluating.
Returns:
`Dataset` object.
| Loads dataset using the tf.data API from CSV files. | def load_dataset(pattern, batch_size=1, mode='eval'):
"""Loads dataset using the tf.data API from CSV files.
Args:
pattern: str, file pattern to glob into list of files.
batch_size: int, the number of examples per batch.
mode: 'train' | 'eval' to determine if training or evaluating.
... | [
"def",
"load_dataset",
"(",
"pattern",
",",
"batch_size",
"=",
"1",
",",
"mode",
"=",
"'eval'",
")",
":",
"print",
"(",
"\"mode = {}\"",
".",
"format",
"(",
"mode",
")",
")",
"# Make a CSV dataset",
"dataset",
"=",
"tf",
".",
"data",
".",
"experimental",
... | [
50,
0
] | [
78,
18
] | python | en | ['en', 'en', 'en'] | True |
create_input_layers | () | Creates dictionary of input layers for each feature.
Returns:
Dictionary of `tf.Keras.layers.Input` layers for each feature.
| Creates dictionary of input layers for each feature. | def create_input_layers():
"""Creates dictionary of input layers for each feature.
Returns:
Dictionary of `tf.Keras.layers.Input` layers for each feature.
"""
deep_inputs = {
colname: tf.keras.layers.Input(
name=colname, shape=(), dtype="float32")
for colname in ["mo... | [
"def",
"create_input_layers",
"(",
")",
":",
"deep_inputs",
"=",
"{",
"colname",
":",
"tf",
".",
"keras",
".",
"layers",
".",
"Input",
"(",
"name",
"=",
"colname",
",",
"shape",
"=",
"(",
")",
",",
"dtype",
"=",
"\"float32\"",
")",
"for",
"colname",
... | [
81,
0
] | [
101,
17
] | python | en | ['en', 'en', 'en'] | True |
categorical_fc | (name, values) | Helper function to wrap categorical feature by indicator column.
Args:
name: str, name of feature.
values: list, list of strings of categorical values.
Returns:
Categorical and indicator column of categorical feature.
| Helper function to wrap categorical feature by indicator column. | def categorical_fc(name, values):
"""Helper function to wrap categorical feature by indicator column.
Args:
name: str, name of feature.
values: list, list of strings of categorical values.
Returns:
Categorical and indicator column of categorical feature.
"""
cat_column = tf.... | [
"def",
"categorical_fc",
"(",
"name",
",",
"values",
")",
":",
"cat_column",
"=",
"tf",
".",
"feature_column",
".",
"categorical_column_with_vocabulary_list",
"(",
"key",
"=",
"name",
",",
"vocabulary_list",
"=",
"values",
")",
"ind_column",
"=",
"tf",
".",
"f... | [
104,
0
] | [
118,
33
] | python | en | ['en', 'en', 'en'] | True |
create_feature_columns | (nembeds) | Creates wide and deep dictionaries of feature columns from inputs.
Args:
nembeds: int, number of dimensions to embed categorical column down to.
Returns:
Wide and deep dictionaries of feature columns.
| Creates wide and deep dictionaries of feature columns from inputs. | def create_feature_columns(nembeds):
"""Creates wide and deep dictionaries of feature columns from inputs.
Args:
nembeds: int, number of dimensions to embed categorical column down to.
Returns:
Wide and deep dictionaries of feature columns.
"""
deep_fc = {
colname: tf.featur... | [
"def",
"create_feature_columns",
"(",
"nembeds",
")",
":",
"deep_fc",
"=",
"{",
"colname",
":",
"tf",
".",
"feature_column",
".",
"numeric_column",
"(",
"key",
"=",
"colname",
")",
"for",
"colname",
"in",
"[",
"\"mother_age\"",
",",
"\"gestation_weeks\"",
"]",... | [
121,
0
] | [
160,
27
] | python | en | ['en', 'en', 'en'] | True |
get_model_outputs | (wide_inputs, deep_inputs, dnn_hidden_units) | Creates model architecture and returns outputs.
Args:
wide_inputs: Dense tensor used as inputs to wide side of model.
deep_inputs: Dense tensor used as inputs to deep side of model.
dnn_hidden_units: List of integers where length is number of hidden
layers and ith element is the... | Creates model architecture and returns outputs. | def get_model_outputs(wide_inputs, deep_inputs, dnn_hidden_units):
"""Creates model architecture and returns outputs.
Args:
wide_inputs: Dense tensor used as inputs to wide side of model.
deep_inputs: Dense tensor used as inputs to deep side of model.
dnn_hidden_units: List of integers ... | [
"def",
"get_model_outputs",
"(",
"wide_inputs",
",",
"deep_inputs",
",",
"dnn_hidden_units",
")",
":",
"# Hidden layers for the deep side",
"layers",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"dnn_hidden_units",
"]",
"deep",
"=",
"deep_inputs",
"for",
"l... | [
163,
0
] | [
196,
17
] | python | en | ['en', 'en', 'en'] | True |
rmse | (y_true, y_pred) | Calculates RMSE evaluation metric.
Args:
y_true: tensor, true labels.
y_pred: tensor, predicted labels.
Returns:
Tensor with value of RMSE between true and predicted labels.
| Calculates RMSE evaluation metric. | def rmse(y_true, y_pred):
"""Calculates RMSE evaluation metric.
Args:
y_true: tensor, true labels.
y_pred: tensor, predicted labels.
Returns:
Tensor with value of RMSE between true and predicted labels.
"""
return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) | [
"def",
"rmse",
"(",
"y_true",
",",
"y_pred",
")",
":",
"return",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"reduce_mean",
"(",
"tf",
".",
"square",
"(",
"y_pred",
"-",
"y_true",
")",
")",
")"
] | [
199,
0
] | [
208,
62
] | python | en | ['en', 'en', 'en'] | True |
build_wide_deep_model | (dnn_hidden_units=[64, 32], nembeds=3) | Builds wide and deep model using Keras Functional API.
Returns:
`tf.keras.models.Model` object.
| Builds wide and deep model using Keras Functional API. | def build_wide_deep_model(dnn_hidden_units=[64, 32], nembeds=3):
"""Builds wide and deep model using Keras Functional API.
Returns:
`tf.keras.models.Model` object.
"""
# Create input layers
inputs = create_input_layers()
# Create feature columns for both wide and deep
wide_fc, deep... | [
"def",
"build_wide_deep_model",
"(",
"dnn_hidden_units",
"=",
"[",
"64",
",",
"32",
"]",
",",
"nembeds",
"=",
"3",
")",
":",
"# Create input layers",
"inputs",
"=",
"create_input_layers",
"(",
")",
"# Create feature columns for both wide and deep",
"wide_fc",
",",
"... | [
211,
0
] | [
237,
16
] | python | en | ['en', 'en', 'en'] | True |
sorted_walk | (dir) | Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
| Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
| def sorted_walk(dir):
"""Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
"""
for base, dirs, files in os.walk(dir):
dirs.sort()
files.sort()
yield base, dirs, files | [
"def",
"sorted_walk",
"(",
"dir",
")",
":",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir",
")",
":",
"dirs",
".",
"sort",
"(",
")",
"files",
".",
"sort",
"(",
")",
"yield",
"base",
",",
"dirs",
",",
"files"
] | [
42,
0
] | [
49,
31
] | python | en | ['en', 'gl', 'en'] | True |
walk_egg | (egg_dir) | Walk an unpacked egg's contents, skipping the metadata directory | Walk an unpacked egg's contents, skipping the metadata directory | def walk_egg(egg_dir):
"""Walk an unpacked egg's contents, skipping the metadata directory"""
walker = sorted_walk(egg_dir)
base, dirs, files = next(walker)
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf | [
"def",
"walk_egg",
"(",
"egg_dir",
")",
":",
"walker",
"=",
"sorted_walk",
"(",
"egg_dir",
")",
"base",
",",
"dirs",
",",
"files",
"=",
"next",
"(",
"walker",
")",
"if",
"'EGG-INFO'",
"in",
"dirs",
":",
"dirs",
".",
"remove",
"(",
"'EGG-INFO'",
")",
... | [
357,
0
] | [
365,
17
] | python | en | ['en', 'en', 'en'] | True |
scan_module | (egg_dir, base, name, stubs) | Check whether module possibly uses unsafe-for-zipfile stuff | Check whether module possibly uses unsafe-for-zipfile stuff | def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base, name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
module = pkg + (pkg and '.' or '')... | [
"def",
"scan_module",
"(",
"egg_dir",
",",
"base",
",",
"name",
",",
"stubs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"name",
")",
"if",
"filename",
"[",
":",
"-",
"1",
"]",
"in",
"stubs",
":",
"return",
"True... | [
405,
0
] | [
438,
15
] | python | en | ['en', 'en', 'en'] | True |
iter_symbols | (code) | Yield names and strings used by `code` and its nested code objects | Yield names and strings used by `code` and its nested code objects | def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names:
yield name
for const in code.co_consts:
if isinstance(const, six.string_types):
yield const
elif isinstance(const, CodeType):
for name i... | [
"def",
"iter_symbols",
"(",
"code",
")",
":",
"for",
"name",
"in",
"code",
".",
"co_names",
":",
"yield",
"name",
"for",
"const",
"in",
"code",
".",
"co_consts",
":",
"if",
"isinstance",
"(",
"const",
",",
"six",
".",
"string_types",
")",
":",
"yield",... | [
441,
0
] | [
450,
26
] | python | en | ['en', 'en', 'en'] | True |
make_zipfile | (zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
mode='w') | Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecErro... | Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecErro... | def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
mode='w'):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if... | [
"def",
"make_zipfile",
"(",
"zip_filename",
",",
"base_dir",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"compress",
"=",
"True",
",",
"mode",
"=",
"'w'",
")",
":",
"import",
"zipfile",
"mkpath",
"(",
"os",
".",
"path",
".",
"dirname",
"... | [
470,
0
] | [
501,
23
] | python | en | ['en', 'en', 'en'] | True |
bdist_egg.call_command | (self, cmdname, **kw) | Invoke reinitialized command `cmdname` with keyword args | Invoke reinitialized command `cmdname` with keyword args | def call_command(self, cmdname, **kw):
"""Invoke reinitialized command `cmdname` with keyword args"""
for dirname in INSTALL_DIRECTORY_ATTRS:
kw.setdefault(dirname, self.bdist_dir)
kw.setdefault('skip_build', self.skip_build)
kw.setdefault('dry_run', self.dry_run)
cmd... | [
"def",
"call_command",
"(",
"self",
",",
"cmdname",
",",
"*",
"*",
"kw",
")",
":",
"for",
"dirname",
"in",
"INSTALL_DIRECTORY_ATTRS",
":",
"kw",
".",
"setdefault",
"(",
"dirname",
",",
"self",
".",
"bdist_dir",
")",
"kw",
".",
"setdefault",
"(",
"'skip_b... | [
150,
4
] | [
158,
18
] | python | en | ['en', 'en', 'en'] | True |
bdist_egg.copy_metadata_to | (self, target_dir) | Copy metadata (egg info) to the target_dir | Copy metadata (egg info) to the target_dir | def copy_metadata_to(self, target_dir):
"Copy metadata (egg info) to the target_dir"
# normalize the path (so that a forward-slash in egg_info will
# match using startswith below)
norm_egg_info = os.path.normpath(self.egg_info)
prefix = os.path.join(norm_egg_info, '')
for... | [
"def",
"copy_metadata_to",
"(",
"self",
",",
"target_dir",
")",
":",
"# normalize the path (so that a forward-slash in egg_info will",
"# match using startswith below)",
"norm_egg_info",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"self",
".",
"egg_info",
")",
"prefix",... | [
313,
4
] | [
323,
44
] | python | en | ['en', 'pt', 'en'] | True |
bdist_egg.get_ext_outputs | (self) | Get a list of relative paths to C extensions in the output distro | Get a list of relative paths to C extensions in the output distro | def get_ext_outputs(self):
"""Get a list of relative paths to C extensions in the output distro"""
all_outputs = []
ext_outputs = []
paths = {self.bdist_dir: ''}
for base, dirs, files in sorted_walk(self.bdist_dir):
for filename in files:
if os.path.... | [
"def",
"get_ext_outputs",
"(",
"self",
")",
":",
"all_outputs",
"=",
"[",
"]",
"ext_outputs",
"=",
"[",
"]",
"paths",
"=",
"{",
"self",
".",
"bdist_dir",
":",
"''",
"}",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"sorted_walk",
"(",
"self",
".",... | [
325,
4
] | [
351,
39
] | python | en | ['en', 'en', 'en'] | True |
Resolution._push_new_state | (self) | Push a new state into history.
This new state will be used to hold resolution results of the next
coming round.
| Push a new state into history. | def _push_new_state(self):
"""Push a new state into history.
This new state will be used to hold resolution results of the next
coming round.
"""
base = self._states[-1]
state = State(
mapping=base.mapping.copy(),
criteria=base.criteria.copy(),
... | [
"def",
"_push_new_state",
"(",
"self",
")",
":",
"base",
"=",
"self",
".",
"_states",
"[",
"-",
"1",
"]",
"state",
"=",
"State",
"(",
"mapping",
"=",
"base",
".",
"mapping",
".",
"copy",
"(",
")",
",",
"criteria",
"=",
"base",
".",
"criteria",
".",... | [
123,
4
] | [
134,
34
] | python | en | ['en', 'en', 'en'] | True |
Resolution._backtrack | (self) | Perform backtracking.
When we enter here, the stack is like this::
[ state Z ]
[ state Y ]
[ state X ]
.... earlier states are irrelevant.
1. No pins worked for Z, so it does not have a pin.
2. We want to reset state Y to unpinned, and pin anoth... | Perform backtracking. | def _backtrack(self):
"""Perform backtracking.
When we enter here, the stack is like this::
[ state Z ]
[ state Y ]
[ state X ]
.... earlier states are irrelevant.
1. No pins worked for Z, so it does not have a pin.
2. We want to reset s... | [
"def",
"_backtrack",
"(",
"self",
")",
":",
"while",
"len",
"(",
"self",
".",
"_states",
")",
">=",
"3",
":",
"# Remove the state that triggered backtracking.",
"del",
"self",
".",
"_states",
"[",
"-",
"1",
"]",
"# Retrieve the last candidate pin and known incompati... | [
241,
4
] | [
328,
20
] | python | en | ['en', 'en', 'en'] | False |
Resolver.resolve | (self, requirements, max_rounds=100) | Take a collection of constraints, spit out the resolution result.
The return value is a representation to the final resolution result. It
is a tuple subclass with three public members:
* `mapping`: A dict of resolved candidates. Each key is an identifier
of a requirement (as return... | Take a collection of constraints, spit out the resolution result. | def resolve(self, requirements, max_rounds=100):
"""Take a collection of constraints, spit out the resolution result.
The return value is a representation to the final resolution result. It
is a tuple subclass with three public members:
* `mapping`: A dict of resolved candidates. Each ... | [
"def",
"resolve",
"(",
"self",
",",
"requirements",
",",
"max_rounds",
"=",
"100",
")",
":",
"resolution",
"=",
"Resolution",
"(",
"self",
".",
"provider",
",",
"self",
".",
"reporter",
")",
"state",
"=",
"resolution",
".",
"resolve",
"(",
"requirements",
... | [
442,
4
] | [
472,
35
] | python | en | ['en', 'en', 'en'] | True |
load_cdll | (name, macos10_16_path) | Loads a CDLL by name, falling back to known path on 10.16+ | Loads a CDLL by name, falling back to known path on 10.16+ | def load_cdll(name, macos10_16_path):
"""Loads a CDLL by name, falling back to known path on 10.16+"""
try:
# Big Sur is technically 11 but we use 10.16 due to the Big Sur
# beta being labeled as 10.16.
if version_info >= (10, 16):
path = macos10_16_path
else:
... | [
"def",
"load_cdll",
"(",
"name",
",",
"macos10_16_path",
")",
":",
"try",
":",
"# Big Sur is technically 11 but we use 10.16 due to the Big Sur",
"# beta being labeled as 10.16.",
"if",
"version_info",
">=",
"(",
"10",
",",
"16",
")",
":",
"path",
"=",
"macos10_16_path"... | [
64,
0
] | [
77,
77
] | python | en | ['en', 'en', 'en'] | True |
init_logging | (quiet, loglevel, configdir) | Initializes the console and file handlers for the logging module. | Initializes the console and file handlers for the logging module. | def init_logging(quiet, loglevel, configdir):
"Initializes the console and file handlers for the logging module."
logger = logging.getLogger()
# Set the loglevel.
if loglevel > 3:
loglevel = 3
levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
logger.setLevel(levels[log... | [
"def",
"init_logging",
"(",
"quiet",
",",
"loglevel",
",",
"configdir",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"# Set the loglevel.",
"if",
"loglevel",
">",
"3",
":",
"loglevel",
"=",
"3",
"levels",
"=",
"[",
"logging",
".",
"ERR... | [
40,
0
] | [
68,
50
] | python | en | ['en', 'en', 'en'] | True |
get_configdir | () | Determines where to store our logs and read our config file from. | Determines where to store our logs and read our config file from. | def get_configdir():
"Determines where to store our logs and read our config file from."
configdir = os.path.dirname(os.path.realpath(__file__)) # We are here.
home = os.path.join(os.path.expanduser("~"), ".gmxmail")
homeconfig = os.path.join(os.path.expanduser("~"), ".config/gmxmail")
if os.path.i... | [
"def",
"get_configdir",
"(",
")",
":",
"configdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"# We are here.",
"home",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
"... | [
71,
0
] | [
81,
20
] | python | en | ['en', 'en', 'en'] | True |
main | () | Entry point for gmxmail. Parse command-line arguments and instantiate MH. | Entry point for gmxmail. Parse command-line arguments and instantiate MH. | def main():
"Entry point for gmxmail. Parse command-line arguments and instantiate MH."
args = docopt(__doc__, version="0.1")
configdir = get_configdir()
init_logging(args["--quiet"], args["-v"], configdir)
# Loglevels: 10 (Debug), 20 (Info), 30 (Warn), 40 (Error)
log.info("Loglevel is {}".fo... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"\"0.1\"",
")",
"configdir",
"=",
"get_configdir",
"(",
")",
"init_logging",
"(",
"args",
"[",
"\"--quiet\"",
"]",
",",
"args",
"[",
"\"-v\"",
"]",
",",
"configdi... | [
84,
0
] | [
103,
20
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.ensure_timezone | (self) |
Ensure the connection's timezone is set to `self.timezone_name` and
return whether it changed or not.
|
Ensure the connection's timezone is set to `self.timezone_name` and
return whether it changed or not.
| def ensure_timezone(self):
"""
Ensure the connection's timezone is set to `self.timezone_name` and
return whether it changed or not.
"""
return False | [
"def",
"ensure_timezone",
"(",
"self",
")",
":",
"return",
"False"
] | [
109,
4
] | [
114,
20
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.timezone | (self) |
Return a tzinfo of the database connection time zone.
This is only used when time zone support is enabled. When a datetime is
read from the database, it is always returned in this time zone.
When the database backend supports time zones, it doesn't matter which
time zone Djang... |
Return a tzinfo of the database connection time zone. | def timezone(self):
"""
Return a tzinfo of the database connection time zone.
This is only used when time zone support is enabled. When a datetime is
read from the database, it is always returned in this time zone.
When the database backend supports time zones, it doesn't matte... | [
"def",
"timezone",
"(",
"self",
")",
":",
"if",
"not",
"settings",
".",
"USE_TZ",
":",
"return",
"None",
"elif",
"self",
".",
"settings_dict",
"[",
"'TIME_ZONE'",
"]",
"is",
"None",
":",
"return",
"timezone",
".",
"utc",
"else",
":",
"return",
"pytz",
... | [
117,
4
] | [
137,
65
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.timezone_name | (self) |
Name of the time zone of the database connection.
|
Name of the time zone of the database connection.
| def timezone_name(self):
"""
Name of the time zone of the database connection.
"""
if not settings.USE_TZ:
return settings.TIME_ZONE
elif self.settings_dict['TIME_ZONE'] is None:
return 'UTC'
else:
return self.settings_dict['TIME_ZONE'] | [
"def",
"timezone_name",
"(",
"self",
")",
":",
"if",
"not",
"settings",
".",
"USE_TZ",
":",
"return",
"settings",
".",
"TIME_ZONE",
"elif",
"self",
".",
"settings_dict",
"[",
"'TIME_ZONE'",
"]",
"is",
"None",
":",
"return",
"'UTC'",
"else",
":",
"return",
... | [
140,
4
] | [
149,
50
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.get_connection_params | (self) | Return a dict of parameters suitable for get_new_connection. | Return a dict of parameters suitable for get_new_connection. | def get_connection_params(self):
"""Return a dict of parameters suitable for get_new_connection."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_connection_params() method') | [
"def",
"get_connection_params",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a get_connection_params() method'",
")"
] | [
165,
4
] | [
167,
115
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.get_new_connection | (self, conn_params) | Open a connection to the database. | Open a connection to the database. | def get_new_connection(self, conn_params):
"""Open a connection to the database."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_new_connection() method') | [
"def",
"get_new_connection",
"(",
"self",
",",
"conn_params",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a get_new_connection() method'",
")"
] | [
169,
4
] | [
171,
112
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.init_connection_state | (self) | Initialize the database connection settings. | Initialize the database connection settings. | def init_connection_state(self):
"""Initialize the database connection settings."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require an init_connection_state() method') | [
"def",
"init_connection_state",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require an init_connection_state() method'",
")"
] | [
173,
4
] | [
175,
116
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.create_cursor | (self, name=None) | Create a cursor. Assume that a connection is established. | Create a cursor. Assume that a connection is established. | def create_cursor(self, name=None):
"""Create a cursor. Assume that a connection is established."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a create_cursor() method') | [
"def",
"create_cursor",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a create_cursor() method'",
")"
] | [
177,
4
] | [
179,
107
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.connect | (self) | Connect to the database. Assume that the connection is closed. | Connect to the database. Assume that the connection is closed. | def connect(self):
"""Connect to the database. Assume that the connection is closed."""
# Check for invalid configurations.
self.check_settings()
# In case the previous connection was closed while in an atomic block
self.in_atomic_block = False
self.savepoint_ids = []
... | [
"def",
"connect",
"(",
"self",
")",
":",
"# Check for invalid configurations.",
"self",
".",
"check_settings",
"(",
")",
"# In case the previous connection was closed while in an atomic block",
"self",
".",
"in_atomic_block",
"=",
"False",
"self",
".",
"savepoint_ids",
"=",... | [
184,
4
] | [
204,
31
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.ensure_connection | (self) | Guarantee that a connection to the database is established. | Guarantee that a connection to the database is established. | def ensure_connection(self):
"""Guarantee that a connection to the database is established."""
if self.connection is None:
with self.wrap_database_errors:
self.connect() | [
"def",
"ensure_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
"is",
"None",
":",
"with",
"self",
".",
"wrap_database_errors",
":",
"self",
".",
"connect",
"(",
")"
] | [
214,
4
] | [
218,
30
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper._prepare_cursor | (self, cursor) |
Validate the connection is usable and perform database cursor wrapping.
|
Validate the connection is usable and perform database cursor wrapping.
| def _prepare_cursor(self, cursor):
"""
Validate the connection is usable and perform database cursor wrapping.
"""
self.validate_thread_sharing()
if self.queries_logged:
wrapped_cursor = self.make_debug_cursor(cursor)
else:
wrapped_cursor = self.ma... | [
"def",
"_prepare_cursor",
"(",
"self",
",",
"cursor",
")",
":",
"self",
".",
"validate_thread_sharing",
"(",
")",
"if",
"self",
".",
"queries_logged",
":",
"wrapped_cursor",
"=",
"self",
".",
"make_debug_cursor",
"(",
"cursor",
")",
"else",
":",
"wrapped_curso... | [
222,
4
] | [
231,
29
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.cursor | (self) | Create a cursor, opening a connection if necessary. | Create a cursor, opening a connection if necessary. | def cursor(self):
"""Create a cursor, opening a connection if necessary."""
return self._cursor() | [
"def",
"cursor",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cursor",
"(",
")"
] | [
256,
4
] | [
258,
29
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.commit | (self) | Commit a transaction and reset the dirty flag. | Commit a transaction and reset the dirty flag. | def commit(self):
"""Commit a transaction and reset the dirty flag."""
self.validate_thread_sharing()
self.validate_no_atomic_block()
self._commit()
# A successful commit means that the database connection works.
self.errors_occurred = False
self.run_commit_hooks_... | [
"def",
"commit",
"(",
"self",
")",
":",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"validate_no_atomic_block",
"(",
")",
"self",
".",
"_commit",
"(",
")",
"# A successful commit means that the database connection works.",
"self",
".",
"errors_occur... | [
261,
4
] | [
268,
57
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.rollback | (self) | Roll back a transaction and reset the dirty flag. | Roll back a transaction and reset the dirty flag. | def rollback(self):
"""Roll back a transaction and reset the dirty flag."""
self.validate_thread_sharing()
self.validate_no_atomic_block()
self._rollback()
# A successful rollback means that the database connection works.
self.errors_occurred = False
self.needs_ro... | [
"def",
"rollback",
"(",
"self",
")",
":",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"validate_no_atomic_block",
"(",
")",
"self",
".",
"_rollback",
"(",
")",
"# A successful rollback means that the database connection works.",
"self",
".",
"errors... | [
271,
4
] | [
279,
31
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.close | (self) | Close the connection to the database. | Close the connection to the database. | def close(self):
"""Close the connection to the database."""
self.validate_thread_sharing()
self.run_on_commit = []
# Don't call validate_no_atomic_block() to avoid making it difficult
# to get rid of a connection in an invalid state. The next connect()
# will reset the ... | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"run_on_commit",
"=",
"[",
"]",
"# Don't call validate_no_atomic_block() to avoid making it difficult",
"# to get rid of a connection in an invalid state. The next connect()",
... | [
282,
4
] | [
299,
38
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.savepoint | (self) |
Create a savepoint inside the current transaction. Return an
identifier for the savepoint that will be used for the subsequent
rollback or commit. Do nothing if savepoints are not supported.
|
Create a savepoint inside the current transaction. Return an
identifier for the savepoint that will be used for the subsequent
rollback or commit. Do nothing if savepoints are not supported.
| def savepoint(self):
"""
Create a savepoint inside the current transaction. Return an
identifier for the savepoint that will be used for the subsequent
rollback or commit. Do nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
return... | [
"def",
"savepoint",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_savepoint_allowed",
"(",
")",
":",
"return",
"thread_ident",
"=",
"_thread",
".",
"get_ident",
"(",
")",
"tid",
"=",
"str",
"(",
"thread_ident",
")",
".",
"replace",
"(",
"'-'",
","... | [
322,
4
] | [
340,
18
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.savepoint_rollback | (self, sid) |
Roll back to a savepoint. Do nothing if savepoints are not supported.
|
Roll back to a savepoint. Do nothing if savepoints are not supported.
| def savepoint_rollback(self, sid):
"""
Roll back to a savepoint. Do nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
return
self.validate_thread_sharing()
self._savepoint_rollback(sid)
# Remove any callbacks registered w... | [
"def",
"savepoint_rollback",
"(",
"self",
",",
"sid",
")",
":",
"if",
"not",
"self",
".",
"_savepoint_allowed",
"(",
")",
":",
"return",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"_savepoint_rollback",
"(",
"sid",
")",
"# Remove any callba... | [
343,
4
] | [
356,
9
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.savepoint_commit | (self, sid) |
Release a savepoint. Do nothing if savepoints are not supported.
|
Release a savepoint. Do nothing if savepoints are not supported.
| def savepoint_commit(self, sid):
"""
Release a savepoint. Do nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
return
self.validate_thread_sharing()
self._savepoint_commit(sid) | [
"def",
"savepoint_commit",
"(",
"self",
",",
"sid",
")",
":",
"if",
"not",
"self",
".",
"_savepoint_allowed",
"(",
")",
":",
"return",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"_savepoint_commit",
"(",
"sid",
")"
] | [
359,
4
] | [
367,
35
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.clean_savepoints | (self) |
Reset the counter used to generate unique savepoint ids in this thread.
|
Reset the counter used to generate unique savepoint ids in this thread.
| def clean_savepoints(self):
"""
Reset the counter used to generate unique savepoint ids in this thread.
"""
self.savepoint_state = 0 | [
"def",
"clean_savepoints",
"(",
"self",
")",
":",
"self",
".",
"savepoint_state",
"=",
"0"
] | [
370,
4
] | [
374,
32
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper._set_autocommit | (self, autocommit) |
Backend-specific implementation to enable or disable autocommit.
|
Backend-specific implementation to enable or disable autocommit.
| def _set_autocommit(self, autocommit):
"""
Backend-specific implementation to enable or disable autocommit.
"""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a _set_autocommit() method') | [
"def",
"_set_autocommit",
"(",
"self",
",",
"autocommit",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a _set_autocommit() method'",
")"
] | [
378,
4
] | [
382,
109
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.get_autocommit | (self) | Get the autocommit state. | Get the autocommit state. | def get_autocommit(self):
"""Get the autocommit state."""
self.ensure_connection()
return self.autocommit | [
"def",
"get_autocommit",
"(",
"self",
")",
":",
"self",
".",
"ensure_connection",
"(",
")",
"return",
"self",
".",
"autocommit"
] | [
386,
4
] | [
389,
30
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.set_autocommit | (self, autocommit, force_begin_transaction_with_broken_autocommit=False) |
Enable or disable autocommit.
The usual way to start a transaction is to turn autocommit off.
SQLite does not properly start a transaction when disabling
autocommit. To avoid this buggy behavior and to actually enter a new
transaction, an explicit BEGIN is required. Using
... |
Enable or disable autocommit. | def set_autocommit(self, autocommit, force_begin_transaction_with_broken_autocommit=False):
"""
Enable or disable autocommit.
The usual way to start a transaction is to turn autocommit off.
SQLite does not properly start a transaction when disabling
autocommit. To avoid this bug... | [
"def",
"set_autocommit",
"(",
"self",
",",
"autocommit",
",",
"force_begin_transaction_with_broken_autocommit",
"=",
"False",
")",
":",
"self",
".",
"validate_no_atomic_block",
"(",
")",
"self",
".",
"ensure_connection",
"(",
")",
"start_transaction_under_autocommit",
"... | [
391,
4
] | [
420,
62
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.get_rollback | (self) | Get the "needs rollback" flag -- for *advanced use* only. | Get the "needs rollback" flag -- for *advanced use* only. | def get_rollback(self):
"""Get the "needs rollback" flag -- for *advanced use* only."""
if not self.in_atomic_block:
raise TransactionManagementError(
"The rollback flag doesn't work outside of an 'atomic' block.")
return self.needs_rollback | [
"def",
"get_rollback",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"in_atomic_block",
":",
"raise",
"TransactionManagementError",
"(",
"\"The rollback flag doesn't work outside of an 'atomic' block.\"",
")",
"return",
"self",
".",
"needs_rollback"
] | [
422,
4
] | [
427,
34
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.set_rollback | (self, rollback) |
Set or unset the "needs rollback" flag -- for *advanced use* only.
|
Set or unset the "needs rollback" flag -- for *advanced use* only.
| def set_rollback(self, rollback):
"""
Set or unset the "needs rollback" flag -- for *advanced use* only.
"""
if not self.in_atomic_block:
raise TransactionManagementError(
"The rollback flag doesn't work outside of an 'atomic' block.")
self.needs_rollb... | [
"def",
"set_rollback",
"(",
"self",
",",
"rollback",
")",
":",
"if",
"not",
"self",
".",
"in_atomic_block",
":",
"raise",
"TransactionManagementError",
"(",
"\"The rollback flag doesn't work outside of an 'atomic' block.\"",
")",
"self",
".",
"needs_rollback",
"=",
"rol... | [
429,
4
] | [
436,
38
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.validate_no_atomic_block | (self) | Raise an error if an atomic block is active. | Raise an error if an atomic block is active. | def validate_no_atomic_block(self):
"""Raise an error if an atomic block is active."""
if self.in_atomic_block:
raise TransactionManagementError(
"This is forbidden when an 'atomic' block is active.") | [
"def",
"validate_no_atomic_block",
"(",
"self",
")",
":",
"if",
"self",
".",
"in_atomic_block",
":",
"raise",
"TransactionManagementError",
"(",
"\"This is forbidden when an 'atomic' block is active.\"",
")"
] | [
438,
4
] | [
442,
70
] | python | en | ['en', 'lb', 'en'] | True |
BaseDatabaseWrapper.constraint_checks_disabled | (self) |
Disable foreign key constraint checking.
|
Disable foreign key constraint checking.
| def constraint_checks_disabled(self):
"""
Disable foreign key constraint checking.
"""
disabled = self.disable_constraint_checking()
try:
yield
finally:
if disabled:
self.enable_constraint_checking() | [
"def",
"constraint_checks_disabled",
"(",
"self",
")",
":",
"disabled",
"=",
"self",
".",
"disable_constraint_checking",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"if",
"disabled",
":",
"self",
".",
"enable_constraint_checking",
"(",
")"
] | [
453,
4
] | [
462,
49
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.disable_constraint_checking | (self) |
Backends can implement as needed to temporarily disable foreign key
constraint checking. Should return True if the constraints were
disabled and will need to be reenabled.
|
Backends can implement as needed to temporarily disable foreign key
constraint checking. Should return True if the constraints were
disabled and will need to be reenabled.
| def disable_constraint_checking(self):
"""
Backends can implement as needed to temporarily disable foreign key
constraint checking. Should return True if the constraints were
disabled and will need to be reenabled.
"""
return False | [
"def",
"disable_constraint_checking",
"(",
"self",
")",
":",
"return",
"False"
] | [
464,
4
] | [
470,
20
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.enable_constraint_checking | (self) |
Backends can implement as needed to re-enable foreign key constraint
checking.
|
Backends can implement as needed to re-enable foreign key constraint
checking.
| def enable_constraint_checking(self):
"""
Backends can implement as needed to re-enable foreign key constraint
checking.
"""
pass | [
"def",
"enable_constraint_checking",
"(",
"self",
")",
":",
"pass"
] | [
472,
4
] | [
477,
12
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.