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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Base.from_decimal | (self, n, base=10) | Input: base10 integer. Output: base2-64 string. | Input: base10 integer. Output: base2-64 string. | def from_decimal(self, n, base=10):
"Input: base10 integer. Output: base2-64 string."
try:
n = int(n)
except (ValueError, TypeError):
return "NaN"
if base < 2 or base > 64:
return "N/A"
basecases = "0123456789" + self.alphabet
if 63 <=... | [
"def",
"from_decimal",
"(",
"self",
",",
"n",
",",
"base",
"=",
"10",
")",
":",
"try",
":",
"n",
"=",
"int",
"(",
"n",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"\"NaN\"",
"if",
"base",
"<",
"2",
"or",
"base",
">",
... | [
54,
4
] | [
74,
31
] | python | da | ['de', 'da', 'en'] | False |
Base.to_decimal | (self, s, base=10) | Input: base2-64 string. Output: base10 integer. | Input: base2-64 string. Output: base10 integer. | def to_decimal(self, s, base=10):
"Input: base2-64 string. Output: base10 integer."
try:
s = str(s)
except (ValueError, TypeError):
return "NaN"
if base < 2 or base > 64:
return "N/A"
basecases = "0123456789" + self.alphabet
if 63 <= b... | [
"def",
"to_decimal",
"(",
"self",
",",
"s",
",",
"base",
"=",
"10",
")",
":",
"try",
":",
"s",
"=",
"str",
"(",
"s",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"\"NaN\"",
"if",
"base",
"<",
"2",
"or",
"base",
">",
"... | [
76,
4
] | [
102,
16
] | python | da | ['de', 'da', 'en'] | False |
Data.kilobytes | (self) | 1000 bytes, kB or KB | 1000 bytes, kB or KB | def kilobytes(self):
"1000 bytes, kB or KB"
return format_num(self._bytes / 1000, self.decplaces) | [
"def",
"kilobytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"1000",
",",
"self",
".",
"decplaces",
")"
] | [
129,
4
] | [
131,
61
] | python | en | ['en', 'hmn', 'en'] | True |
Data.megabytes | (self) | 1000^2 bytes, MB | 1000^2 bytes, MB | def megabytes(self):
"1000^2 bytes, MB"
return format_num(self._bytes / (1000 ** 2), self.decplaces) | [
"def",
"megabytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"(",
"1000",
"**",
"2",
")",
",",
"self",
".",
"decplaces",
")"
] | [
138,
4
] | [
140,
68
] | python | en | ['en', 'hu', 'hi'] | False |
Data.gigabytes | (self) | 1000^3 bytes, GB | 1000^3 bytes, GB | def gigabytes(self):
"1000^3 bytes, GB"
return format_num(self._bytes / (1000 ** 3), self.decplaces) | [
"def",
"gigabytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"(",
"1000",
"**",
"3",
")",
",",
"self",
".",
"decplaces",
")"
] | [
147,
4
] | [
149,
68
] | python | en | ['en', 'uz', 'en'] | True |
Data.terrabytes | (self) | 1000^4 bytes, TB | 1000^4 bytes, TB | def terrabytes(self):
"1000^4 bytes, TB"
return format_num(self._bytes / (1000 ** 4), self.decplaces) | [
"def",
"terrabytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"(",
"1000",
"**",
"4",
")",
",",
"self",
".",
"decplaces",
")"
] | [
156,
4
] | [
158,
68
] | python | en | ['en', 'hu', 'hi'] | False |
Data.petabytes | (self) | 1000^5 bytes, PB | 1000^5 bytes, PB | def petabytes(self):
"1000^5 bytes, PB"
return format_num(self._bytes / (1000 ** 5), self.decplaces) | [
"def",
"petabytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"(",
"1000",
"**",
"5",
")",
",",
"self",
".",
"decplaces",
")"
] | [
165,
4
] | [
167,
68
] | python | hi | ['nl', 'uz', 'hi'] | False |
Data.kibibytes | (self) | 1024 bytes, KiB or KB | 1024 bytes, KiB or KB | def kibibytes(self):
"1024 bytes, KiB or KB"
return format_num(self._bytes / 1024, self.decplaces) | [
"def",
"kibibytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"1024",
",",
"self",
".",
"decplaces",
")"
] | [
174,
4
] | [
176,
61
] | python | en | ['en', 'hmn', 'hi'] | False |
Data.mebibytes | (self) | 1024^2 bytes, MiB | 1024^2 bytes, MiB | def mebibytes(self):
"1024^2 bytes, MiB"
return format_num(self._bytes / (1024 ** 2), self.decplaces) | [
"def",
"mebibytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"(",
"1024",
"**",
"2",
")",
",",
"self",
".",
"decplaces",
")"
] | [
183,
4
] | [
185,
68
] | python | en | ['en', 'uz', 'hi'] | False |
Data.gibibytes | (self) | 1024^3 bytes, GiB | 1024^3 bytes, GiB | def gibibytes(self):
"1024^3 bytes, GiB"
return format_num(self._bytes / (1024 ** 3), self.decplaces) | [
"def",
"gibibytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"(",
"1024",
"**",
"3",
")",
",",
"self",
".",
"decplaces",
")"
] | [
192,
4
] | [
194,
68
] | python | en | ['en', 'ru-Latn', 'hi'] | False |
Data.tebibytes | (self) | 1024^4 bytes, TiB | 1024^4 bytes, TiB | def tebibytes(self):
"1024^4 bytes, TiB"
return format_num(self._bytes / (1024 ** 4), self.decplaces) | [
"def",
"tebibytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"(",
"1024",
"**",
"4",
")",
",",
"self",
".",
"decplaces",
")"
] | [
201,
4
] | [
203,
68
] | python | en | ['en', 'uz', 'hi'] | False |
Data.pebibytes | (self) | 1024^5 bytes, PiB | 1024^5 bytes, PiB | def pebibytes(self):
"1024^5 bytes, PiB"
return format_num(self._bytes / (1024 ** 5), self.decplaces) | [
"def",
"pebibytes",
"(",
"self",
")",
":",
"return",
"format_num",
"(",
"self",
".",
"_bytes",
"/",
"(",
"1024",
"**",
"5",
")",
",",
"self",
".",
"decplaces",
")"
] | [
210,
4
] | [
212,
68
] | python | en | ['en', 'uk', 'hi'] | False |
init_logger | (logpath=None, loglevel=1, quiet=False) | Initializes the logging module. | Initializes the logging module. | def init_logger(logpath=None, loglevel=1, quiet=False):
"Initializes the logging module."
logger = logging.getLogger()
# Set the loglevel.
if loglevel > 3:
loglevel = 3 # Cap at 3 to avoid index errors.
levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
logger.setLevel... | [
"def",
"init_logger",
"(",
"logpath",
"=",
"None",
",",
"loglevel",
"=",
"1",
",",
"quiet",
"=",
"False",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"# Set the loglevel.",
"if",
"loglevel",
">",
"3",
":",
"loglevel",
"=",
"3",
"# C... | [
286,
0
] | [
314,
55
] | python | en | ['en', 'en', 'en'] | True |
main | () | Entry point for the CLI-version of Blockify. | Entry point for the CLI-version of Blockify. | def main():
"Entry point for the CLI-version of Blockify."
try:
args = docopt(__doc__, version="1.0")
init_logger(args["--log"], args["-v"], args["--quiet"])
except NameError:
init_logger(logpath=None, loglevel=2, quiet=False)
log.error("Please install docopt to use the CLI."... | [
"def",
"main",
"(",
")",
":",
"try",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"\"1.0\"",
")",
"init_logger",
"(",
"args",
"[",
"\"--log\"",
"]",
",",
"args",
"[",
"\"-v\"",
"]",
",",
"args",
"[",
"\"--quiet\"",
"]",
")",
"ex... | [
317,
0
] | [
337,
23
] | python | en | ['en', 'en', 'en'] | True |
Blocklist.append | (self, item) | Overloading list.append to automatically save the list to a file. | Overloading list.append to automatically save the list to a file. | def append(self, item):
"Overloading list.append to automatically save the list to a file."
# Only allow nonempty strings.
if item in self or not item or item == " ":
log.debug("Not adding empty or duplicate item: {}.".format(item))
return
log.info("Adding {} to {... | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"# Only allow nonempty strings.",
"if",
"item",
"in",
"self",
"or",
"not",
"item",
"or",
"item",
"==",
"\" \"",
":",
"log",
".",
"debug",
"(",
"\"Not adding empty or duplicate item: {}.\"",
".",
"format",
"(... | [
51,
4
] | [
59,
19
] | python | en | ['en', 'en', 'en'] | True |
Blockify.update | (self) | Main loop. Checks for blocklist match and mutes accordingly. | Main loop. Checks for blocklist match and mutes accordingly. | def update(self):
"Main loop. Checks for blocklist match and mutes accordingly."
# It all relies on current_song.
self.current_song = self.get_current_song()
if not self.current_song or not self.automute:
return
# Check if the blockfile has changed.
current_... | [
"def",
"update",
"(",
"self",
")",
":",
"# It all relies on current_song.",
"self",
".",
"current_song",
"=",
"self",
".",
"get_current_song",
"(",
")",
"if",
"not",
"self",
".",
"current_song",
"or",
"not",
"self",
".",
"automute",
":",
"return",
"# Check if ... | [
119,
4
] | [
140,
20
] | python | en | ['en', 'en', 'en'] | True |
Blockify.get_windows | (self) | Libwnck list of currently open windows. | Libwnck list of currently open windows. | def get_windows(self):
"Libwnck list of currently open windows."
# Get the current screen.
screen = wnck.screen_get_default()
# Object list of windows in screen.
windows = screen.get_windows()
# Return the actual list of windows or an empty list.
return [win.get... | [
"def",
"get_windows",
"(",
"self",
")",
":",
"# Get the current screen.",
"screen",
"=",
"wnck",
".",
"screen_get_default",
"(",
")",
"# Object list of windows in screen.",
"windows",
"=",
"screen",
".",
"get_windows",
"(",
")",
"# Return the actual list of windows or an ... | [
142,
4
] | [
151,
71
] | python | en | ['en', 'en', 'en'] | True |
Blockify.get_current_song | (self) | Checks if a Spotify window exists and returns the current songname. | Checks if a Spotify window exists and returns the current songname. | def get_current_song(self):
"Checks if a Spotify window exists and returns the current songname."
pipe = self.get_windows()
for line in pipe:
if line.startswith("Spotify - "):
# Remove "Spotify - " and return the rest of the songname.
return " ".join(l... | [
"def",
"get_current_song",
"(",
"self",
")",
":",
"pipe",
"=",
"self",
".",
"get_windows",
"(",
")",
"for",
"line",
"in",
"pipe",
":",
"if",
"line",
".",
"startswith",
"(",
"\"Spotify - \"",
")",
":",
"# Remove \"Spotify - \" and return the rest of the songname.",... | [
153,
4
] | [
162,
17
] | python | en | ['en', 'en', 'en'] | True |
Blockify.alsa_mute | (self, force) | Mute method for systems without Pulseaudio. Mutes sound system-wide. | Mute method for systems without Pulseaudio. Mutes sound system-wide. | def alsa_mute(self, force):
"Mute method for systems without Pulseaudio. Mutes sound system-wide."
state = self.get_state(force)
if not state:
return
for channel in self.channels:
subprocess.Popen(["amixer", "-q", "set", channel, state]) | [
"def",
"alsa_mute",
"(",
"self",
",",
"force",
")",
":",
"state",
"=",
"self",
".",
"get_state",
"(",
"force",
")",
"if",
"not",
"state",
":",
"return",
"for",
"channel",
"in",
"self",
".",
"channels",
":",
"subprocess",
".",
"Popen",
"(",
"[",
"\"am... | [
210,
4
] | [
217,
69
] | python | en | ['en', 'en', 'en'] | True |
Blockify.pulse_mute | (self, force) | Used if pulseaudio is installed but no sinks are found. System-wide. | Used if pulseaudio is installed but no sinks are found. System-wide. | def pulse_mute(self, force):
"Used if pulseaudio is installed but no sinks are found. System-wide."
state = self.get_state(force)
if not state:
return
for channel in self.channels:
subprocess.Popen(["amixer", "-qD", "pulse", "set", channel, state]) | [
"def",
"pulse_mute",
"(",
"self",
",",
"force",
")",
":",
"state",
"=",
"self",
".",
"get_state",
"(",
"force",
")",
"if",
"not",
"state",
":",
"return",
"for",
"channel",
"in",
"self",
".",
"channels",
":",
"subprocess",
".",
"Popen",
"(",
"[",
"\"a... | [
219,
4
] | [
226,
79
] | python | en | ['en', 'en', 'en'] | True |
Blockify.pulsesink_mute | (self, force) | Finds spotify's audio sink and toggles its mute state. | Finds spotify's audio sink and toggles its mute state. | def pulsesink_mute(self, force):
"Finds spotify's audio sink and toggles its mute state."
try:
pacmd_out = subprocess.check_output(["pacmd", "list-sink-inputs"])
pidof_out = subprocess.check_output(["pidof", "spotify"])
except subprocess.CalledProcessError:
lo... | [
"def",
"pulsesink_mute",
"(",
"self",
",",
"force",
")",
":",
"try",
":",
"pacmd_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"pacmd\"",
",",
"\"list-sink-inputs\"",
"]",
")",
"pidof_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"pid... | [
235,
4
] | [
267,
73
] | python | en | ['en', 'en', 'en'] | True |
Blockify.bind_signals | (self) | Catch SIGINT and SIGTERM to exit cleanly & SIGUSR1 to block a song. | Catch SIGINT and SIGTERM to exit cleanly & SIGUSR1 to block a song. | def bind_signals(self):
"Catch SIGINT and SIGTERM to exit cleanly & SIGUSR1 to block a song."
signal.signal(signal.SIGUSR1, lambda sig, hdl: self.block_current())
signal.signal(signal.SIGUSR2, lambda sig, hdl: self.unblock_current())
signal.signal(signal.SIGTERM, lambda sig, hdl: self.st... | [
"def",
"bind_signals",
"(",
"self",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGUSR1",
",",
"lambda",
"sig",
",",
"hdl",
":",
"self",
".",
"block_current",
"(",
")",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGUSR2",
",",
"la... | [
269,
4
] | [
274,
66
] | python | en | ['en', 'en', 'en'] | True |
render_value_in_context | (value, context) |
Convert any value to a string to become part of a rendered template. This
means escaping, if required, and conversion to a string. If value is a
string, it's expected to already be translated.
|
Convert any value to a string to become part of a rendered template. This
means escaping, if required, and conversion to a string. If value is a
string, it's expected to already be translated.
| def render_value_in_context(value, context):
"""
Convert any value to a string to become part of a rendered template. This
means escaping, if required, and conversion to a string. If value is a
string, it's expected to already be translated.
"""
value = template_localtime(value, use_tz=context.u... | [
"def",
"render_value_in_context",
"(",
"value",
",",
"context",
")",
":",
"value",
"=",
"template_localtime",
"(",
"value",
",",
"use_tz",
"=",
"context",
".",
"use_tz",
")",
"value",
"=",
"localize",
"(",
"value",
",",
"use_l10n",
"=",
"context",
".",
"us... | [
962,
0
] | [
975,
25
] | python | en | ['en', 'error', 'th'] | False |
token_kwargs | (bits, parser, support_legacy=False) |
Parse token keyword arguments and return a dictionary of the arguments
retrieved from the ``bits`` token list.
`bits` is a list containing the remainder of the token (split by spaces)
that is to be checked for arguments. Valid arguments are removed from this
list.
`support_legacy` - if True, ... |
Parse token keyword arguments and return a dictionary of the arguments
retrieved from the ``bits`` token list. | def token_kwargs(bits, parser, support_legacy=False):
"""
Parse token keyword arguments and return a dictionary of the arguments
retrieved from the ``bits`` token list.
`bits` is a list containing the remainder of the token (split by spaces)
that is to be checked for arguments. Valid arguments are ... | [
"def",
"token_kwargs",
"(",
"bits",
",",
"parser",
",",
"support_legacy",
"=",
"False",
")",
":",
"if",
"not",
"bits",
":",
"return",
"{",
"}",
"match",
"=",
"kwarg_re",
".",
"match",
"(",
"bits",
"[",
"0",
"]",
")",
"kwarg_format",
"=",
"match",
"an... | [
1000,
0
] | [
1044,
17
] | python | en | ['en', 'error', 'th'] | False |
Template.render | (self, context) | Display stage -- can be called many times | Display stage -- can be called many times | def render(self, context):
"Display stage -- can be called many times"
with context.render_context.push_state(self):
if context.template is None:
with context.bind_template(self):
context.template_name = self.name
return self._render(co... | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"with",
"context",
".",
"render_context",
".",
"push_state",
"(",
"self",
")",
":",
"if",
"context",
".",
"template",
"is",
"None",
":",
"with",
"context",
".",
"bind_template",
"(",
"self",
")",
... | [
163,
4
] | [
171,
44
] | python | en | ['en', 'en', 'en'] | True |
Template.compile_nodelist | (self) |
Parse and compile the template source into a nodelist. If debug
is True and an exception occurs during parsing, the exception is
annotated with contextual line information where it occurred in the
template source.
|
Parse and compile the template source into a nodelist. If debug
is True and an exception occurs during parsing, the exception is
annotated with contextual line information where it occurred in the
template source.
| def compile_nodelist(self):
"""
Parse and compile the template source into a nodelist. If debug
is True and an exception occurs during parsing, the exception is
annotated with contextual line information where it occurred in the
template source.
"""
if self.engine... | [
"def",
"compile_nodelist",
"(",
"self",
")",
":",
"if",
"self",
".",
"engine",
".",
"debug",
":",
"lexer",
"=",
"DebugLexer",
"(",
"self",
".",
"source",
")",
"else",
":",
"lexer",
"=",
"Lexer",
"(",
"self",
".",
"source",
")",
"tokens",
"=",
"lexer"... | [
173,
4
] | [
196,
17
] | python | en | ['en', 'error', 'th'] | False |
Template.get_exception_info | (self, exception, token) |
Return a dictionary containing contextual line information of where
the exception occurred in the template. The following information is
provided:
message
The message of the exception raised.
source_lines
The lines before, after, and including the line ... |
Return a dictionary containing contextual line information of where
the exception occurred in the template. The following information is
provided: | def get_exception_info(self, exception, token):
"""
Return a dictionary containing contextual line information of where
the exception occurred in the template. The following information is
provided:
message
The message of the exception raised.
source_lines
... | [
"def",
"get_exception_info",
"(",
"self",
",",
"exception",
",",
"token",
")",
":",
"start",
",",
"end",
"=",
"token",
".",
"position",
"context_lines",
"=",
"10",
"line",
"=",
"0",
"upto",
"=",
"0",
"source_lines",
"=",
"[",
"]",
"before",
"=",
"durin... | [
198,
4
] | [
274,
9
] | python | en | ['en', 'error', 'th'] | False |
Token.__init__ | (self, token_type, contents, position=None, lineno=None) |
A token representing a string from the template.
token_type
A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT.
contents
The token source string.
position
An optional tuple containing the start and end index of the token
in the templa... |
A token representing a string from the template. | def __init__(self, token_type, contents, position=None, lineno=None):
"""
A token representing a string from the template.
token_type
A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT.
contents
The token source string.
position
An optiona... | [
"def",
"__init__",
"(",
"self",
",",
"token_type",
",",
"contents",
",",
"position",
"=",
"None",
",",
"lineno",
"=",
"None",
")",
":",
"self",
".",
"token_type",
",",
"self",
".",
"contents",
"=",
"token_type",
",",
"contents",
"self",
".",
"lineno",
... | [
287,
4
] | [
308,
32
] | python | en | ['en', 'error', 'th'] | False |
Lexer.tokenize | (self) |
Return a list of tokens from a given template_string.
|
Return a list of tokens from a given template_string.
| def tokenize(self):
"""
Return a list of tokens from a given template_string.
"""
in_tag = False
lineno = 1
result = []
for bit in tag_re.split(self.template_string):
if bit:
result.append(self.create_token(bit, None, lineno, in_tag))
... | [
"def",
"tokenize",
"(",
"self",
")",
":",
"in_tag",
"=",
"False",
"lineno",
"=",
"1",
"result",
"=",
"[",
"]",
"for",
"bit",
"in",
"tag_re",
".",
"split",
"(",
"self",
".",
"template_string",
")",
":",
"if",
"bit",
":",
"result",
".",
"append",
"("... | [
336,
4
] | [
348,
21
] | python | en | ['en', 'error', 'th'] | False |
Lexer.create_token | (self, token_string, position, lineno, in_tag) |
Convert the given token string into a new Token object and return it.
If in_tag is True, we are processing something that matched a tag,
otherwise it should be treated as a literal string.
|
Convert the given token string into a new Token object and return it.
If in_tag is True, we are processing something that matched a tag,
otherwise it should be treated as a literal string.
| def create_token(self, token_string, position, lineno, in_tag):
"""
Convert the given token string into a new Token object and return it.
If in_tag is True, we are processing something that matched a tag,
otherwise it should be treated as a literal string.
"""
if in_tag a... | [
"def",
"create_token",
"(",
"self",
",",
"token_string",
",",
"position",
",",
"lineno",
",",
"in_tag",
")",
":",
"if",
"in_tag",
"and",
"token_string",
".",
"startswith",
"(",
"BLOCK_TAG_START",
")",
":",
"# The [2:-2] ranges below strip off *_TAG_START and *_TAG_END... | [
350,
4
] | [
377,
72
] | python | en | ['en', 'error', 'th'] | False |
DebugLexer.tokenize | (self) |
Split a template string into tokens and annotates each token with its
start and end position in the source. This is slower than the default
lexer so only use it when debug is True.
|
Split a template string into tokens and annotates each token with its
start and end position in the source. This is slower than the default
lexer so only use it when debug is True.
| def tokenize(self):
"""
Split a template string into tokens and annotates each token with its
start and end position in the source. This is slower than the default
lexer so only use it when debug is True.
"""
lineno = 1
result = []
upto = 0
for mat... | [
"def",
"tokenize",
"(",
"self",
")",
":",
"lineno",
"=",
"1",
"result",
"=",
"[",
"]",
"upto",
"=",
"0",
"for",
"match",
"in",
"tag_re",
".",
"finditer",
"(",
"self",
".",
"template_string",
")",
":",
"start",
",",
"end",
"=",
"match",
".",
"span",... | [
381,
4
] | [
403,
21
] | python | en | ['en', 'error', 'th'] | False |
Parser.parse | (self, parse_until=None) |
Iterate through the parser tokens and compiles each one into a node.
If parse_until is provided, parsing will stop once one of the
specified tokens has been reached. This is formatted as a list of
tokens, e.g. ['elif', 'else', 'endif']. If no matching token is
reached, raise an... |
Iterate through the parser tokens and compiles each one into a node. | def parse(self, parse_until=None):
"""
Iterate through the parser tokens and compiles each one into a node.
If parse_until is provided, parsing will stop once one of the
specified tokens has been reached. This is formatted as a list of
tokens, e.g. ['elif', 'else', 'endif']. If ... | [
"def",
"parse",
"(",
"self",
",",
"parse_until",
"=",
"None",
")",
":",
"if",
"parse_until",
"is",
"None",
":",
"parse_until",
"=",
"[",
"]",
"nodelist",
"=",
"NodeList",
"(",
")",
"while",
"self",
".",
"tokens",
":",
"token",
"=",
"self",
".",
"next... | [
425,
4
] | [
483,
23
] | python | en | ['en', 'error', 'th'] | False |
Parser.error | (self, token, e) |
Return an exception annotated with the originating token. Since the
parser can be called recursively, check if a token is already set. This
ensures the innermost token is highlighted if an exception occurs,
e.g. a compile error within the body of an if statement.
|
Return an exception annotated with the originating token. Since the
parser can be called recursively, check if a token is already set. This
ensures the innermost token is highlighted if an exception occurs,
e.g. a compile error within the body of an if statement.
| def error(self, token, e):
"""
Return an exception annotated with the originating token. Since the
parser can be called recursively, check if a token is already set. This
ensures the innermost token is highlighted if an exception occurs,
e.g. a compile error within the body of an... | [
"def",
"error",
"(",
"self",
",",
"token",
",",
"e",
")",
":",
"if",
"not",
"isinstance",
"(",
"e",
",",
"Exception",
")",
":",
"e",
"=",
"TemplateSyntaxError",
"(",
"e",
")",
"if",
"not",
"hasattr",
"(",
"e",
",",
"'token'",
")",
":",
"e",
".",
... | [
506,
4
] | [
517,
16
] | python | en | ['en', 'error', 'th'] | False |
Parser.compile_filter | (self, token) |
Convenient wrapper for FilterExpression
|
Convenient wrapper for FilterExpression
| def compile_filter(self, token):
"""
Convenient wrapper for FilterExpression
"""
return FilterExpression(token, self) | [
"def",
"compile_filter",
"(",
"self",
",",
"token",
")",
":",
"return",
"FilterExpression",
"(",
"token",
",",
"self",
")"
] | [
558,
4
] | [
562,
44
] | python | en | ['en', 'error', 'th'] | False |
Variable.resolve | (self, context) | Resolve this variable against a given context. | Resolve this variable against a given context. | def resolve(self, context):
"""Resolve this variable against a given context."""
if self.lookups is not None:
# We're dealing with a variable that needs to be resolved
value = self._resolve_lookup(context)
else:
# We're dealing with a literal, so it's already ... | [
"def",
"resolve",
"(",
"self",
",",
"context",
")",
":",
"if",
"self",
".",
"lookups",
"is",
"not",
"None",
":",
"# We're dealing with a variable that needs to be resolved",
"value",
"=",
"self",
".",
"_resolve_lookup",
"(",
"context",
")",
"else",
":",
"# We're... | [
791,
4
] | [
807,
20
] | python | en | ['en', 'en', 'en'] | True |
Variable._resolve_lookup | (self, context) |
Perform resolution of a real variable (i.e. not a literal) against the
given context.
As indicated by the method's name, this method is an implementation
detail and shouldn't be called by external code. Use Variable.resolve()
instead.
|
Perform resolution of a real variable (i.e. not a literal) against the
given context. | def _resolve_lookup(self, context):
"""
Perform resolution of a real variable (i.e. not a literal) against the
given context.
As indicated by the method's name, this method is an implementation
detail and shouldn't be called by external code. Use Variable.resolve()
inste... | [
"def",
"_resolve_lookup",
"(",
"self",
",",
"context",
")",
":",
"current",
"=",
"context",
"try",
":",
"# catch-all for silent variable failures",
"for",
"bit",
"in",
"self",
".",
"lookups",
":",
"try",
":",
"# dictionary lookup",
"current",
"=",
"current",
"["... | [
815,
4
] | [
880,
22
] | python | en | ['en', 'error', 'th'] | False |
Node.render | (self, context) |
Return the node rendered as a string.
|
Return the node rendered as a string.
| def render(self, context):
"""
Return the node rendered as a string.
"""
pass | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"pass"
] | [
890,
4
] | [
894,
12
] | python | en | ['en', 'error', 'th'] | False |
Node.render_annotated | (self, context) |
Render the node. If debug is True and an exception occurs during
rendering, the exception is annotated with contextual line information
where it occurred in the template. For internal usage this method is
preferred over using the render method directly.
|
Render the node. If debug is True and an exception occurs during
rendering, the exception is annotated with contextual line information
where it occurred in the template. For internal usage this method is
preferred over using the render method directly.
| def render_annotated(self, context):
"""
Render the node. If debug is True and an exception occurs during
rendering, the exception is annotated with contextual line information
where it occurred in the template. For internal usage this method is
preferred over using the render me... | [
"def",
"render_annotated",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"return",
"self",
".",
"render",
"(",
"context",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"context",
".",
"template",
".",
"engine",
".",
"debug",
"and",
"not",
"has... | [
896,
4
] | [
908,
17
] | python | en | ['en', 'error', 'th'] | False |
Node.get_nodes_by_type | (self, nodetype) |
Return a list of all nodes (within this node and its nodelist)
of the given type
|
Return a list of all nodes (within this node and its nodelist)
of the given type
| def get_nodes_by_type(self, nodetype):
"""
Return a list of all nodes (within this node and its nodelist)
of the given type
"""
nodes = []
if isinstance(self, nodetype):
nodes.append(self)
for attr in self.child_nodelists:
nodelist = getatt... | [
"def",
"get_nodes_by_type",
"(",
"self",
",",
"nodetype",
")",
":",
"nodes",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
",",
"nodetype",
")",
":",
"nodes",
".",
"append",
"(",
"self",
")",
"for",
"attr",
"in",
"self",
".",
"child_nodelists",
":",
... | [
913,
4
] | [
925,
20
] | python | en | ['en', 'error', 'th'] | False |
NodeList.get_nodes_by_type | (self, nodetype) | Return a list of all nodes of the given type | Return a list of all nodes of the given type | def get_nodes_by_type(self, nodetype):
"Return a list of all nodes of the given type"
nodes = []
for node in self:
nodes.extend(node.get_nodes_by_type(nodetype))
return nodes | [
"def",
"get_nodes_by_type",
"(",
"self",
",",
"nodetype",
")",
":",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
":",
"nodes",
".",
"extend",
"(",
"node",
".",
"get_nodes_by_type",
"(",
"nodetype",
")",
")",
"return",
"nodes"
] | [
943,
4
] | [
948,
20
] | python | en | ['en', 'en', 'en'] | True |
reshape_into_image | (features, params) | reshape features dict containing ref, ltg channels into image.
Args:
features (dict): Looks for ref, ltg entries in dict
params (dict): command-line parameters
Returns:
reshaped tensor with shape [2*train_patch_radius, 2*train_patch_radius, 2]
| reshape features dict containing ref, ltg channels into image. | def reshape_into_image(features, params):
"""reshape features dict containing ref, ltg channels into image.
Args:
features (dict): Looks for ref, ltg entries in dict
params (dict): command-line parameters
Returns:
reshaped tensor with shape [2*train_patch_radius, 2*train_patch_radius, 2]
"""
# s... | [
"def",
"reshape_into_image",
"(",
"features",
",",
"params",
")",
":",
"# stack the inputs to form a 2-channel input",
"# features['ref'] is [-1, height*width]",
"# stacked image is [-1, height*width, n_channels]",
"n_channels",
"=",
"2",
"print",
"(",
"'shape of ref feature {}'",
... | [
29,
0
] | [
48,
57
] | python | en | ['en', 'en', 'en'] | True |
make_preprocess_fn | (params) | Make preprocessing function.
Args:
params (dict): command-line parameters
Returns:
function that takes tfexample and returns img, label
| Make preprocessing function. | def make_preprocess_fn(params):
"""Make preprocessing function.
Args:
params (dict): command-line parameters
Returns:
function that takes tfexample and returns img, label
"""
def _sparse_to_dense(data, arrlen):
return tf.expand_dims(
tf.reshape(tf.sparse_tensor_to_dense(data, default_val... | [
"def",
"make_preprocess_fn",
"(",
"params",
")",
":",
"def",
"_sparse_to_dense",
"(",
"data",
",",
"arrlen",
")",
":",
"return",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"reshape",
"(",
"tf",
".",
"sparse_tensor_to_dense",
"(",
"data",
",",
"default_value",... | [
51,
0
] | [
92,
28
] | python | en | ['en', 'jv', 'en'] | True |
make_dataset | (pattern, mode, batch_size, params) | Make training/evaluation dataset.
Args:
pattern (str): filename pattern
mode (int): TRAIN/EVAL/PREDICT
default_batch_size (int): batch_size
params (dict): transpose, num_cores
Returns:
tf.data dataset
| Make training/evaluation dataset. | def make_dataset(pattern, mode, batch_size, params):
"""Make training/evaluation dataset.
Args:
pattern (str): filename pattern
mode (int): TRAIN/EVAL/PREDICT
default_batch_size (int): batch_size
params (dict): transpose, num_cores
Returns:
tf.data dataset
"""
def _set_shapes(batch_size,... | [
"def",
"make_dataset",
"(",
"pattern",
",",
"mode",
",",
"batch_size",
",",
"params",
")",
":",
"def",
"_set_shapes",
"(",
"batch_size",
",",
"images",
",",
"labels",
")",
":",
"\"\"\"Statically set the batch_size dimension.\"\"\"",
"if",
"params",
"[",
"'transpos... | [
160,
0
] | [
225,
16
] | python | en | ['fr', 'zu', 'en'] | False |
train_and_evaluate | (hparams) | Main train and evaluate loop.
Args:
hparams (dict): Command-line parameters passed in
| Main train and evaluate loop. | def train_and_evaluate(hparams):
"""Main train and evaluate loop.
Args:
hparams (dict): Command-line parameters passed in
"""
output_dir = hparams['job_dir']
max_steps = hparams['train_steps']
# avoid overly frequent evaluation
steps_per_epoch = min(1000, max_steps//10)
num_epochs = max_steps // s... | [
"def",
"train_and_evaluate",
"(",
"hparams",
")",
":",
"output_dir",
"=",
"hparams",
"[",
"'job_dir'",
"]",
"max_steps",
"=",
"hparams",
"[",
"'train_steps'",
"]",
"# avoid overly frequent evaluation",
"steps_per_epoch",
"=",
"min",
"(",
"1000",
",",
"max_steps",
... | [
228,
0
] | [
312,
57
] | python | en | ['en', 'id', 'en'] | True |
normalize | (pattern) | r"""
Given a reg-exp pattern, normalize it to an iterable of forms that
suffice for reverse matching. This does the following:
(1) For any repeating sections, keeps the minimum number of occurrences
permitted (this means zero for optional groups).
(2) If an optional group includes parameters, i... | r"""
Given a reg-exp pattern, normalize it to an iterable of forms that
suffice for reverse matching. This does the following: | def normalize(pattern):
r"""
Given a reg-exp pattern, normalize it to an iterable of forms that
suffice for reverse matching. This does the following:
(1) For any repeating sections, keeps the minimum number of occurrences
permitted (this means zero for optional groups).
(2) If an optional ... | [
"def",
"normalize",
"(",
"pattern",
")",
":",
"# Do a linear scan to work out the special features of this pattern. The",
"# idea is that we scan once here and collect all the information we need to",
"# make future decisions.",
"result",
"=",
"[",
"]",
"non_capturing_groups",
"=",
"["... | [
40,
0
] | [
189,
45
] | python | cy | ['en', 'cy', 'hi'] | False |
next_char | (input_iter) | r"""
An iterator that yields the next character from "pattern_iter", respecting
escape sequences. An escaped character is replaced by a representative of
its class (e.g. \w -> "x"). If the escaped character is one that is
skipped, it is not returned (the next character is returned instead).
Yield t... | r"""
An iterator that yields the next character from "pattern_iter", respecting
escape sequences. An escaped character is replaced by a representative of
its class (e.g. \w -> "x"). If the escaped character is one that is
skipped, it is not returned (the next character is returned instead). | def next_char(input_iter):
r"""
An iterator that yields the next character from "pattern_iter", respecting
escape sequences. An escaped character is replaced by a representative of
its class (e.g. \w -> "x"). If the escaped character is one that is
skipped, it is not returned (the next character is ... | [
"def",
"next_char",
"(",
"input_iter",
")",
":",
"for",
"ch",
"in",
"input_iter",
":",
"if",
"ch",
"!=",
"'\\\\'",
":",
"yield",
"ch",
",",
"False",
"continue",
"ch",
"=",
"next",
"(",
"input_iter",
")",
"representative",
"=",
"ESCAPE_MAPPINGS",
".",
"ge... | [
192,
0
] | [
210,
34
] | python | cy | ['en', 'cy', 'hi'] | False |
walk_to_end | (ch, input_iter) |
The iterator is currently inside a capturing group. Walk to the close of
this group, skipping over any nested groups and handling escaped
parentheses correctly.
|
The iterator is currently inside a capturing group. Walk to the close of
this group, skipping over any nested groups and handling escaped
parentheses correctly.
| def walk_to_end(ch, input_iter):
"""
The iterator is currently inside a capturing group. Walk to the close of
this group, skipping over any nested groups and handling escaped
parentheses correctly.
"""
if ch == '(':
nesting = 1
else:
nesting = 0
for ch, escaped in input_i... | [
"def",
"walk_to_end",
"(",
"ch",
",",
"input_iter",
")",
":",
"if",
"ch",
"==",
"'('",
":",
"nesting",
"=",
"1",
"else",
":",
"nesting",
"=",
"0",
"for",
"ch",
",",
"escaped",
"in",
"input_iter",
":",
"if",
"escaped",
":",
"continue",
"elif",
"ch",
... | [
213,
0
] | [
231,
24
] | python | en | ['en', 'error', 'th'] | False |
get_quantifier | (ch, input_iter) |
Parse a quantifier from the input, where "ch" is the first character in the
quantifier.
Return the minimum number of occurrences permitted by the quantifier and
either None or the next character from the input_iter if the next character
is not part of the quantifier.
|
Parse a quantifier from the input, where "ch" is the first character in the
quantifier. | def get_quantifier(ch, input_iter):
"""
Parse a quantifier from the input, where "ch" is the first character in the
quantifier.
Return the minimum number of occurrences permitted by the quantifier and
either None or the next character from the input_iter if the next character
is not part of the... | [
"def",
"get_quantifier",
"(",
"ch",
",",
"input_iter",
")",
":",
"if",
"ch",
"in",
"'*?+'",
":",
"try",
":",
"ch2",
",",
"escaped",
"=",
"next",
"(",
"input_iter",
")",
"except",
"StopIteration",
":",
"ch2",
"=",
"None",
"if",
"ch2",
"==",
"'?'",
":"... | [
234,
0
] | [
268,
29
] | python | en | ['en', 'error', 'th'] | False |
contains | (source, inst) |
Return True if the "source" contains an instance of "inst". False,
otherwise.
|
Return True if the "source" contains an instance of "inst". False,
otherwise.
| def contains(source, inst):
"""
Return True if the "source" contains an instance of "inst". False,
otherwise.
"""
if isinstance(source, inst):
return True
if isinstance(source, NonCapture):
for elt in source:
if contains(elt, inst):
return True
ret... | [
"def",
"contains",
"(",
"source",
",",
"inst",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"inst",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"source",
",",
"NonCapture",
")",
":",
"for",
"elt",
"in",
"source",
":",
"if",
"contains",
... | [
271,
0
] | [
282,
16
] | python | en | ['en', 'error', 'th'] | False |
flatten_result | (source) |
Turn the given source sequence into a list of reg-exp possibilities and
their arguments. Return a list of strings and a list of argument lists.
Each of the two lists will be of the same length.
|
Turn the given source sequence into a list of reg-exp possibilities and
their arguments. Return a list of strings and a list of argument lists.
Each of the two lists will be of the same length.
| def flatten_result(source):
"""
Turn the given source sequence into a list of reg-exp possibilities and
their arguments. Return a list of strings and a list of argument lists.
Each of the two lists will be of the same length.
"""
if source is None:
return [''], [[]]
if isinstance(sou... | [
"def",
"flatten_result",
"(",
"source",
")",
":",
"if",
"source",
"is",
"None",
":",
"return",
"[",
"''",
"]",
",",
"[",
"[",
"]",
"]",
"if",
"isinstance",
"(",
"source",
",",
"Group",
")",
":",
"if",
"source",
"[",
"1",
"]",
"is",
"None",
":",
... | [
285,
0
] | [
336,
30
] | python | en | ['en', 'error', 'th'] | False |
_lazy_re_compile | (regex, flags=0) | Lazily compile a regex with flags. | Lazily compile a regex with flags. | def _lazy_re_compile(regex, flags=0):
"""Lazily compile a regex with flags."""
def _compile():
# Compile the regex if it was not passed pre-compiled.
if isinstance(regex, (str, bytes)):
return re.compile(regex, flags)
else:
assert not flags, (
'fla... | [
"def",
"_lazy_re_compile",
"(",
"regex",
",",
"flags",
"=",
"0",
")",
":",
"def",
"_compile",
"(",
")",
":",
"# Compile the regex if it was not passed pre-compiled.",
"if",
"isinstance",
"(",
"regex",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"return",
"... | [
339,
0
] | [
350,
37
] | python | en | ['en', 'en', 'en'] | True |
BaseRatingPrediction.__init__ | (self, train_file, test_file, output_file=None, similarity_metric='cosine', sep='\t',
output_sep='\t') |
This class is base for all rating prediction algorithms. Inherits the class Recommender
and implements / adds common methods and attributes for rating prediction approaches.
:param train_file: File which contains the train set. This file needs to have at least 3 columns
(user item fe... |
This class is base for all rating prediction algorithms. Inherits the class Recommender
and implements / adds common methods and attributes for rating prediction approaches. | def __init__(self, train_file, test_file, output_file=None, similarity_metric='cosine', sep='\t',
output_sep='\t'):
"""
This class is base for all rating prediction algorithms. Inherits the class Recommender
and implements / adds common methods and attributes for rating predic... | [
"def",
"__init__",
"(",
"self",
",",
"train_file",
",",
"test_file",
",",
"output_file",
"=",
"None",
",",
"similarity_metric",
"=",
"'cosine'",
",",
"sep",
"=",
"'\\t'",
",",
"output_sep",
"=",
"'\\t'",
")",
":",
"self",
".",
"train_file",
"=",
"train_fil... | [
20,
4
] | [
68,
29
] | python | en | ['en', 'error', 'th'] | False |
BaseRatingPrediction.read_files | (self) |
Method to initialize recommender algorithm.
|
Method to initialize recommender algorithm. | def read_files(self):
"""
Method to initialize recommender algorithm.
"""
self.train_set = ReadFile(self.train_file, sep=self.sep).read()
if self.test_file is not None:
self.test_set = ReadFile(self.test_file).read()
self.users = sorted(set(list(self.tr... | [
"def",
"read_files",
"(",
"self",
")",
":",
"self",
".",
"train_set",
"=",
"ReadFile",
"(",
"self",
".",
"train_file",
",",
"sep",
"=",
"self",
".",
"sep",
")",
".",
"read",
"(",
")",
"if",
"self",
".",
"test_file",
"is",
"not",
"None",
":",
"self"... | [
70,
4
] | [
91,
50
] | python | en | ['en', 'error', 'th'] | False |
BaseRatingPrediction.create_matrix | (self) |
Method to create a feedback matrix
|
Method to create a feedback matrix | def create_matrix(self):
"""
Method to create a feedback matrix
"""
self.matrix = np.zeros((len(self.users), len(self.items)))
for user in self.train_set['users']:
for item in self.train_set['feedback'][user]:
self.matrix[self.user_to_user_id[user]]... | [
"def",
"create_matrix",
"(",
"self",
")",
":",
"self",
".",
"matrix",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"self",
".",
"users",
")",
",",
"len",
"(",
"self",
".",
"items",
")",
")",
")",
"for",
"user",
"in",
"self",
".",
"train_set",
... | [
93,
4
] | [
104,
58
] | python | en | ['en', 'error', 'th'] | False |
BaseRatingPrediction.compute_similarity | (self, transpose=False) |
Method to compute a similarity matrix from original df_matrix
:param transpose: If True, calculate the similarity in a transpose matrix
:type transpose: bool, default False
|
Method to compute a similarity matrix from original df_matrix | def compute_similarity(self, transpose=False):
"""
Method to compute a similarity matrix from original df_matrix
:param transpose: If True, calculate the similarity in a transpose matrix
:type transpose: bool, default False
"""
# Calculate distance matrix
if tr... | [
"def",
"compute_similarity",
"(",
"self",
",",
"transpose",
"=",
"False",
")",
":",
"# Calculate distance matrix",
"if",
"transpose",
":",
"similarity_matrix",
"=",
"np",
".",
"float32",
"(",
"squareform",
"(",
"pdist",
"(",
"self",
".",
"matrix",
".",
"T",
... | [
106,
4
] | [
126,
32
] | python | en | ['en', 'error', 'th'] | False |
BaseRatingPrediction.evaluate | (self, metrics, verbose=True, as_table=False, table_sep='\t') |
Method to evaluate the final ranking
:param metrics: List of evaluation metrics
:type metrics: list, default ('MAE', 'RMSE')
:param verbose: Print the evaluation results
:type verbose: bool, default True
:param as_table: Print the evaluation results as table
:... |
Method to evaluate the final ranking | def evaluate(self, metrics, verbose=True, as_table=False, table_sep='\t'):
"""
Method to evaluate the final ranking
:param metrics: List of evaluation metrics
:type metrics: list, default ('MAE', 'RMSE')
:param verbose: Print the evaluation results
:type verbose: bool, ... | [
"def",
"evaluate",
"(",
"self",
",",
"metrics",
",",
"verbose",
"=",
"True",
",",
"as_table",
"=",
"False",
",",
"table_sep",
"=",
"'\\t'",
")",
":",
"self",
".",
"evaluation_results",
"=",
"{",
"}",
"if",
"metrics",
"is",
"None",
":",
"metrics",
"=",
... | [
128,
4
] | [
156,
77
] | python | en | ['en', 'error', 'th'] | False |
BaseRatingPrediction.write_predictions | (self) |
Method to write final ranking
|
Method to write final ranking | def write_predictions(self):
"""
Method to write final ranking
"""
if self.output_file is not None:
WriteFile(self.output_file, data=self.predictions, sep=self.sep).write() | [
"def",
"write_predictions",
"(",
"self",
")",
":",
"if",
"self",
".",
"output_file",
"is",
"not",
"None",
":",
"WriteFile",
"(",
"self",
".",
"output_file",
",",
"data",
"=",
"self",
".",
"predictions",
",",
"sep",
"=",
"self",
".",
"sep",
")",
".",
... | [
158,
4
] | [
165,
84
] | python | en | ['en', 'error', 'th'] | False |
BaseRatingPrediction.compute | (self, verbose=True) |
Method to run the recommender algorithm
:param verbose: Print the information about recommender
:type verbose: bool, default True
|
Method to run the recommender algorithm | def compute(self, verbose=True):
"""
Method to run the recommender algorithm
:param verbose: Print the information about recommender
:type verbose: bool, default True
"""
# read files
self.read_files()
# initialize empty predictions (Don't remove: impo... | [
"def",
"compute",
"(",
"self",
",",
"verbose",
"=",
"True",
")",
":",
"# read files",
"self",
".",
"read_files",
"(",
")",
"# initialize empty predictions (Don't remove: important to Cross Validation)",
"self",
".",
"predictions",
"=",
"[",
"]",
"if",
"verbose",
":"... | [
167,
4
] | [
201,
46
] | python | en | ['en', 'error', 'th'] | False |
is_password_usable | (encoded) |
Return True if this password wasn't generated by
User.set_unusable_password(), i.e. make_password(None).
|
Return True if this password wasn't generated by
User.set_unusable_password(), i.e. make_password(None).
| def is_password_usable(encoded):
"""
Return True if this password wasn't generated by
User.set_unusable_password(), i.e. make_password(None).
"""
return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX) | [
"def",
"is_password_usable",
"(",
"encoded",
")",
":",
"return",
"encoded",
"is",
"None",
"or",
"not",
"encoded",
".",
"startswith",
"(",
"UNUSABLE_PASSWORD_PREFIX",
")"
] | [
22,
0
] | [
27,
78
] | python | en | ['en', 'error', 'th'] | False |
check_password | (password, encoded, setter=None, preferred='default') |
Return a boolean of whether the raw password matches the three
part encoded digest.
If setter is specified, it'll be called when you need to
regenerate the password.
|
Return a boolean of whether the raw password matches the three
part encoded digest. | def check_password(password, encoded, setter=None, preferred='default'):
"""
Return a boolean of whether the raw password matches the three
part encoded digest.
If setter is specified, it'll be called when you need to
regenerate the password.
"""
if password is None or not is_password_usabl... | [
"def",
"check_password",
"(",
"password",
",",
"encoded",
",",
"setter",
"=",
"None",
",",
"preferred",
"=",
"'default'",
")",
":",
"if",
"password",
"is",
"None",
"or",
"not",
"is_password_usable",
"(",
"encoded",
")",
":",
"return",
"False",
"preferred",
... | [
30,
0
] | [
61,
21
] | python | en | ['en', 'error', 'th'] | False |
make_password | (password, salt=None, hasher='default') |
Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Additional random string reduces chances of gaining
access to staff ... |
Turn a plain-text password into a hash for database storage | def make_password(password, salt=None, hasher='default'):
"""
Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Additio... | [
"def",
"make_password",
"(",
"password",
",",
"salt",
"=",
"None",
",",
"hasher",
"=",
"'default'",
")",
":",
"if",
"password",
"is",
"None",
":",
"return",
"UNUSABLE_PASSWORD_PREFIX",
"+",
"get_random_string",
"(",
"UNUSABLE_PASSWORD_SUFFIX_LENGTH",
")",
"if",
... | [
64,
0
] | [
82,
40
] | python | en | ['en', 'error', 'th'] | False |
get_hasher | (algorithm='default') |
Return an instance of a loaded password hasher.
If algorithm is 'default', return the default hasher. Lazily import hashers
specified in the project's settings file if needed.
|
Return an instance of a loaded password hasher. | def get_hasher(algorithm='default'):
"""
Return an instance of a loaded password hasher.
If algorithm is 'default', return the default hasher. Lazily import hashers
specified in the project's settings file if needed.
"""
if hasattr(algorithm, 'algorithm'):
return algorithm
elif alg... | [
"def",
"get_hasher",
"(",
"algorithm",
"=",
"'default'",
")",
":",
"if",
"hasattr",
"(",
"algorithm",
",",
"'algorithm'",
")",
":",
"return",
"algorithm",
"elif",
"algorithm",
"==",
"'default'",
":",
"return",
"get_hashers",
"(",
")",
"[",
"0",
"]",
"else"... | [
110,
0
] | [
130,
52
] | python | en | ['en', 'error', 'th'] | False |
identify_hasher | (encoded) |
Return an instance of a loaded password hasher.
Identify hasher algorithm by examining encoded hash, and call
get_hasher() to return hasher. Raise ValueError if
algorithm cannot be identified, or if hasher is not loaded.
|
Return an instance of a loaded password hasher. | def identify_hasher(encoded):
"""
Return an instance of a loaded password hasher.
Identify hasher algorithm by examining encoded hash, and call
get_hasher() to return hasher. Raise ValueError if
algorithm cannot be identified, or if hasher is not loaded.
"""
# Ancient versions of Django cre... | [
"def",
"identify_hasher",
"(",
"encoded",
")",
":",
"# Ancient versions of Django created plain MD5 passwords and accepted",
"# MD5 passwords with an empty salt.",
"if",
"(",
"(",
"len",
"(",
"encoded",
")",
"==",
"32",
"and",
"'$'",
"not",
"in",
"encoded",
")",
"or",
... | [
133,
0
] | [
151,
32
] | python | en | ['en', 'error', 'th'] | False |
mask_hash | (hash, show=6, char="*") |
Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons.
|
Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons.
| def mask_hash(hash, show=6, char="*"):
"""
Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons.
"""
masked = hash[:show]
masked += char * len(hash[show:])
return masked | [
"def",
"mask_hash",
"(",
"hash",
",",
"show",
"=",
"6",
",",
"char",
"=",
"\"*\"",
")",
":",
"masked",
"=",
"hash",
"[",
":",
"show",
"]",
"masked",
"+=",
"char",
"*",
"len",
"(",
"hash",
"[",
"show",
":",
"]",
")",
"return",
"masked"
] | [
154,
0
] | [
161,
17
] | python | en | ['en', 'error', 'th'] | False |
BasePasswordHasher.salt | (self) |
Generate a cryptographically secure nonce salt in ASCII with an entropy
of at least `salt_entropy` bits.
|
Generate a cryptographically secure nonce salt in ASCII with an entropy
of at least `salt_entropy` bits.
| def salt(self):
"""
Generate a cryptographically secure nonce salt in ASCII with an entropy
of at least `salt_entropy` bits.
"""
# Each character in the salt provides
# log_2(len(alphabet)) bits of entropy.
char_count = math.ceil(self.salt_entropy / math.log2(len(... | [
"def",
"salt",
"(",
"self",
")",
":",
"# Each character in the salt provides",
"# log_2(len(alphabet)) bits of entropy.",
"char_count",
"=",
"math",
".",
"ceil",
"(",
"self",
".",
"salt_entropy",
"/",
"math",
".",
"log2",
"(",
"len",
"(",
"RANDOM_STRING_CHARS",
")",... | [
197,
4
] | [
205,
79
] | python | en | ['en', 'error', 'th'] | False |
BasePasswordHasher.verify | (self, password, encoded) | Check if the given password is correct. | Check if the given password is correct. | def verify(self, password, encoded):
"""Check if the given password is correct."""
raise NotImplementedError('subclasses of BasePasswordHasher must provide a verify() method') | [
"def",
"verify",
"(",
"self",
",",
"password",
",",
"encoded",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BasePasswordHasher must provide a verify() method'",
")"
] | [
207,
4
] | [
209,
100
] | python | en | ['en', 'en', 'en'] | True |
BasePasswordHasher.encode | (self, password, salt) |
Create an encoded database value.
The result is normally formatted as "algorithm$salt$hash" and
must be fewer than 128 characters.
|
Create an encoded database value. | def encode(self, password, salt):
"""
Create an encoded database value.
The result is normally formatted as "algorithm$salt$hash" and
must be fewer than 128 characters.
"""
raise NotImplementedError('subclasses of BasePasswordHasher must provide an encode() method') | [
"def",
"encode",
"(",
"self",
",",
"password",
",",
"salt",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BasePasswordHasher must provide an encode() method'",
")"
] | [
211,
4
] | [
218,
101
] | python | en | ['en', 'error', 'th'] | False |
BasePasswordHasher.decode | (self, encoded) |
Return a decoded database value.
The result is a dictionary and should contain `algorithm`, `hash`, and
`salt`. Extra keys can be algorithm specific like `iterations` or
`work_factor`.
|
Return a decoded database value. | def decode(self, encoded):
"""
Return a decoded database value.
The result is a dictionary and should contain `algorithm`, `hash`, and
`salt`. Extra keys can be algorithm specific like `iterations` or
`work_factor`.
"""
raise NotImplementedError(
'sub... | [
"def",
"decode",
"(",
"self",
",",
"encoded",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BasePasswordHasher must provide a decode() method.'",
")"
] | [
220,
4
] | [
230,
9
] | python | en | ['en', 'error', 'th'] | False |
BasePasswordHasher.safe_summary | (self, encoded) |
Return a summary of safe values.
The result is a dictionary and will be used where the password field
must be displayed to construct a safe representation of the password.
|
Return a summary of safe values. | def safe_summary(self, encoded):
"""
Return a summary of safe values.
The result is a dictionary and will be used where the password field
must be displayed to construct a safe representation of the password.
"""
raise NotImplementedError('subclasses of BasePasswordHashe... | [
"def",
"safe_summary",
"(",
"self",
",",
"encoded",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BasePasswordHasher must provide a safe_summary() method'",
")"
] | [
232,
4
] | [
239,
106
] | python | en | ['en', 'error', 'th'] | False |
BasePasswordHasher.harden_runtime | (self, password, encoded) |
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
`self.iterations` is 30000, this method should run password through
another 10000 iteration... |
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher. | def harden_runtime(self, password, encoded):
"""
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
`self.iterations` is 30000, this method sho... | [
"def",
"harden_runtime",
"(",
"self",
",",
"password",
",",
"encoded",
")",
":",
"warnings",
".",
"warn",
"(",
"'subclasses of BasePasswordHasher should provide a harden_runtime() method'",
")"
] | [
244,
4
] | [
255,
98
] | python | en | ['en', 'error', 'th'] | False |
_suggest_semantic_version | (s) |
Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything.
|
Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything.
| def _suggest_semantic_version(s):
"""
Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything.
"""
result = s.strip().lower()
for pat, repl in _REPLACEMENTS:
result = pat.sub(repl, result)
if not result:
result = '0.0.... | [
"def",
"_suggest_semantic_version",
"(",
"s",
")",
":",
"result",
"=",
"s",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"pat",
",",
"repl",
"in",
"_REPLACEMENTS",
":",
"result",
"=",
"pat",
".",
"sub",
"(",
"repl",
",",
"result",
")",
"i... | [
405,
0
] | [
448,
17
] | python | en | ['en', 'error', 'th'] | False |
_suggest_normalized_version | (s) | Suggest a normalized version close to the given version string.
If you have a version string that isn't rational (i.e. NormalizedVersion
doesn't like it) then you might be able to get an equivalent (or close)
rational version from this function.
This does a number of simple normalizations to the given... | Suggest a normalized version close to the given version string. | def _suggest_normalized_version(s):
"""Suggest a normalized version close to the given version string.
If you have a version string that isn't rational (i.e. NormalizedVersion
doesn't like it) then you might be able to get an equivalent (or close)
rational version from this function.
This does a n... | [
"def",
"_suggest_normalized_version",
"(",
"s",
")",
":",
"try",
":",
"_normalized_key",
"(",
"s",
")",
"return",
"s",
"# already rational",
"except",
"UnsupportedVersionError",
":",
"pass",
"rs",
"=",
"s",
".",
"lower",
"(",
")",
"# part of this could use maketra... | [
451,
0
] | [
559,
13
] | python | en | ['en', 'en', 'en'] | True |
Matcher.match | (self, version) |
Check if the provided version matches the constraints.
:param version: The version to match against this instance.
:type version: String or :class:`Version` instance.
|
Check if the provided version matches the constraints. | def match(self, version):
"""
Check if the provided version matches the constraints.
:param version: The version to match against this instance.
:type version: String or :class:`Version` instance.
"""
if isinstance(version, string_types):
version = self.versi... | [
"def",
"match",
"(",
"self",
",",
"version",
")",
":",
"if",
"isinstance",
"(",
"version",
",",
"string_types",
")",
":",
"version",
"=",
"self",
".",
"version_class",
"(",
"version",
")",
"for",
"operator",
",",
"constraint",
",",
"prefix",
"in",
"self"... | [
128,
4
] | [
147,
19
] | python | en | ['en', 'error', 'th'] | False |
VersionScheme.is_valid_constraint_list | (self, s) |
Used for processing some metadata fields
|
Used for processing some metadata fields
| def is_valid_constraint_list(self, s):
"""
Used for processing some metadata fields
"""
# See issue #140. Be tolerant of a single trailing comma.
if s.endswith(','):
s = s[:-1]
return self.is_valid_matcher('dummy_name (%s)' % s) | [
"def",
"is_valid_constraint_list",
"(",
"self",
",",
"s",
")",
":",
"# See issue #140. Be tolerant of a single trailing comma.",
"if",
"s",
".",
"endswith",
"(",
"','",
")",
":",
"s",
"=",
"s",
"[",
":",
"-",
"1",
"]",
"return",
"self",
".",
"is_valid_matcher"... | [
708,
4
] | [
715,
59
] | python | en | ['en', 'error', 'th'] | False |
partition | (
predicate: Callable[[Any], bool],
iterator: Sequence[Any]
) | A stable, out-of-place partition. | A stable, out-of-place partition. | def partition(
predicate: Callable[[Any], bool],
iterator: Sequence[Any]
) -> Tuple[List[Any], List[Any]]:
"""A stable, out-of-place partition."""
results = ([], [])
for i in iterator:
results[int(predicate(i))].append(i)
# Returns trueList, falseList
return results[1], results[0] | [
"def",
"partition",
"(",
"predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
",",
"iterator",
":",
"Sequence",
"[",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Any",
"]",
",",
"List",
"[",
"Any",
"]",
"]",
":",
"results",... | [
24,
0
] | [
35,
33
] | python | en | ['en', 'en', 'en'] | True |
fix_files | (
in_dir: pathlib.Path,
out_dir: pathlib.Path,
*,
transformer=dashboardCallTransformer(),
) | Duplicate the input dir to the output dir, fixing file method calls.
Preconditions:
* in_dir is a real directory
* out_dir is a real, empty directory
| Duplicate the input dir to the output dir, fixing file method calls. | def fix_files(
in_dir: pathlib.Path,
out_dir: pathlib.Path,
*,
transformer=dashboardCallTransformer(),
):
"""Duplicate the input dir to the output dir, fixing file method calls.
Preconditions:
* in_dir is a real directory
* out_dir is a real, empty directory
"""
pyfile_gen = (
... | [
"def",
"fix_files",
"(",
"in_dir",
":",
"pathlib",
".",
"Path",
",",
"out_dir",
":",
"pathlib",
".",
"Path",
",",
"*",
",",
"transformer",
"=",
"dashboardCallTransformer",
"(",
")",
",",
")",
":",
"pyfile_gen",
"=",
"(",
"pathlib",
".",
"Path",
"(",
"o... | [
90,
0
] | [
122,
33
] | python | en | ['en', 'su', 'en'] | True |
get_major_minor_version | () |
Return the major-minor version of the current Python as a string, e.g.
"3.7" or "3.10".
|
Return the major-minor version of the current Python as a string, e.g.
"3.7" or "3.10".
| def get_major_minor_version() -> str:
"""
Return the major-minor version of the current Python as a string, e.g.
"3.7" or "3.10".
"""
return "{}.{}".format(*sys.version_info) | [
"def",
"get_major_minor_version",
"(",
")",
"->",
"str",
":",
"return",
"\"{}.{}\"",
".",
"format",
"(",
"*",
"sys",
".",
"version_info",
")"
] | [
17,
0
] | [
22,
44
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.__getitem__ | (self, key) |
Return the last data value for this key, or [] if it's an empty list;
raise KeyError if not found.
|
Return the last data value for this key, or [] if it's an empty list;
raise KeyError if not found.
| def __getitem__(self, key):
"""
Return the last data value for this key, or [] if it's an empty list;
raise KeyError if not found.
"""
try:
list_ = super().__getitem__(key)
except KeyError:
raise MultiValueDictKeyError(key)
try:
... | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"list_",
"=",
"super",
"(",
")",
".",
"__getitem__",
"(",
"key",
")",
"except",
"KeyError",
":",
"raise",
"MultiValueDictKeyError",
"(",
"key",
")",
"try",
":",
"return",
"list_",
"["... | [
69,
4
] | [
81,
21
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.get | (self, key, default=None) |
Return the last data value for the passed key. If key doesn't exist
or value is an empty list, return `default`.
|
Return the last data value for the passed key. If key doesn't exist
or value is an empty list, return `default`.
| def get(self, key, default=None):
"""
Return the last data value for the passed key. If key doesn't exist
or value is an empty list, return `default`.
"""
try:
val = self[key]
except KeyError:
return default
if val == []:
return... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"return",
"default",
"if",
"val",
"==",
"[",
"]",
":",
"return",
"default",
"return",
"val"
] | [
109,
4
] | [
120,
18
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict._getlist | (self, key, default=None, force_list=False) |
Return a list of values for the key.
Used internally to manipulate values list. If force_list is True,
return a new copy of values.
|
Return a list of values for the key. | def _getlist(self, key, default=None, force_list=False):
"""
Return a list of values for the key.
Used internally to manipulate values list. If force_list is True,
return a new copy of values.
"""
try:
values = super().__getitem__(key)
except KeyError... | [
"def",
"_getlist",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"force_list",
"=",
"False",
")",
":",
"try",
":",
"values",
"=",
"super",
"(",
")",
".",
"__getitem__",
"(",
"key",
")",
"except",
"KeyError",
":",
"if",
"default",
"is",
... | [
122,
4
] | [
138,
25
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.getlist | (self, key, default=None) |
Return the list of values for the key. If key doesn't exist, return a
default value.
|
Return the list of values for the key. If key doesn't exist, return a
default value.
| def getlist(self, key, default=None):
"""
Return the list of values for the key. If key doesn't exist, return a
default value.
"""
return self._getlist(key, default, force_list=True) | [
"def",
"getlist",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getlist",
"(",
"key",
",",
"default",
",",
"force_list",
"=",
"True",
")"
] | [
140,
4
] | [
145,
59
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.appendlist | (self, key, value) | Append an item to the internal list associated with key. | Append an item to the internal list associated with key. | def appendlist(self, key, value):
"""Append an item to the internal list associated with key."""
self.setlistdefault(key).append(value) | [
"def",
"appendlist",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"setlistdefault",
"(",
"key",
")",
".",
"append",
"(",
"value",
")"
] | [
166,
4
] | [
168,
46
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict.items | (self) |
Yield (key, value) pairs, where value is the last item in the list
associated with the key.
|
Yield (key, value) pairs, where value is the last item in the list
associated with the key.
| def items(self):
"""
Yield (key, value) pairs, where value is the last item in the list
associated with the key.
"""
for key in self:
yield key, self[key] | [
"def",
"items",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"yield",
"key",
",",
"self",
"[",
"key",
"]"
] | [
170,
4
] | [
176,
32
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.lists | (self) | Yield (key, list) pairs. | Yield (key, list) pairs. | def lists(self):
"""Yield (key, list) pairs."""
return iter(super().items()) | [
"def",
"lists",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"super",
"(",
")",
".",
"items",
"(",
")",
")"
] | [
178,
4
] | [
180,
36
] | python | en | ['en', 'hmn', 'en'] | True |
MultiValueDict.values | (self) | Yield the last value on every key list. | Yield the last value on every key list. | def values(self):
"""Yield the last value on every key list."""
for key in self:
yield self[key] | [
"def",
"values",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"yield",
"self",
"[",
"key",
"]"
] | [
182,
4
] | [
185,
27
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict.copy | (self) | Return a shallow copy of this object. | Return a shallow copy of this object. | def copy(self):
"""Return a shallow copy of this object."""
return copy.copy(self) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"copy",
".",
"copy",
"(",
"self",
")"
] | [
187,
4
] | [
189,
30
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict.update | (self, *args, **kwargs) | Extend rather than replace existing key lists. | Extend rather than replace existing key lists. | def update(self, *args, **kwargs):
"""Extend rather than replace existing key lists."""
if len(args) > 1:
raise TypeError("update expected at most 1 argument, got %d" % len(args))
if args:
arg = args[0]
if isinstance(arg, MultiValueDict):
for k... | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"update expected at most 1 argument, got %d\"",
"%",
"len",
"(",
"args",
")",
")",
"if",
"args... | [
191,
4
] | [
206,
50
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict.dict | (self) | Return current object as a dict with singular values. | Return current object as a dict with singular values. | def dict(self):
"""Return current object as a dict with singular values."""
return {key: self[key] for key in self} | [
"def",
"dict",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"self",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
"}"
] | [
208,
4
] | [
210,
47
] | python | en | ['en', 'en', 'en'] | True |
DictWrapper.__getitem__ | (self, key) |
Retrieve the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
|
Retrieve the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
| def __getitem__(self, key):
"""
Retrieve the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
"""
use_func = key.startswith(self.prefix)
if use_f... | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"use_func",
"=",
"key",
".",
"startswith",
"(",
"self",
".",
"prefix",
")",
"if",
"use_func",
":",
"key",
"=",
"key",
"[",
"len",
"(",
"self",
".",
"prefix",
")",
":",
"]",
"value",
"=",
"s... | [
264,
4
] | [
276,
20
] | python | en | ['en', 'error', 'th'] | False |
create_reverse_many_to_one_manager | (superclass, rel) |
Create a manager for the reverse side of a many-to-one relation.
This manager subclasses another manager, generally the default manager of
the related model, and adds behaviors specific to many-to-one relations.
|
Create a manager for the reverse side of a many-to-one relation. | def create_reverse_many_to_one_manager(superclass, rel):
"""
Create a manager for the reverse side of a many-to-one relation.
This manager subclasses another manager, generally the default manager of
the related model, and adds behaviors specific to many-to-one relations.
"""
class RelatedMana... | [
"def",
"create_reverse_many_to_one_manager",
"(",
"superclass",
",",
"rel",
")",
":",
"class",
"RelatedManager",
"(",
"superclass",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"instance",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
"... | [
550,
0
] | [
757,
25
] | python | en | ['en', 'error', 'th'] | False |
create_forward_many_to_many_manager | (superclass, rel, reverse) |
Create a manager for the either side of a many-to-many relation.
This manager subclasses another manager, generally the default manager of
the related model, and adds behaviors specific to many-to-many relations.
|
Create a manager for the either side of a many-to-many relation. | def create_forward_many_to_many_manager(superclass, rel, reverse):
"""
Create a manager for the either side of a many-to-many relation.
This manager subclasses another manager, generally the default manager of
the related model, and adds behaviors specific to many-to-many relations.
"""
class ... | [
"def",
"create_forward_many_to_many_manager",
"(",
"superclass",
",",
"rel",
",",
"reverse",
")",
":",
"class",
"ManyRelatedManager",
"(",
"superclass",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"instance",
"=",
"None",
")",
":",
"super",
"(",
")",
".",... | [
806,
0
] | [
1204,
29
] | python | en | ['en', 'error', 'th'] | False |
ForwardManyToOneDescriptor.__get__ | (self, instance, cls=None) |
Get the related instance through the forward relation.
With the example above, when getting ``child.parent``:
- ``self`` is the descriptor managing the ``parent`` attribute
- ``instance`` is the ``child`` instance
- ``cls`` is the ``Child`` class (we don't need it)
|
Get the related instance through the forward relation. | def __get__(self, instance, cls=None):
"""
Get the related instance through the forward relation.
With the example above, when getting ``child.parent``:
- ``self`` is the descriptor managing the ``parent`` attribute
- ``instance`` is the ``child`` instance
- ``cls`` is ... | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"cls",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"# The related instance is loaded from the database and then cached",
"# by the field on the model instance state. It can also be pre-cach... | [
155,
4
] | [
200,
26
] | python | en | ['en', 'error', 'th'] | False |
ForwardManyToOneDescriptor.__set__ | (self, instance, value) |
Set the related instance through the forward relation.
With the example above, when setting ``child.parent = parent``:
- ``self`` is the descriptor managing the ``parent`` attribute
- ``instance`` is the ``child`` instance
- ``value`` is the ``parent`` instance on the right of... |
Set the related instance through the forward relation. | def __set__(self, instance, value):
"""
Set the related instance through the forward relation.
With the example above, when setting ``child.parent = parent``:
- ``self`` is the descriptor managing the ``parent`` attribute
- ``instance`` is the ``child`` instance
- ``val... | [
"def",
"__set__",
"(",
"self",
",",
"instance",
",",
"value",
")",
":",
"# An object must be an instance of the related class.",
"if",
"value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"field",
".",
"remote_field",
".",
... | [
202,
4
] | [
266,
58
] | python | en | ['en', 'error', 'th'] | False |
ForwardManyToOneDescriptor.__reduce__ | (self) |
Pickling should return the instance attached by self.field on the
model, not a new copy of that descriptor. Use getattr() to retrieve
the instance directly from the model.
|
Pickling should return the instance attached by self.field on the
model, not a new copy of that descriptor. Use getattr() to retrieve
the instance directly from the model.
| def __reduce__(self):
"""
Pickling should return the instance attached by self.field on the
model, not a new copy of that descriptor. Use getattr() to retrieve
the instance directly from the model.
"""
return getattr, (self.field.model, self.field.name) | [
"def",
"__reduce__",
"(",
"self",
")",
":",
"return",
"getattr",
",",
"(",
"self",
".",
"field",
".",
"model",
",",
"self",
".",
"field",
".",
"name",
")"
] | [
268,
4
] | [
274,
59
] | python | en | ['en', 'error', 'th'] | False |
ReverseOneToOneDescriptor.__get__ | (self, instance, cls=None) |
Get the related instance through the reverse relation.
With the example above, when getting ``place.restaurant``:
- ``self`` is the descriptor managing the ``restaurant`` attribute
- ``instance`` is the ``place`` instance
- ``cls`` is the ``Place`` class (unused)
Keep... |
Get the related instance through the reverse relation. | def __get__(self, instance, cls=None):
"""
Get the related instance through the reverse relation.
With the example above, when getting ``place.restaurant``:
- ``self`` is the descriptor managing the ``restaurant`` attribute
- ``instance`` is the ``place`` instance
- ``c... | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"cls",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"# The related instance is loaded from the database and then cached",
"# by the field on the model instance state. It can also be pre-cach... | [
382,
4
] | [
427,
26
] | python | en | ['en', 'error', 'th'] | False |
ReverseOneToOneDescriptor.__set__ | (self, instance, value) |
Set the related instance through the reverse relation.
With the example above, when setting ``place.restaurant = restaurant``:
- ``self`` is the descriptor managing the ``restaurant`` attribute
- ``instance`` is the ``place`` instance
- ``value`` is the ``restaurant`` instance... |
Set the related instance through the reverse relation. | def __set__(self, instance, value):
"""
Set the related instance through the reverse relation.
With the example above, when setting ``place.restaurant = restaurant``:
- ``self`` is the descriptor managing the ``restaurant`` attribute
- ``instance`` is the ``place`` instance
... | [
"def",
"__set__",
"(",
"self",
",",
"instance",
",",
"value",
")",
":",
"# The similarity of the code below to the code in",
"# ForwardManyToOneDescriptor is annoying, but there's a bunch",
"# of small differences that would make a common base class convoluted.",
"if",
"value",
"is",
... | [
429,
4
] | [
486,
64
] | python | en | ['en', 'error', 'th'] | False |
ReverseManyToOneDescriptor.__get__ | (self, instance, cls=None) |
Get the related objects through the reverse relation.
With the example above, when getting ``parent.children``:
- ``self`` is the descriptor managing the ``children`` attribute
- ``instance`` is the ``parent`` instance
- ``cls`` is the ``Parent`` class (unused)
|
Get the related objects through the reverse relation. | def __get__(self, instance, cls=None):
"""
Get the related objects through the reverse relation.
With the example above, when getting ``parent.children``:
- ``self`` is the descriptor managing the ``children`` attribute
- ``instance`` is the ``parent`` instance
- ``cls`... | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"cls",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"return",
"self",
".",
"related_manager_cls",
"(",
"instance",
")"
] | [
522,
4
] | [
535,
49
] | python | en | ['en', 'error', 'th'] | False |
is_appengine_sandbox | () | Reports if the app is running in the first generation sandbox.
The second generation runtimes are technically still in a sandbox, but it
is much less restrictive, so generally you shouldn't need to check for it.
see https://cloud.google.com/appengine/docs/standard/runtimes
| Reports if the app is running in the first generation sandbox. | def is_appengine_sandbox():
"""Reports if the app is running in the first generation sandbox.
The second generation runtimes are technically still in a sandbox, but it
is much less restrictive, so generally you shouldn't need to check for it.
see https://cloud.google.com/appengine/docs/standard/runtime... | [
"def",
"is_appengine_sandbox",
"(",
")",
":",
"return",
"is_appengine",
"(",
")",
"and",
"os",
".",
"environ",
"[",
"\"APPENGINE_RUNTIME\"",
"]",
"==",
"\"python27\""
] | [
11,
0
] | [
18,
75
] | python | en | ['en', 'en', 'en'] | True |
is_prod_appengine_mvms | () | Deprecated. | Deprecated. | def is_prod_appengine_mvms():
"""Deprecated."""
return False | [
"def",
"is_prod_appengine_mvms",
"(",
")",
":",
"return",
"False"
] | [
33,
0
] | [
35,
16
] | python | en | ['en', 'la', 'it'] | False |
default_credentials | () | Returns Application Default Credentials. | Returns Application Default Credentials. | def default_credentials():
"""Returns Application Default Credentials."""
if HAS_GOOGLE_AUTH:
credentials, _ = google.auth.default()
return credentials
elif HAS_OAUTH2CLIENT:
return oauth2client.client.GoogleCredentials.get_application_default()
else:
raise EnvironmentErr... | [
"def",
"default_credentials",
"(",
")",
":",
"if",
"HAS_GOOGLE_AUTH",
":",
"credentials",
",",
"_",
"=",
"google",
".",
"auth",
".",
"default",
"(",
")",
"return",
"credentials",
"elif",
"HAS_OAUTH2CLIENT",
":",
"return",
"oauth2client",
".",
"client",
".",
... | [
34,
0
] | [
44,
43
] | python | en | ['en', 'ca', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.