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
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
user_in_user_groups | (user_id, **options) |
Get all user groups a user belongs to
:param user_id: The id of user
:param user_id: str
:param options: Generic advanced options dict, see online documentation
:type options: dict, optional
:return: List of groups user is in
:rtype: dict
|
Get all user groups a user belongs to
:param user_id: The id of user
:param user_id: str
:param options: Generic advanced options dict, see online documentation
:type options: dict, optional
:return: List of groups user is in
:rtype: dict
| def user_in_user_groups(user_id, **options):
"""
Get all user groups a user belongs to
:param user_id: The id of user
:param user_id: str
:param options: Generic advanced options dict, see online documentation
:type options: dict, optional
:return: List of groups user is in
:rtype: dict
"""
uri = [USER_GROUPS_SUB_PATH, user_id]
return _call_account_api("get", uri, {}, **options) | [
"def",
"user_in_user_groups",
"(",
"user_id",
",",
"*",
"*",
"options",
")",
":",
"uri",
"=",
"[",
"USER_GROUPS_SUB_PATH",
",",
"user_id",
"]",
"return",
"_call_account_api",
"(",
"\"get\"",
",",
"uri",
",",
"{",
"}",
",",
"*",
"*",
"options",
")"
] | [
354,
0
] | [
365,
55
] | python | en | ['en', 'error', 'th'] | False |
scaled_dot_product_attention | (q, k, v) | Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be broadcastable for addition.
Args:
q: query shape == (..., seq_len_q, depth)
k: key shape == (..., seq_len_k, depth)
v: value shape == (..., seq_len_v, depth_v)
Returns:
output, attention_weights
from : https://www.tensorflow.org/tutorials/text/transformer
| Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be broadcastable for addition. | def scaled_dot_product_attention(q, k, v):
"""Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be broadcastable for addition.
Args:
q: query shape == (..., seq_len_q, depth)
k: key shape == (..., seq_len_k, depth)
v: value shape == (..., seq_len_v, depth_v)
Returns:
output, attention_weights
from : https://www.tensorflow.org/tutorials/text/transformer
"""
matmul_qk = tf.matmul(q, k, transpose_b=True) # (..., seq_len_q, seq_len_k)
# scale matmul_qk
dk = tf.cast(tf.shape(k)[-1], tf.float32)
scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)
# softmax is normalized on the last axis (seq_len_k) so that the scores
# add up to 1.
attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1) # (..., seq_len_q, seq_len_k)
output = tf.matmul(attention_weights, v) # (..., seq_len_q, depth_v)
return output, attention_weights | [
"def",
"scaled_dot_product_attention",
"(",
"q",
",",
"k",
",",
"v",
")",
":",
"matmul_qk",
"=",
"tf",
".",
"matmul",
"(",
"q",
",",
"k",
",",
"transpose_b",
"=",
"True",
")",
"# (..., seq_len_q, seq_len_k)",
"# scale matmul_qk",
"dk",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"shape",
"(",
"k",
")",
"[",
"-",
"1",
"]",
",",
"tf",
".",
"float32",
")",
"scaled_attention_logits",
"=",
"matmul_qk",
"/",
"tf",
".",
"math",
".",
"sqrt",
"(",
"dk",
")",
"# softmax is normalized on the last axis (seq_len_k) so that the scores",
"# add up to 1.",
"attention_weights",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"scaled_attention_logits",
",",
"axis",
"=",
"-",
"1",
")",
"# (..., seq_len_q, seq_len_k)",
"output",
"=",
"tf",
".",
"matmul",
"(",
"attention_weights",
",",
"v",
")",
"# (..., seq_len_q, depth_v)",
"return",
"output",
",",
"attention_weights"
] | [
60,
0
] | [
90,
36
] | python | en | ['en', 'en', 'en'] | True |
Attention.__init__ | (self, d_model, spatial_dims, positional_encoding=True, name="self_attention") |
d_model : number of output channels
spatial_dim : spatial dimensions of input tensor (x , y)
if positional_encoding: depth must correspond to input channel number
adapted from: https://www.tensorflow.org/tutorials/text/transformer
|
d_model : number of output channels
spatial_dim : spatial dimensions of input tensor (x , y)
if positional_encoding: depth must correspond to input channel number
adapted from: https://www.tensorflow.org/tutorials/text/transformer
| def __init__(self, d_model, spatial_dims, positional_encoding=True, name="self_attention"):
'''
d_model : number of output channels
spatial_dim : spatial dimensions of input tensor (x , y)
if positional_encoding: depth must correspond to input channel number
adapted from: https://www.tensorflow.org/tutorials/text/transformer
'''
super().__init__(name=name)
self.d_model = d_model
self.spatial_dims=spatial_dims
self.spatial_dim = np.prod(spatial_dims)
self.wq = Dense(self.d_model, name=name+"_q")
self.wk = Dense(self.d_model, name=name+"_k")
self.wv = Dense(self.d_model, name=name+"_w")
self.positional_encoding=positional_encoding
if positional_encoding:
self.pos_embedding = Embedding(self.spatial_dim, d_model, name=name+"pos_enc") | [
"def",
"__init__",
"(",
"self",
",",
"d_model",
",",
"spatial_dims",
",",
"positional_encoding",
"=",
"True",
",",
"name",
"=",
"\"self_attention\"",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"name",
"=",
"name",
")",
"self",
".",
"d_model",
"=",
"d_model",
"self",
".",
"spatial_dims",
"=",
"spatial_dims",
"self",
".",
"spatial_dim",
"=",
"np",
".",
"prod",
"(",
"spatial_dims",
")",
"self",
".",
"wq",
"=",
"Dense",
"(",
"self",
".",
"d_model",
",",
"name",
"=",
"name",
"+",
"\"_q\"",
")",
"self",
".",
"wk",
"=",
"Dense",
"(",
"self",
".",
"d_model",
",",
"name",
"=",
"name",
"+",
"\"_k\"",
")",
"self",
".",
"wv",
"=",
"Dense",
"(",
"self",
".",
"d_model",
",",
"name",
"=",
"name",
"+",
"\"_w\"",
")",
"self",
".",
"positional_encoding",
"=",
"positional_encoding",
"if",
"positional_encoding",
":",
"self",
".",
"pos_embedding",
"=",
"Embedding",
"(",
"self",
".",
"spatial_dim",
",",
"d_model",
",",
"name",
"=",
"name",
"+",
"\"pos_enc\"",
")"
] | [
6,
4
] | [
22,
90
] | python | en | ['en', 'error', 'th'] | False |
Attention.call | (self, x) |
x : list of 2 tensor with shape (batch_size, y, x, channels)
|
x : list of 2 tensor with shape (batch_size, y, x, channels)
| def call(self, x):
'''
x : list of 2 tensor with shape (batch_size, y, x, channels)
'''
[input, output] = x
shape = tf.shape(output)
batch_size = shape[0]
#spatial_dims = shape[1:-1]
#spatial_dim = tf.reduce_prod(spatial_dims)
depth_dim = shape[3]
if self.positional_encoding:
x_index = tf.range(self.spatial_dim, dtype=tf.int32)
pos_emb = self.pos_embedding(x_index) # (spa_dim, d_model)
pos_emb = tf.reshape(pos_emb, (self.spatial_dims[0], self.spatial_dims[1], self.d_model)) #for broadcasting purpose
input = input + pos_emb # broadcast
output = output + pos_emb # broadcast
q = self.wq(output) # (batch_size, *spa_dims, d_model)
k = self.wk(input) # (batch_size, *spa_dims, d_model)
v = self.wv(input) # (batch_size, *spa_dims, d_model)
q = tf.reshape(q, (batch_size, -1, depth_dim)) # (batch_size, spa_dim, d_model)
k = tf.reshape(k, (batch_size, -1, depth_dim))
v = tf.reshape(v, (batch_size, -1, depth_dim))
# scaled_attention.shape == (batch_size, spa_dims, depth)
# attention_weights.shape == (batch_size, spa_dims, spa_dims)
scaled_attention, attention_weights = scaled_dot_product_attention(q, k, v)
output = tf.reshape(scaled_attention, (batch_size, self.spatial_dims[0], self.spatial_dims[1], self.d_model))
tf.identity(attention_weights, name=self.name+"_attention_weights")
return output, attention_weights | [
"def",
"call",
"(",
"self",
",",
"x",
")",
":",
"[",
"input",
",",
"output",
"]",
"=",
"x",
"shape",
"=",
"tf",
".",
"shape",
"(",
"output",
")",
"batch_size",
"=",
"shape",
"[",
"0",
"]",
"#spatial_dims = shape[1:-1]",
"#spatial_dim = tf.reduce_prod(spatial_dims)",
"depth_dim",
"=",
"shape",
"[",
"3",
"]",
"if",
"self",
".",
"positional_encoding",
":",
"x_index",
"=",
"tf",
".",
"range",
"(",
"self",
".",
"spatial_dim",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"pos_emb",
"=",
"self",
".",
"pos_embedding",
"(",
"x_index",
")",
"# (spa_dim, d_model)",
"pos_emb",
"=",
"tf",
".",
"reshape",
"(",
"pos_emb",
",",
"(",
"self",
".",
"spatial_dims",
"[",
"0",
"]",
",",
"self",
".",
"spatial_dims",
"[",
"1",
"]",
",",
"self",
".",
"d_model",
")",
")",
"#for broadcasting purpose",
"input",
"=",
"input",
"+",
"pos_emb",
"# broadcast",
"output",
"=",
"output",
"+",
"pos_emb",
"# broadcast",
"q",
"=",
"self",
".",
"wq",
"(",
"output",
")",
"# (batch_size, *spa_dims, d_model)",
"k",
"=",
"self",
".",
"wk",
"(",
"input",
")",
"# (batch_size, *spa_dims, d_model)",
"v",
"=",
"self",
".",
"wv",
"(",
"input",
")",
"# (batch_size, *spa_dims, d_model)",
"q",
"=",
"tf",
".",
"reshape",
"(",
"q",
",",
"(",
"batch_size",
",",
"-",
"1",
",",
"depth_dim",
")",
")",
"# (batch_size, spa_dim, d_model)",
"k",
"=",
"tf",
".",
"reshape",
"(",
"k",
",",
"(",
"batch_size",
",",
"-",
"1",
",",
"depth_dim",
")",
")",
"v",
"=",
"tf",
".",
"reshape",
"(",
"v",
",",
"(",
"batch_size",
",",
"-",
"1",
",",
"depth_dim",
")",
")",
"# scaled_attention.shape == (batch_size, spa_dims, depth)",
"# attention_weights.shape == (batch_size, spa_dims, spa_dims)",
"scaled_attention",
",",
"attention_weights",
"=",
"scaled_dot_product_attention",
"(",
"q",
",",
"k",
",",
"v",
")",
"output",
"=",
"tf",
".",
"reshape",
"(",
"scaled_attention",
",",
"(",
"batch_size",
",",
"self",
".",
"spatial_dims",
"[",
"0",
"]",
",",
"self",
".",
"spatial_dims",
"[",
"1",
"]",
",",
"self",
".",
"d_model",
")",
")",
"tf",
".",
"identity",
"(",
"attention_weights",
",",
"name",
"=",
"self",
".",
"name",
"+",
"\"_attention_weights\"",
")",
"return",
"output",
",",
"attention_weights"
] | [
24,
4
] | [
55,
40
] | python | en | ['en', 'error', 'th'] | False |
all_frames | (im, func=None) |
Applies a given function to all frames in an image or a list of images.
The frames are returned as a list of separate images.
:param im: An image, or a list of images.
:param func: The function to apply to all of the image frames.
:returns: A list of images.
|
Applies a given function to all frames in an image or a list of images.
The frames are returned as a list of separate images. | def all_frames(im, func=None):
"""
Applies a given function to all frames in an image or a list of images.
The frames are returned as a list of separate images.
:param im: An image, or a list of images.
:param func: The function to apply to all of the image frames.
:returns: A list of images.
"""
if not isinstance(im, list):
im = [im]
ims = []
for imSequence in im:
current = imSequence.tell()
ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
imSequence.seek(current)
return [func(im) for im in ims] if func else ims | [
"def",
"all_frames",
"(",
"im",
",",
"func",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"im",
",",
"list",
")",
":",
"im",
"=",
"[",
"im",
"]",
"ims",
"=",
"[",
"]",
"for",
"imSequence",
"in",
"im",
":",
"current",
"=",
"imSequence",
".",
"tell",
"(",
")",
"ims",
"+=",
"[",
"im_frame",
".",
"copy",
"(",
")",
"for",
"im_frame",
"in",
"Iterator",
"(",
"imSequence",
")",
"]",
"imSequence",
".",
"seek",
"(",
"current",
")",
"return",
"[",
"func",
"(",
"im",
")",
"for",
"im",
"in",
"ims",
"]",
"if",
"func",
"else",
"ims"
] | [
55,
0
] | [
74,
52
] | python | en | ['en', 'error', 'th'] | False |
command_swanson | (bot, user, channel, args) | Prints Ron Swanson quotes. | Prints Ron Swanson quotes. | def command_swanson(bot, user, channel, args):
"Prints Ron Swanson quotes."
quotefile = os.path.join(bot.factory.moduledir, "swanson.txt")
try:
with open(quotefile) as f:
quotes = f.readlines()
except IOError:
log.error("Could not read {}".format(quotefile))
else:
quote = random.choice(quotes).strip()
return bot.say(channel, "{} - Ron Swanson".format(quote)) | [
"def",
"command_swanson",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"quotefile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"bot",
".",
"factory",
".",
"moduledir",
",",
"\"swanson.txt\"",
")",
"try",
":",
"with",
"open",
"(",
"quotefile",
")",
"as",
"f",
":",
"quotes",
"=",
"f",
".",
"readlines",
"(",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"\"Could not read {}\"",
".",
"format",
"(",
"quotefile",
")",
")",
"else",
":",
"quote",
"=",
"random",
".",
"choice",
"(",
"quotes",
")",
".",
"strip",
"(",
")",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"{} - Ron Swanson\"",
".",
"format",
"(",
"quote",
")",
")"
] | [
8,
0
] | [
20,
61
] | python | en | ['fr', 'sr', 'en'] | False |
command_whatshesaid | (bot, user, channel, args) | Prints quotes of accomplished women. | Prints quotes of accomplished women. | def command_whatshesaid(bot, user, channel, args):
"Prints quotes of accomplished women."
quotefile = os.path.join(bot.factory.moduledir, "whatshesaid.txt")
try:
with open(quotefile) as f:
quotes = f.readlines()
except IOError:
log.error("Could not read {}".format(quotefile))
else:
quote = random.choice(quotes).strip()
return bot.say(channel, quote) | [
"def",
"command_whatshesaid",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"quotefile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"bot",
".",
"factory",
".",
"moduledir",
",",
"\"whatshesaid.txt\"",
")",
"try",
":",
"with",
"open",
"(",
"quotefile",
")",
"as",
"f",
":",
"quotes",
"=",
"f",
".",
"readlines",
"(",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"\"Could not read {}\"",
".",
"format",
"(",
"quotefile",
")",
")",
"else",
":",
"quote",
"=",
"random",
".",
"choice",
"(",
"quotes",
")",
".",
"strip",
"(",
")",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"quote",
")"
] | [
23,
0
] | [
35,
34
] | python | en | ['en', 'en', 'en'] | True |
do_cache | (parser, token) |
This will cache the contents of a template fragment for a given amount
of time.
Usage::
{% load cache %}
{% cache [expire_time] [fragment_name] %}
.. some expensive processing ..
{% endcache %}
This tag also supports varying by a list of arguments::
{% load cache %}
{% cache [expire_time] [fragment_name] [var1] [var2] .. %}
.. some expensive processing ..
{% endcache %}
Optionally the cache to use may be specified thus::
{% cache .... using="cachename" %}
Each unique set of arguments will result in a unique cache entry.
|
This will cache the contents of a template fragment for a given amount
of time. | def do_cache(parser, token):
"""
This will cache the contents of a template fragment for a given amount
of time.
Usage::
{% load cache %}
{% cache [expire_time] [fragment_name] %}
.. some expensive processing ..
{% endcache %}
This tag also supports varying by a list of arguments::
{% load cache %}
{% cache [expire_time] [fragment_name] [var1] [var2] .. %}
.. some expensive processing ..
{% endcache %}
Optionally the cache to use may be specified thus::
{% cache .... using="cachename" %}
Each unique set of arguments will result in a unique cache entry.
"""
nodelist = parser.parse(('endcache',))
parser.delete_first_token()
tokens = token.split_contents()
if len(tokens) < 3:
raise TemplateSyntaxError("'%r' tag requires at least 2 arguments." % tokens[0])
if len(tokens) > 3 and tokens[-1].startswith('using='):
cache_name = parser.compile_filter(tokens[-1][len('using='):])
tokens = tokens[:-1]
else:
cache_name = None
return CacheNode(
nodelist, parser.compile_filter(tokens[1]),
tokens[2], # fragment_name can't be a variable.
[parser.compile_filter(t) for t in tokens[3:]],
cache_name,
) | [
"def",
"do_cache",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endcache'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"tokens",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
"<",
"3",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%r' tag requires at least 2 arguments.\"",
"%",
"tokens",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"3",
"and",
"tokens",
"[",
"-",
"1",
"]",
".",
"startswith",
"(",
"'using='",
")",
":",
"cache_name",
"=",
"parser",
".",
"compile_filter",
"(",
"tokens",
"[",
"-",
"1",
"]",
"[",
"len",
"(",
"'using='",
")",
":",
"]",
")",
"tokens",
"=",
"tokens",
"[",
":",
"-",
"1",
"]",
"else",
":",
"cache_name",
"=",
"None",
"return",
"CacheNode",
"(",
"nodelist",
",",
"parser",
".",
"compile_filter",
"(",
"tokens",
"[",
"1",
"]",
")",
",",
"tokens",
"[",
"2",
"]",
",",
"# fragment_name can't be a variable.",
"[",
"parser",
".",
"compile_filter",
"(",
"t",
")",
"for",
"t",
"in",
"tokens",
"[",
"3",
":",
"]",
"]",
",",
"cache_name",
",",
")"
] | [
52,
0
] | [
92,
5
] | python | en | ['en', 'error', 'th'] | False |
MigrationQuestioner.ask_initial | (self, app_label) | Should we create an initial migration for the app? | Should we create an initial migration for the app? | def ask_initial(self, app_label):
"""Should we create an initial migration for the app?"""
# If it was specified on the command line, definitely true
if app_label in self.specified_apps:
return True
# Otherwise, we look to see if it has a migrations module
# without any Python files in it, apart from __init__.py.
# Apps from the new app template will have these; the Python
# file check will ensure we skip South ones.
try:
app_config = apps.get_app_config(app_label)
except LookupError: # It's a fake app.
return self.defaults.get("ask_initial", False)
migrations_import_path, _ = MigrationLoader.migrations_module(app_config.label)
if migrations_import_path is None:
# It's an application with migrations disabled.
return self.defaults.get("ask_initial", False)
try:
migrations_module = importlib.import_module(migrations_import_path)
except ImportError:
return self.defaults.get("ask_initial", False)
else:
# getattr() needed on PY36 and older (replace with attribute access).
if getattr(migrations_module, "__file__", None):
filenames = os.listdir(os.path.dirname(migrations_module.__file__))
elif hasattr(migrations_module, "__path__"):
if len(migrations_module.__path__) > 1:
return False
filenames = os.listdir(list(migrations_module.__path__)[0])
return not any(x.endswith(".py") for x in filenames if x != "__init__.py") | [
"def",
"ask_initial",
"(",
"self",
",",
"app_label",
")",
":",
"# If it was specified on the command line, definitely true",
"if",
"app_label",
"in",
"self",
".",
"specified_apps",
":",
"return",
"True",
"# Otherwise, we look to see if it has a migrations module",
"# without any Python files in it, apart from __init__.py.",
"# Apps from the new app template will have these; the Python",
"# file check will ensure we skip South ones.",
"try",
":",
"app_config",
"=",
"apps",
".",
"get_app_config",
"(",
"app_label",
")",
"except",
"LookupError",
":",
"# It's a fake app.",
"return",
"self",
".",
"defaults",
".",
"get",
"(",
"\"ask_initial\"",
",",
"False",
")",
"migrations_import_path",
",",
"_",
"=",
"MigrationLoader",
".",
"migrations_module",
"(",
"app_config",
".",
"label",
")",
"if",
"migrations_import_path",
"is",
"None",
":",
"# It's an application with migrations disabled.",
"return",
"self",
".",
"defaults",
".",
"get",
"(",
"\"ask_initial\"",
",",
"False",
")",
"try",
":",
"migrations_module",
"=",
"importlib",
".",
"import_module",
"(",
"migrations_import_path",
")",
"except",
"ImportError",
":",
"return",
"self",
".",
"defaults",
".",
"get",
"(",
"\"ask_initial\"",
",",
"False",
")",
"else",
":",
"# getattr() needed on PY36 and older (replace with attribute access).",
"if",
"getattr",
"(",
"migrations_module",
",",
"\"__file__\"",
",",
"None",
")",
":",
"filenames",
"=",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"migrations_module",
".",
"__file__",
")",
")",
"elif",
"hasattr",
"(",
"migrations_module",
",",
"\"__path__\"",
")",
":",
"if",
"len",
"(",
"migrations_module",
".",
"__path__",
")",
">",
"1",
":",
"return",
"False",
"filenames",
"=",
"os",
".",
"listdir",
"(",
"list",
"(",
"migrations_module",
".",
"__path__",
")",
"[",
"0",
"]",
")",
"return",
"not",
"any",
"(",
"x",
".",
"endswith",
"(",
"\".py\"",
")",
"for",
"x",
"in",
"filenames",
"if",
"x",
"!=",
"\"__init__.py\"",
")"
] | [
24,
4
] | [
53,
86
] | python | en | ['en', 'en', 'en'] | True |
MigrationQuestioner.ask_not_null_addition | (self, field_name, model_name) | Adding a NOT NULL field to a model. | Adding a NOT NULL field to a model. | def ask_not_null_addition(self, field_name, model_name):
"""Adding a NOT NULL field to a model."""
# None means quit
return None | [
"def",
"ask_not_null_addition",
"(",
"self",
",",
"field_name",
",",
"model_name",
")",
":",
"# None means quit",
"return",
"None"
] | [
55,
4
] | [
58,
19
] | python | en | ['en', 'en', 'en'] | True |
MigrationQuestioner.ask_not_null_alteration | (self, field_name, model_name) | Changing a NULL field to NOT NULL. | Changing a NULL field to NOT NULL. | def ask_not_null_alteration(self, field_name, model_name):
"""Changing a NULL field to NOT NULL."""
# None means quit
return None | [
"def",
"ask_not_null_alteration",
"(",
"self",
",",
"field_name",
",",
"model_name",
")",
":",
"# None means quit",
"return",
"None"
] | [
60,
4
] | [
63,
19
] | python | en | ['en', 'en', 'en'] | True |
MigrationQuestioner.ask_rename | (self, model_name, old_name, new_name, field_instance) | Was this field really renamed? | Was this field really renamed? | def ask_rename(self, model_name, old_name, new_name, field_instance):
"""Was this field really renamed?"""
return self.defaults.get("ask_rename", False) | [
"def",
"ask_rename",
"(",
"self",
",",
"model_name",
",",
"old_name",
",",
"new_name",
",",
"field_instance",
")",
":",
"return",
"self",
".",
"defaults",
".",
"get",
"(",
"\"ask_rename\"",
",",
"False",
")"
] | [
65,
4
] | [
67,
53
] | python | en | ['en', 'en', 'en'] | True |
MigrationQuestioner.ask_rename_model | (self, old_model_state, new_model_state) | Was this model really renamed? | Was this model really renamed? | def ask_rename_model(self, old_model_state, new_model_state):
"""Was this model really renamed?"""
return self.defaults.get("ask_rename_model", False) | [
"def",
"ask_rename_model",
"(",
"self",
",",
"old_model_state",
",",
"new_model_state",
")",
":",
"return",
"self",
".",
"defaults",
".",
"get",
"(",
"\"ask_rename_model\"",
",",
"False",
")"
] | [
69,
4
] | [
71,
59
] | python | en | ['en', 'en', 'en'] | True |
MigrationQuestioner.ask_merge | (self, app_label) | Do you really want to merge these migrations? | Do you really want to merge these migrations? | def ask_merge(self, app_label):
"""Do you really want to merge these migrations?"""
return self.defaults.get("ask_merge", False) | [
"def",
"ask_merge",
"(",
"self",
",",
"app_label",
")",
":",
"return",
"self",
".",
"defaults",
".",
"get",
"(",
"\"ask_merge\"",
",",
"False",
")"
] | [
73,
4
] | [
75,
52
] | python | en | ['en', 'en', 'en'] | True |
MigrationQuestioner.ask_auto_now_add_addition | (self, field_name, model_name) | Adding an auto_now_add field to a model. | Adding an auto_now_add field to a model. | def ask_auto_now_add_addition(self, field_name, model_name):
"""Adding an auto_now_add field to a model."""
# None means quit
return None | [
"def",
"ask_auto_now_add_addition",
"(",
"self",
",",
"field_name",
",",
"model_name",
")",
":",
"# None means quit",
"return",
"None"
] | [
77,
4
] | [
80,
19
] | python | en | ['en', 'en', 'en'] | True |
InteractiveMigrationQuestioner._ask_default | (self, default='') |
Prompt for a default value.
The ``default`` argument allows providing a custom default value (as a
string) which will be shown to the user and used as the return value
if the user doesn't provide any other input.
|
Prompt for a default value. | def _ask_default(self, default=''):
"""
Prompt for a default value.
The ``default`` argument allows providing a custom default value (as a
string) which will be shown to the user and used as the return value
if the user doesn't provide any other input.
"""
print("Please enter the default value now, as valid Python")
if default:
print(
"You can accept the default '{}' by pressing 'Enter' or you "
"can provide another value.".format(default)
)
print("The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now")
print("Type 'exit' to exit this prompt")
while True:
if default:
prompt = "[default: {}] >>> ".format(default)
else:
prompt = ">>> "
code = input(prompt)
if not code and default:
code = default
if not code:
print("Please enter some code, or 'exit' (with no quotes) to exit.")
elif code == "exit":
sys.exit(1)
else:
try:
return eval(code, {}, {'datetime': datetime, 'timezone': timezone})
except (SyntaxError, NameError) as e:
print("Invalid input: %s" % e) | [
"def",
"_ask_default",
"(",
"self",
",",
"default",
"=",
"''",
")",
":",
"print",
"(",
"\"Please enter the default value now, as valid Python\"",
")",
"if",
"default",
":",
"print",
"(",
"\"You can accept the default '{}' by pressing 'Enter' or you \"",
"\"can provide another value.\"",
".",
"format",
"(",
"default",
")",
")",
"print",
"(",
"\"The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now\"",
")",
"print",
"(",
"\"Type 'exit' to exit this prompt\"",
")",
"while",
"True",
":",
"if",
"default",
":",
"prompt",
"=",
"\"[default: {}] >>> \"",
".",
"format",
"(",
"default",
")",
"else",
":",
"prompt",
"=",
"\">>> \"",
"code",
"=",
"input",
"(",
"prompt",
")",
"if",
"not",
"code",
"and",
"default",
":",
"code",
"=",
"default",
"if",
"not",
"code",
":",
"print",
"(",
"\"Please enter some code, or 'exit' (with no quotes) to exit.\"",
")",
"elif",
"code",
"==",
"\"exit\"",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"else",
":",
"try",
":",
"return",
"eval",
"(",
"code",
",",
"{",
"}",
",",
"{",
"'datetime'",
":",
"datetime",
",",
"'timezone'",
":",
"timezone",
"}",
")",
"except",
"(",
"SyntaxError",
",",
"NameError",
")",
"as",
"e",
":",
"print",
"(",
"\"Invalid input: %s\"",
"%",
"e",
")"
] | [
108,
4
] | [
140,
50
] | python | en | ['en', 'error', 'th'] | False |
InteractiveMigrationQuestioner.ask_not_null_addition | (self, field_name, model_name) | Adding a NOT NULL field to a model. | Adding a NOT NULL field to a model. | def ask_not_null_addition(self, field_name, model_name):
"""Adding a NOT NULL field to a model."""
if not self.dry_run:
choice = self._choice_input(
"You are trying to add a non-nullable field '%s' to %s without a default; "
"we can't do that (the database needs something to populate existing rows).\n"
"Please select a fix:" % (field_name, model_name),
[
("Provide a one-off default now (will be set on all existing "
"rows with a null value for this column)"),
"Quit, and let me add a default in models.py",
]
)
if choice == 2:
sys.exit(3)
else:
return self._ask_default()
return None | [
"def",
"ask_not_null_addition",
"(",
"self",
",",
"field_name",
",",
"model_name",
")",
":",
"if",
"not",
"self",
".",
"dry_run",
":",
"choice",
"=",
"self",
".",
"_choice_input",
"(",
"\"You are trying to add a non-nullable field '%s' to %s without a default; \"",
"\"we can't do that (the database needs something to populate existing rows).\\n\"",
"\"Please select a fix:\"",
"%",
"(",
"field_name",
",",
"model_name",
")",
",",
"[",
"(",
"\"Provide a one-off default now (will be set on all existing \"",
"\"rows with a null value for this column)\"",
")",
",",
"\"Quit, and let me add a default in models.py\"",
",",
"]",
")",
"if",
"choice",
"==",
"2",
":",
"sys",
".",
"exit",
"(",
"3",
")",
"else",
":",
"return",
"self",
".",
"_ask_default",
"(",
")",
"return",
"None"
] | [
142,
4
] | [
159,
19
] | python | en | ['en', 'en', 'en'] | True |
InteractiveMigrationQuestioner.ask_not_null_alteration | (self, field_name, model_name) | Changing a NULL field to NOT NULL. | Changing a NULL field to NOT NULL. | def ask_not_null_alteration(self, field_name, model_name):
"""Changing a NULL field to NOT NULL."""
if not self.dry_run:
choice = self._choice_input(
"You are trying to change the nullable field '%s' on %s to non-nullable "
"without a default; we can't do that (the database needs something to "
"populate existing rows).\n"
"Please select a fix:" % (field_name, model_name),
[
("Provide a one-off default now (will be set on all existing "
"rows with a null value for this column)"),
("Ignore for now, and let me handle existing rows with NULL myself "
"(e.g. because you added a RunPython or RunSQL operation to handle "
"NULL values in a previous data migration)"),
"Quit, and let me add a default in models.py",
]
)
if choice == 2:
return NOT_PROVIDED
elif choice == 3:
sys.exit(3)
else:
return self._ask_default()
return None | [
"def",
"ask_not_null_alteration",
"(",
"self",
",",
"field_name",
",",
"model_name",
")",
":",
"if",
"not",
"self",
".",
"dry_run",
":",
"choice",
"=",
"self",
".",
"_choice_input",
"(",
"\"You are trying to change the nullable field '%s' on %s to non-nullable \"",
"\"without a default; we can't do that (the database needs something to \"",
"\"populate existing rows).\\n\"",
"\"Please select a fix:\"",
"%",
"(",
"field_name",
",",
"model_name",
")",
",",
"[",
"(",
"\"Provide a one-off default now (will be set on all existing \"",
"\"rows with a null value for this column)\"",
")",
",",
"(",
"\"Ignore for now, and let me handle existing rows with NULL myself \"",
"\"(e.g. because you added a RunPython or RunSQL operation to handle \"",
"\"NULL values in a previous data migration)\"",
")",
",",
"\"Quit, and let me add a default in models.py\"",
",",
"]",
")",
"if",
"choice",
"==",
"2",
":",
"return",
"NOT_PROVIDED",
"elif",
"choice",
"==",
"3",
":",
"sys",
".",
"exit",
"(",
"3",
")",
"else",
":",
"return",
"self",
".",
"_ask_default",
"(",
")",
"return",
"None"
] | [
161,
4
] | [
184,
19
] | python | en | ['en', 'en', 'en'] | True |
InteractiveMigrationQuestioner.ask_rename | (self, model_name, old_name, new_name, field_instance) | Was this field really renamed? | Was this field really renamed? | def ask_rename(self, model_name, old_name, new_name, field_instance):
"""Was this field really renamed?"""
msg = "Did you rename %s.%s to %s.%s (a %s)? [y/N]"
return self._boolean_input(msg % (model_name, old_name, model_name, new_name,
field_instance.__class__.__name__), False) | [
"def",
"ask_rename",
"(",
"self",
",",
"model_name",
",",
"old_name",
",",
"new_name",
",",
"field_instance",
")",
":",
"msg",
"=",
"\"Did you rename %s.%s to %s.%s (a %s)? [y/N]\"",
"return",
"self",
".",
"_boolean_input",
"(",
"msg",
"%",
"(",
"model_name",
",",
"old_name",
",",
"model_name",
",",
"new_name",
",",
"field_instance",
".",
"__class__",
".",
"__name__",
")",
",",
"False",
")"
] | [
186,
4
] | [
190,
84
] | python | en | ['en', 'en', 'en'] | True |
InteractiveMigrationQuestioner.ask_rename_model | (self, old_model_state, new_model_state) | Was this model really renamed? | Was this model really renamed? | def ask_rename_model(self, old_model_state, new_model_state):
"""Was this model really renamed?"""
msg = "Did you rename the %s.%s model to %s? [y/N]"
return self._boolean_input(msg % (old_model_state.app_label, old_model_state.name,
new_model_state.name), False) | [
"def",
"ask_rename_model",
"(",
"self",
",",
"old_model_state",
",",
"new_model_state",
")",
":",
"msg",
"=",
"\"Did you rename the %s.%s model to %s? [y/N]\"",
"return",
"self",
".",
"_boolean_input",
"(",
"msg",
"%",
"(",
"old_model_state",
".",
"app_label",
",",
"old_model_state",
".",
"name",
",",
"new_model_state",
".",
"name",
")",
",",
"False",
")"
] | [
192,
4
] | [
196,
71
] | python | en | ['en', 'en', 'en'] | True |
InteractiveMigrationQuestioner.ask_auto_now_add_addition | (self, field_name, model_name) | Adding an auto_now_add field to a model. | Adding an auto_now_add field to a model. | def ask_auto_now_add_addition(self, field_name, model_name):
"""Adding an auto_now_add field to a model."""
if not self.dry_run:
choice = self._choice_input(
"You are trying to add the field '{}' with 'auto_now_add=True' "
"to {} without a default; the database needs something to "
"populate existing rows.\n".format(field_name, model_name),
[
"Provide a one-off default now (will be set on all "
"existing rows)",
"Quit, and let me add a default in models.py",
]
)
if choice == 2:
sys.exit(3)
else:
return self._ask_default(default='timezone.now')
return None | [
"def",
"ask_auto_now_add_addition",
"(",
"self",
",",
"field_name",
",",
"model_name",
")",
":",
"if",
"not",
"self",
".",
"dry_run",
":",
"choice",
"=",
"self",
".",
"_choice_input",
"(",
"\"You are trying to add the field '{}' with 'auto_now_add=True' \"",
"\"to {} without a default; the database needs something to \"",
"\"populate existing rows.\\n\"",
".",
"format",
"(",
"field_name",
",",
"model_name",
")",
",",
"[",
"\"Provide a one-off default now (will be set on all \"",
"\"existing rows)\"",
",",
"\"Quit, and let me add a default in models.py\"",
",",
"]",
")",
"if",
"choice",
"==",
"2",
":",
"sys",
".",
"exit",
"(",
"3",
")",
"else",
":",
"return",
"self",
".",
"_ask_default",
"(",
"default",
"=",
"'timezone.now'",
")",
"return",
"None"
] | [
206,
4
] | [
223,
19
] | python | en | ['en', 'en', 'en'] | True |
upload_large | (file, **options) | Upload large files. | Upload large files. | def upload_large(file, **options):
""" Upload large files. """
if utils.is_remote_url(file):
return upload(file, **options)
if hasattr(file, 'read') and callable(file.read):
file_io = file
else:
file_io = open(file, 'rb')
upload_result = None
with file_io:
upload_id = utils.random_public_id()
current_loc = 0
chunk_size = options.get("chunk_size", UPLOAD_LARGE_CHUNK_SIZE)
file_size = utils.file_io_size(file_io)
file_name = options.get(
"filename",
file_io.name if hasattr(file_io, 'name') and isinstance(file_io.name, str) else "stream")
chunk = file_io.read(chunk_size)
while chunk:
content_range = "bytes {0}-{1}/{2}".format(current_loc, current_loc + len(chunk) - 1, file_size)
current_loc += len(chunk)
http_headers = {"Content-Range": content_range, "X-Unique-Upload-Id": upload_id}
upload_result = upload_large_part((file_name, chunk), http_headers=http_headers, **options)
options["public_id"] = upload_result.get("public_id")
chunk = file_io.read(chunk_size)
return upload_result | [
"def",
"upload_large",
"(",
"file",
",",
"*",
"*",
"options",
")",
":",
"if",
"utils",
".",
"is_remote_url",
"(",
"file",
")",
":",
"return",
"upload",
"(",
"file",
",",
"*",
"*",
"options",
")",
"if",
"hasattr",
"(",
"file",
",",
"'read'",
")",
"and",
"callable",
"(",
"file",
".",
"read",
")",
":",
"file_io",
"=",
"file",
"else",
":",
"file_io",
"=",
"open",
"(",
"file",
",",
"'rb'",
")",
"upload_result",
"=",
"None",
"with",
"file_io",
":",
"upload_id",
"=",
"utils",
".",
"random_public_id",
"(",
")",
"current_loc",
"=",
"0",
"chunk_size",
"=",
"options",
".",
"get",
"(",
"\"chunk_size\"",
",",
"UPLOAD_LARGE_CHUNK_SIZE",
")",
"file_size",
"=",
"utils",
".",
"file_io_size",
"(",
"file_io",
")",
"file_name",
"=",
"options",
".",
"get",
"(",
"\"filename\"",
",",
"file_io",
".",
"name",
"if",
"hasattr",
"(",
"file_io",
",",
"'name'",
")",
"and",
"isinstance",
"(",
"file_io",
".",
"name",
",",
"str",
")",
"else",
"\"stream\"",
")",
"chunk",
"=",
"file_io",
".",
"read",
"(",
"chunk_size",
")",
"while",
"chunk",
":",
"content_range",
"=",
"\"bytes {0}-{1}/{2}\"",
".",
"format",
"(",
"current_loc",
",",
"current_loc",
"+",
"len",
"(",
"chunk",
")",
"-",
"1",
",",
"file_size",
")",
"current_loc",
"+=",
"len",
"(",
"chunk",
")",
"http_headers",
"=",
"{",
"\"Content-Range\"",
":",
"content_range",
",",
"\"X-Unique-Upload-Id\"",
":",
"upload_id",
"}",
"upload_result",
"=",
"upload_large_part",
"(",
"(",
"file_name",
",",
"chunk",
")",
",",
"http_headers",
"=",
"http_headers",
",",
"*",
"*",
"options",
")",
"options",
"[",
"\"public_id\"",
"]",
"=",
"upload_result",
".",
"get",
"(",
"\"public_id\"",
")",
"chunk",
"=",
"file_io",
".",
"read",
"(",
"chunk_size",
")",
"return",
"upload_result"
] | [
67,
0
] | [
102,
24
] | python | en | ['en', 'da', 'en'] | True |
upload_large_part | (file, **options) | Upload large files. | Upload large files. | def upload_large_part(file, **options):
""" Upload large files. """
params = utils.build_upload_params(**options)
if 'resource_type' not in options:
options['resource_type'] = "raw"
return call_cacheable_api("upload", params, file=file, **options) | [
"def",
"upload_large_part",
"(",
"file",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"utils",
".",
"build_upload_params",
"(",
"*",
"*",
"options",
")",
"if",
"'resource_type'",
"not",
"in",
"options",
":",
"options",
"[",
"'resource_type'",
"]",
"=",
"\"raw\"",
"return",
"call_cacheable_api",
"(",
"\"upload\"",
",",
"params",
",",
"file",
"=",
"file",
",",
"*",
"*",
"options",
")"
] | [
105,
0
] | [
112,
69
] | python | en | ['en', 'da', 'en'] | True |
update_metadata | (metadata, public_ids, **options) |
Populates metadata fields with the given values. Existing values will be overwritten.
Any metadata-value pairs given are merged with any existing metadata-value pairs
(an empty value for an existing metadata field clears the value)
:param metadata: A list of custom metadata fields (by external_id) and the values to assign to each
of them.
:param public_ids: An array of Public IDs of assets uploaded to Cloudinary.
:param options: Options such as
*resource_type* (the type of file. Default: image. Valid values: image, raw, or video) and
*type* (The storage type. Default: upload. Valid values: upload, private, or authenticated.)
:return: A list of public IDs that were updated
:rtype: mixed
|
Populates metadata fields with the given values. Existing values will be overwritten. | def update_metadata(metadata, public_ids, **options):
"""
Populates metadata fields with the given values. Existing values will be overwritten.
Any metadata-value pairs given are merged with any existing metadata-value pairs
(an empty value for an existing metadata field clears the value)
:param metadata: A list of custom metadata fields (by external_id) and the values to assign to each
of them.
:param public_ids: An array of Public IDs of assets uploaded to Cloudinary.
:param options: Options such as
*resource_type* (the type of file. Default: image. Valid values: image, raw, or video) and
*type* (The storage type. Default: upload. Valid values: upload, private, or authenticated.)
:return: A list of public IDs that were updated
:rtype: mixed
"""
params = {
"timestamp": utils.now(),
"metadata": utils.encode_context(metadata),
"public_ids": utils.build_array(public_ids),
"type": options.get("type")
}
return call_api("metadata", params, **options) | [
"def",
"update_metadata",
"(",
"metadata",
",",
"public_ids",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"{",
"\"timestamp\"",
":",
"utils",
".",
"now",
"(",
")",
",",
"\"metadata\"",
":",
"utils",
".",
"encode_context",
"(",
"metadata",
")",
",",
"\"public_ids\"",
":",
"utils",
".",
"build_array",
"(",
"public_ids",
")",
",",
"\"type\"",
":",
"options",
".",
"get",
"(",
"\"type\"",
")",
"}",
"return",
"call_api",
"(",
"\"metadata\"",
",",
"params",
",",
"*",
"*",
"options",
")"
] | [
140,
0
] | [
164,
50
] | python | en | ['en', 'error', 'th'] | False |
generate_sprite | (tag=None, urls=None, **options) |
Generates sprites by merging multiple images into a single large image.
See: `Sprite method API reference
<https://cloudinary.com/documentation/image_upload_api_reference#sprite_method>`_
:param tag: The sprite is created from all images with this tag. If not set - `urls` parameter is required
:type tag: str
:param urls: List of URLs to create a sprite from. Can only be used if `tag` is not set
:type urls: list
:param options: Additional options
:type options: dict, optional
:return: Dictionary with meta information URLs of generated sprite resources
:rtype: dict
|
Generates sprites by merging multiple images into a single large image. | def generate_sprite(tag=None, urls=None, **options):
"""
Generates sprites by merging multiple images into a single large image.
See: `Sprite method API reference
<https://cloudinary.com/documentation/image_upload_api_reference#sprite_method>`_
:param tag: The sprite is created from all images with this tag. If not set - `urls` parameter is required
:type tag: str
:param urls: List of URLs to create a sprite from. Can only be used if `tag` is not set
:type urls: list
:param options: Additional options
:type options: dict, optional
:return: Dictionary with meta information URLs of generated sprite resources
:rtype: dict
"""
params = utils.build_multi_and_sprite_params(tag=tag, urls=urls, **options)
return call_api("sprite", params, **options) | [
"def",
"generate_sprite",
"(",
"tag",
"=",
"None",
",",
"urls",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"utils",
".",
"build_multi_and_sprite_params",
"(",
"tag",
"=",
"tag",
",",
"urls",
"=",
"urls",
",",
"*",
"*",
"options",
")",
"return",
"call_api",
"(",
"\"sprite\"",
",",
"params",
",",
"*",
"*",
"options",
")"
] | [
184,
0
] | [
201,
48
] | python | en | ['en', 'error', 'th'] | False |
download_generated_sprite | (tag=None, urls=None, **options) |
Returns signed URL for the sprite endpoint with `mode=download`
:param tag: The sprite is created from all images with this tag. If not set - `urls` parameter is required
:type tag: str
:param urls: List of URLs to create a sprite from. Can only be used if `tag` is not set
:type urls: list
:param options: Additional options
:type options: dict, optional
:return: The signed URL to download sprite
:rtype: str
|
Returns signed URL for the sprite endpoint with `mode=download` | def download_generated_sprite(tag=None, urls=None, **options):
"""
Returns signed URL for the sprite endpoint with `mode=download`
:param tag: The sprite is created from all images with this tag. If not set - `urls` parameter is required
:type tag: str
:param urls: List of URLs to create a sprite from. Can only be used if `tag` is not set
:type urls: list
:param options: Additional options
:type options: dict, optional
:return: The signed URL to download sprite
:rtype: str
"""
params = utils.build_multi_and_sprite_params(tag=tag, urls=urls, **options)
return utils.cloudinary_api_download_url(action="sprite", params=params, **options) | [
"def",
"download_generated_sprite",
"(",
"tag",
"=",
"None",
",",
"urls",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"utils",
".",
"build_multi_and_sprite_params",
"(",
"tag",
"=",
"tag",
",",
"urls",
"=",
"urls",
",",
"*",
"*",
"options",
")",
"return",
"utils",
".",
"cloudinary_api_download_url",
"(",
"action",
"=",
"\"sprite\"",
",",
"params",
"=",
"params",
",",
"*",
"*",
"options",
")"
] | [
204,
0
] | [
218,
87
] | python | en | ['en', 'error', 'th'] | False |
multi | (tag=None, urls=None, **options) |
Creates either a single animated image, video or a PDF.
See: `Upload method API reference
<https://cloudinary.com/documentation/image_upload_api_reference#multi_method>`_
:param tag: The animated image, video or PDF is created from all images with this tag.
If not set - `urls` parameter is required
:type tag: str
:param urls: List of URLs to create an animated image, video or PDF from. Can only be used if `tag` is not set
:type urls: list
:param options: Additional options
:type options: dict, optional
:return: Dictionary with meta information URLs of the generated file
:rtype: dict
|
Creates either a single animated image, video or a PDF. | def multi(tag=None, urls=None, **options):
"""
Creates either a single animated image, video or a PDF.
See: `Upload method API reference
<https://cloudinary.com/documentation/image_upload_api_reference#multi_method>`_
:param tag: The animated image, video or PDF is created from all images with this tag.
If not set - `urls` parameter is required
:type tag: str
:param urls: List of URLs to create an animated image, video or PDF from. Can only be used if `tag` is not set
:type urls: list
:param options: Additional options
:type options: dict, optional
:return: Dictionary with meta information URLs of the generated file
:rtype: dict
"""
params = utils.build_multi_and_sprite_params(tag=tag, urls=urls, **options)
return call_api("multi", params, **options) | [
"def",
"multi",
"(",
"tag",
"=",
"None",
",",
"urls",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"utils",
".",
"build_multi_and_sprite_params",
"(",
"tag",
"=",
"tag",
",",
"urls",
"=",
"urls",
",",
"*",
"*",
"options",
")",
"return",
"call_api",
"(",
"\"multi\"",
",",
"params",
",",
"*",
"*",
"options",
")"
] | [
221,
0
] | [
239,
47
] | python | en | ['en', 'error', 'th'] | False |
download_multi | (tag=None, urls=None, **options) |
Returns signed URL for the multi endpoint with `mode=download`
:param tag: The sprite is created from all images with this tag. If not set - `urls` parameter is required
:type tag: str
:param urls: List of URLs to create a sprite from. Can only be used if `tag` is not set
:type urls: list
:param options: Additional options
:type options: dict, optional
:return: The signed URL to download multi
:rtype: str
|
Returns signed URL for the multi endpoint with `mode=download` | def download_multi(tag=None, urls=None, **options):
"""
Returns signed URL for the multi endpoint with `mode=download`
:param tag: The sprite is created from all images with this tag. If not set - `urls` parameter is required
:type tag: str
:param urls: List of URLs to create a sprite from. Can only be used if `tag` is not set
:type urls: list
:param options: Additional options
:type options: dict, optional
:return: The signed URL to download multi
:rtype: str
"""
params = utils.build_multi_and_sprite_params(tag=tag, urls=urls, **options)
return utils.cloudinary_api_download_url(action="multi", params=params, **options) | [
"def",
"download_multi",
"(",
"tag",
"=",
"None",
",",
"urls",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"utils",
".",
"build_multi_and_sprite_params",
"(",
"tag",
"=",
"tag",
",",
"urls",
"=",
"urls",
",",
"*",
"*",
"options",
")",
"return",
"utils",
".",
"cloudinary_api_download_url",
"(",
"action",
"=",
"\"multi\"",
",",
"params",
"=",
"params",
",",
"*",
"*",
"options",
")"
] | [
242,
0
] | [
256,
86
] | python | en | ['en', 'error', 'th'] | False |
remove_all_tags | (public_ids, **options) |
Remove all tags from the specified public IDs.
:param public_ids: the public IDs of the resources to update
:param options: additional options passed to the request
:return: dictionary with a list of public IDs that were updated
|
Remove all tags from the specified public IDs. | def remove_all_tags(public_ids, **options):
"""
Remove all tags from the specified public IDs.
:param public_ids: the public IDs of the resources to update
:param options: additional options passed to the request
:return: dictionary with a list of public IDs that were updated
"""
return call_tags_api(None, "remove_all", public_ids, **options) | [
"def",
"remove_all_tags",
"(",
"public_ids",
",",
"*",
"*",
"options",
")",
":",
"return",
"call_tags_api",
"(",
"None",
",",
"\"remove_all\"",
",",
"public_ids",
",",
"*",
"*",
"options",
")"
] | [
285,
0
] | [
294,
67
] | python | en | ['en', 'error', 'th'] | False |
add_context | (context, public_ids, **options) |
Add a context keys and values. If a particular key already exists, the value associated with the key is updated.
:param context: dictionary of context
:param public_ids: the public IDs of the resources to update
:param options: additional options passed to the request
:return: dictionary with a list of public IDs that were updated
|
Add a context keys and values. If a particular key already exists, the value associated with the key is updated. | def add_context(context, public_ids, **options):
"""
Add a context keys and values. If a particular key already exists, the value associated with the key is updated.
:param context: dictionary of context
:param public_ids: the public IDs of the resources to update
:param options: additional options passed to the request
:return: dictionary with a list of public IDs that were updated
"""
return call_context_api(context, "add", public_ids, **options) | [
"def",
"add_context",
"(",
"context",
",",
"public_ids",
",",
"*",
"*",
"options",
")",
":",
"return",
"call_context_api",
"(",
"context",
",",
"\"add\"",
",",
"public_ids",
",",
"*",
"*",
"options",
")"
] | [
297,
0
] | [
307,
66
] | python | en | ['en', 'error', 'th'] | False |
remove_all_context | (public_ids, **options) |
Remove all custom context from the specified public IDs.
:param public_ids: the public IDs of the resources to update
:param options: additional options passed to the request
:return: dictionary with a list of public IDs that were updated
|
Remove all custom context from the specified public IDs. | def remove_all_context(public_ids, **options):
"""
Remove all custom context from the specified public IDs.
:param public_ids: the public IDs of the resources to update
:param options: additional options passed to the request
:return: dictionary with a list of public IDs that were updated
"""
return call_context_api(None, "remove_all", public_ids, **options) | [
"def",
"remove_all_context",
"(",
"public_ids",
",",
"*",
"*",
"options",
")",
":",
"return",
"call_context_api",
"(",
"None",
",",
"\"remove_all\"",
",",
"public_ids",
",",
"*",
"*",
"options",
")"
] | [
310,
0
] | [
319,
70
] | python | en | ['en', 'error', 'th'] | False |
_save_responsive_breakpoints_to_cache | (result) |
Saves responsive breakpoints parsed from upload result to cache
:param result: Upload result
|
Saves responsive breakpoints parsed from upload result to cache | def _save_responsive_breakpoints_to_cache(result):
"""
Saves responsive breakpoints parsed from upload result to cache
:param result: Upload result
"""
if "responsive_breakpoints" not in result:
return
if "public_id" not in result:
# We have some faulty result, nothing to cache
return
options = dict((k, result[k]) for k in ["type", "resource_type"] if k in result)
for transformation in result.get("responsive_breakpoints", []):
options["raw_transformation"] = transformation.get("transformation", "")
options["format"] = os.path.splitext(transformation["breakpoints"][0]["url"])[1][1:]
breakpoints = [bp["width"] for bp in transformation["breakpoints"]]
responsive_breakpoints_cache_instance.set(result["public_id"], breakpoints, **options) | [
"def",
"_save_responsive_breakpoints_to_cache",
"(",
"result",
")",
":",
"if",
"\"responsive_breakpoints\"",
"not",
"in",
"result",
":",
"return",
"if",
"\"public_id\"",
"not",
"in",
"result",
":",
"# We have some faulty result, nothing to cache",
"return",
"options",
"=",
"dict",
"(",
"(",
"k",
",",
"result",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"[",
"\"type\"",
",",
"\"resource_type\"",
"]",
"if",
"k",
"in",
"result",
")",
"for",
"transformation",
"in",
"result",
".",
"get",
"(",
"\"responsive_breakpoints\"",
",",
"[",
"]",
")",
":",
"options",
"[",
"\"raw_transformation\"",
"]",
"=",
"transformation",
".",
"get",
"(",
"\"transformation\"",
",",
"\"\"",
")",
"options",
"[",
"\"format\"",
"]",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"transformation",
"[",
"\"breakpoints\"",
"]",
"[",
"0",
"]",
"[",
"\"url\"",
"]",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
"breakpoints",
"=",
"[",
"bp",
"[",
"\"width\"",
"]",
"for",
"bp",
"in",
"transformation",
"[",
"\"breakpoints\"",
"]",
"]",
"responsive_breakpoints_cache_instance",
".",
"set",
"(",
"result",
"[",
"\"public_id\"",
"]",
",",
"breakpoints",
",",
"*",
"*",
"options",
")"
] | [
365,
0
] | [
384,
94
] | python | en | ['en', 'error', 'th'] | False |
call_cacheable_api | (action, params, http_headers=None, return_error=False, unsigned=False, file=None, timeout=None,
**options) |
Calls Upload API and saves results to cache (if enabled)
|
Calls Upload API and saves results to cache (if enabled)
| def call_cacheable_api(action, params, http_headers=None, return_error=False, unsigned=False, file=None, timeout=None,
**options):
"""
Calls Upload API and saves results to cache (if enabled)
"""
result = call_api(action, params, http_headers, return_error, unsigned, file, timeout, **options)
if "use_cache" in options or cloudinary.config().use_cache:
_save_responsive_breakpoints_to_cache(result)
return result | [
"def",
"call_cacheable_api",
"(",
"action",
",",
"params",
",",
"http_headers",
"=",
"None",
",",
"return_error",
"=",
"False",
",",
"unsigned",
"=",
"False",
",",
"file",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"result",
"=",
"call_api",
"(",
"action",
",",
"params",
",",
"http_headers",
",",
"return_error",
",",
"unsigned",
",",
"file",
",",
"timeout",
",",
"*",
"*",
"options",
")",
"if",
"\"use_cache\"",
"in",
"options",
"or",
"cloudinary",
".",
"config",
"(",
")",
".",
"use_cache",
":",
"_save_responsive_breakpoints_to_cache",
"(",
"result",
")",
"return",
"result"
] | [
387,
0
] | [
398,
17
] | python | en | ['en', 'error', 'th'] | False |
Link.__init__ | (
self,
url: str,
comes_from: Optional[Union[str, "HTMLPage"]] = None,
requires_python: Optional[str] = None,
yanked_reason: Optional[str] = None,
cache_link_parsing: bool = True,
) |
:param url: url of the resource pointed to (href of the link)
:param comes_from: instance of HTMLPage where the link was found,
or string.
:param requires_python: String containing the `Requires-Python`
metadata field, specified in PEP 345. This may be specified by
a data-requires-python attribute in the HTML link tag, as
described in PEP 503.
:param yanked_reason: the reason the file has been yanked, if the
file has been yanked, or None if the file hasn't been yanked.
This is the value of the "data-yanked" attribute, if present, in
a simple repository HTML link. If the file has been yanked but
no reason was provided, this should be the empty string. See
PEP 592 for more information and the specification.
:param cache_link_parsing: A flag that is used elsewhere to determine
whether resources retrieved from this link
should be cached. PyPI index urls should
generally have this set to False, for
example.
|
:param url: url of the resource pointed to (href of the link)
:param comes_from: instance of HTMLPage where the link was found,
or string.
:param requires_python: String containing the `Requires-Python`
metadata field, specified in PEP 345. This may be specified by
a data-requires-python attribute in the HTML link tag, as
described in PEP 503.
:param yanked_reason: the reason the file has been yanked, if the
file has been yanked, or None if the file hasn't been yanked.
This is the value of the "data-yanked" attribute, if present, in
a simple repository HTML link. If the file has been yanked but
no reason was provided, this should be the empty string. See
PEP 592 for more information and the specification.
:param cache_link_parsing: A flag that is used elsewhere to determine
whether resources retrieved from this link
should be cached. PyPI index urls should
generally have this set to False, for
example.
| def __init__(
self,
url: str,
comes_from: Optional[Union[str, "HTMLPage"]] = None,
requires_python: Optional[str] = None,
yanked_reason: Optional[str] = None,
cache_link_parsing: bool = True,
) -> None:
"""
:param url: url of the resource pointed to (href of the link)
:param comes_from: instance of HTMLPage where the link was found,
or string.
:param requires_python: String containing the `Requires-Python`
metadata field, specified in PEP 345. This may be specified by
a data-requires-python attribute in the HTML link tag, as
described in PEP 503.
:param yanked_reason: the reason the file has been yanked, if the
file has been yanked, or None if the file hasn't been yanked.
This is the value of the "data-yanked" attribute, if present, in
a simple repository HTML link. If the file has been yanked but
no reason was provided, this should be the empty string. See
PEP 592 for more information and the specification.
:param cache_link_parsing: A flag that is used elsewhere to determine
whether resources retrieved from this link
should be cached. PyPI index urls should
generally have this set to False, for
example.
"""
# url can be a UNC windows share
if url.startswith('\\\\'):
url = path_to_url(url)
self._parsed_url = urllib.parse.urlsplit(url)
# Store the url as a private attribute to prevent accidentally
# trying to set a new value.
self._url = url
self.comes_from = comes_from
self.requires_python = requires_python if requires_python else None
self.yanked_reason = yanked_reason
super().__init__(key=url, defining_class=Link)
self.cache_link_parsing = cache_link_parsing | [
"def",
"__init__",
"(",
"self",
",",
"url",
":",
"str",
",",
"comes_from",
":",
"Optional",
"[",
"Union",
"[",
"str",
",",
"\"HTMLPage\"",
"]",
"]",
"=",
"None",
",",
"requires_python",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"yanked_reason",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"cache_link_parsing",
":",
"bool",
"=",
"True",
",",
")",
"->",
"None",
":",
"# url can be a UNC windows share",
"if",
"url",
".",
"startswith",
"(",
"'\\\\\\\\'",
")",
":",
"url",
"=",
"path_to_url",
"(",
"url",
")",
"self",
".",
"_parsed_url",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"url",
")",
"# Store the url as a private attribute to prevent accidentally",
"# trying to set a new value.",
"self",
".",
"_url",
"=",
"url",
"self",
".",
"comes_from",
"=",
"comes_from",
"self",
".",
"requires_python",
"=",
"requires_python",
"if",
"requires_python",
"else",
"None",
"self",
".",
"yanked_reason",
"=",
"yanked_reason",
"super",
"(",
")",
".",
"__init__",
"(",
"key",
"=",
"url",
",",
"defining_class",
"=",
"Link",
")",
"self",
".",
"cache_link_parsing",
"=",
"cache_link_parsing"
] | [
40,
4
] | [
84,
52
] | python | en | ['en', 'error', 'th'] | False |
Link.netloc | (self) |
This can contain auth information.
|
This can contain auth information.
| def netloc(self) -> str:
"""
This can contain auth information.
"""
return self._parsed_url.netloc | [
"def",
"netloc",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_parsed_url",
".",
"netloc"
] | [
127,
4
] | [
131,
38
] | python | en | ['en', 'error', 'th'] | False |
Link.is_hash_allowed | (self, hashes: Optional[Hashes]) |
Return True if the link has a hash and it is allowed.
|
Return True if the link has a hash and it is allowed.
| def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool:
"""
Return True if the link has a hash and it is allowed.
"""
if hashes is None or not self.has_hash:
return False
# Assert non-None so mypy knows self.hash_name and self.hash are str.
assert self.hash_name is not None
assert self.hash is not None
return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash) | [
"def",
"is_hash_allowed",
"(",
"self",
",",
"hashes",
":",
"Optional",
"[",
"Hashes",
"]",
")",
"->",
"bool",
":",
"if",
"hashes",
"is",
"None",
"or",
"not",
"self",
".",
"has_hash",
":",
"return",
"False",
"# Assert non-None so mypy knows self.hash_name and self.hash are str.",
"assert",
"self",
".",
"hash_name",
"is",
"not",
"None",
"assert",
"self",
".",
"hash",
"is",
"not",
"None",
"return",
"hashes",
".",
"is_hash_allowed",
"(",
"self",
".",
"hash_name",
",",
"hex_digest",
"=",
"self",
".",
"hash",
")"
] | [
214,
4
] | [
224,
75
] | python | en | ['en', 'error', 'th'] | False |
SimpleTemplateResponse.__getstate__ | (self) |
Raise an exception if trying to pickle an unrendered response. Pickle
only rendered data, not the data used to construct the response.
|
Raise an exception if trying to pickle an unrendered response. Pickle
only rendered data, not the data used to construct the response.
| def __getstate__(self):
"""
Raise an exception if trying to pickle an unrendered response. Pickle
only rendered data, not the data used to construct the response.
"""
obj_dict = self.__dict__.copy()
if not self._is_rendered:
raise ContentNotRenderedError('The response content must be '
'rendered before it can be pickled.')
for attr in self.rendering_attrs:
if attr in obj_dict:
del obj_dict[attr]
return obj_dict | [
"def",
"__getstate__",
"(",
"self",
")",
":",
"obj_dict",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"if",
"not",
"self",
".",
"_is_rendered",
":",
"raise",
"ContentNotRenderedError",
"(",
"'The response content must be '",
"'rendered before it can be pickled.'",
")",
"for",
"attr",
"in",
"self",
".",
"rendering_attrs",
":",
"if",
"attr",
"in",
"obj_dict",
":",
"del",
"obj_dict",
"[",
"attr",
"]",
"return",
"obj_dict"
] | [
44,
4
] | [
57,
23
] | python | en | ['en', 'error', 'th'] | False |
SimpleTemplateResponse.resolve_template | (self, template) | Accept a template object, path-to-template, or list of paths. | Accept a template object, path-to-template, or list of paths. | def resolve_template(self, template):
"""Accept a template object, path-to-template, or list of paths."""
if isinstance(template, (list, tuple)):
return select_template(template, using=self.using)
elif isinstance(template, str):
return get_template(template, using=self.using)
else:
return template | [
"def",
"resolve_template",
"(",
"self",
",",
"template",
")",
":",
"if",
"isinstance",
"(",
"template",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"select_template",
"(",
"template",
",",
"using",
"=",
"self",
".",
"using",
")",
"elif",
"isinstance",
"(",
"template",
",",
"str",
")",
":",
"return",
"get_template",
"(",
"template",
",",
"using",
"=",
"self",
".",
"using",
")",
"else",
":",
"return",
"template"
] | [
59,
4
] | [
66,
27
] | python | en | ['en', 'en', 'en'] | True |
SimpleTemplateResponse.rendered_content | (self) | Return the freshly rendered content for the template and context
described by the TemplateResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly using the value of this property.
| Return the freshly rendered content for the template and context
described by the TemplateResponse. | def rendered_content(self):
"""Return the freshly rendered content for the template and context
described by the TemplateResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly using the value of this property.
"""
template = self.resolve_template(self.template_name)
context = self.resolve_context(self.context_data)
return template.render(context, self._request) | [
"def",
"rendered_content",
"(",
"self",
")",
":",
"template",
"=",
"self",
".",
"resolve_template",
"(",
"self",
".",
"template_name",
")",
"context",
"=",
"self",
".",
"resolve_context",
"(",
"self",
".",
"context_data",
")",
"return",
"template",
".",
"render",
"(",
"context",
",",
"self",
".",
"_request",
")"
] | [
72,
4
] | [
82,
54
] | python | en | ['en', 'en', 'en'] | True |
SimpleTemplateResponse.add_post_render_callback | (self, callback) | Add a new post-rendering callback.
If the response has already been rendered,
invoke the callback immediately.
| Add a new post-rendering callback. | def add_post_render_callback(self, callback):
"""Add a new post-rendering callback.
If the response has already been rendered,
invoke the callback immediately.
"""
if self._is_rendered:
callback(self)
else:
self._post_render_callbacks.append(callback) | [
"def",
"add_post_render_callback",
"(",
"self",
",",
"callback",
")",
":",
"if",
"self",
".",
"_is_rendered",
":",
"callback",
"(",
"self",
")",
"else",
":",
"self",
".",
"_post_render_callbacks",
".",
"append",
"(",
"callback",
")"
] | [
84,
4
] | [
93,
56
] | python | en | ['en', 'en', 'en'] | True |
SimpleTemplateResponse.render | (self) | Render (thereby finalizing) the content of the response.
If the content has already been rendered, this is a no-op.
Return the baked response instance.
| Render (thereby finalizing) the content of the response. | def render(self):
"""Render (thereby finalizing) the content of the response.
If the content has already been rendered, this is a no-op.
Return the baked response instance.
"""
retval = self
if not self._is_rendered:
self.content = self.rendered_content
for post_callback in self._post_render_callbacks:
newretval = post_callback(retval)
if newretval is not None:
retval = newretval
return retval | [
"def",
"render",
"(",
"self",
")",
":",
"retval",
"=",
"self",
"if",
"not",
"self",
".",
"_is_rendered",
":",
"self",
".",
"content",
"=",
"self",
".",
"rendered_content",
"for",
"post_callback",
"in",
"self",
".",
"_post_render_callbacks",
":",
"newretval",
"=",
"post_callback",
"(",
"retval",
")",
"if",
"newretval",
"is",
"not",
"None",
":",
"retval",
"=",
"newretval",
"return",
"retval"
] | [
95,
4
] | [
109,
21
] | python | en | ['en', 'en', 'en'] | True |
SimpleTemplateResponse.content | (self, value) | Set the content for the response. | Set the content for the response. | def content(self, value):
"""Set the content for the response."""
HttpResponse.content.fset(self, value)
self._is_rendered = True | [
"def",
"content",
"(",
"self",
",",
"value",
")",
":",
"HttpResponse",
".",
"content",
".",
"fset",
"(",
"self",
",",
"value",
")",
"self",
".",
"_is_rendered",
"=",
"True"
] | [
131,
4
] | [
134,
32
] | python | en | ['en', 'en', 'en'] | True |
RequestException.__init__ | (self, *args, **kwargs) | Initialize RequestException with `request` and `response` objects. | Initialize RequestException with `request` and `response` objects. | def __init__(self, *args, **kwargs):
"""Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
hasattr(response, 'request')):
self.request = self.response.request
super(RequestException, self).__init__(*args, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"kwargs",
".",
"pop",
"(",
"'response'",
",",
"None",
")",
"self",
".",
"response",
"=",
"response",
"self",
".",
"request",
"=",
"kwargs",
".",
"pop",
"(",
"'request'",
",",
"None",
")",
"if",
"(",
"response",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"request",
"and",
"hasattr",
"(",
"response",
",",
"'request'",
")",
")",
":",
"self",
".",
"request",
"=",
"self",
".",
"response",
".",
"request",
"super",
"(",
"RequestException",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
16,
4
] | [
24,
63
] | python | en | ['en', 'en', 'en'] | True |
certs | () | Returns a dictionary of current Google public key certificates for
validating Google-signed JWTs. Since these change rarely, the result
is cached on first request for faster subsequent responses.
| Returns a dictionary of current Google public key certificates for
validating Google-signed JWTs. Since these change rarely, the result
is cached on first request for faster subsequent responses.
| def certs():
"""Returns a dictionary of current Google public key certificates for
validating Google-signed JWTs. Since these change rarely, the result
is cached on first request for faster subsequent responses.
"""
import requests
global CERTS
if CERTS is None:
response = requests.get(
'https://www.gstatic.com/iap/verify/public_key'
)
CERTS = response.json()
return CERTS | [
"def",
"certs",
"(",
")",
":",
"import",
"requests",
"global",
"CERTS",
"if",
"CERTS",
"is",
"None",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"'https://www.gstatic.com/iap/verify/public_key'",
")",
"CERTS",
"=",
"response",
".",
"json",
"(",
")",
"return",
"CERTS"
] | [
25,
0
] | [
38,
16
] | python | en | ['en', 'en', 'en'] | True |
get_metadata | (item_name) | Returns a string with the project metadata value for the item_name.
See https://cloud.google.com/compute/docs/storing-retrieving-metadata for
possible item_name values.
| Returns a string with the project metadata value for the item_name.
See https://cloud.google.com/compute/docs/storing-retrieving-metadata for
possible item_name values.
| def get_metadata(item_name):
"""Returns a string with the project metadata value for the item_name.
See https://cloud.google.com/compute/docs/storing-retrieving-metadata for
possible item_name values.
"""
import requests
endpoint = 'http://metadata.google.internal'
path = '/computeMetadata/v1/project/'
path += item_name
response = requests.get(
'{}{}'.format(endpoint, path),
headers={'Metadata-Flavor': 'Google'}
)
metadata = response.text
return metadata | [
"def",
"get_metadata",
"(",
"item_name",
")",
":",
"import",
"requests",
"endpoint",
"=",
"'http://metadata.google.internal'",
"path",
"=",
"'/computeMetadata/v1/project/'",
"path",
"+=",
"item_name",
"response",
"=",
"requests",
".",
"get",
"(",
"'{}{}'",
".",
"format",
"(",
"endpoint",
",",
"path",
")",
",",
"headers",
"=",
"{",
"'Metadata-Flavor'",
":",
"'Google'",
"}",
")",
"metadata",
"=",
"response",
".",
"text",
"return",
"metadata"
] | [
43,
0
] | [
58,
19
] | python | en | ['en', 'en', 'en'] | True |
audience | () | Returns the audience value (the JWT 'aud' property) for the current
running instance. Since this involves a metadata lookup, the result is
cached when first requested for faster future responses.
| Returns the audience value (the JWT 'aud' property) for the current
running instance. Since this involves a metadata lookup, the result is
cached when first requested for faster future responses.
| def audience():
"""Returns the audience value (the JWT 'aud' property) for the current
running instance. Since this involves a metadata lookup, the result is
cached when first requested for faster future responses.
"""
global AUDIENCE
if AUDIENCE is None:
project_number = get_metadata('numeric-project-id')
project_id = get_metadata('project-id')
AUDIENCE = '/projects/{}/apps/{}'.format(
project_number, project_id
)
return AUDIENCE | [
"def",
"audience",
"(",
")",
":",
"global",
"AUDIENCE",
"if",
"AUDIENCE",
"is",
"None",
":",
"project_number",
"=",
"get_metadata",
"(",
"'numeric-project-id'",
")",
"project_id",
"=",
"get_metadata",
"(",
"'project-id'",
")",
"AUDIENCE",
"=",
"'/projects/{}/apps/{}'",
".",
"format",
"(",
"project_number",
",",
"project_id",
")",
"return",
"AUDIENCE"
] | [
63,
0
] | [
75,
19
] | python | en | ['en', 'en', 'en'] | True |
validate_assertion | (assertion) | Checks that the JWT assertion is valid (properly signed, for the
correct audience) and if so, returns strings for the requesting user's
email and a persistent user ID. If not valid, returns None for each field.
| Checks that the JWT assertion is valid (properly signed, for the
correct audience) and if so, returns strings for the requesting user's
email and a persistent user ID. If not valid, returns None for each field.
| def validate_assertion(assertion):
"""Checks that the JWT assertion is valid (properly signed, for the
correct audience) and if so, returns strings for the requesting user's
email and a persistent user ID. If not valid, returns None for each field.
"""
from jose import jwt
try:
info = jwt.decode(
assertion,
certs(),
algorithms=['ES256'],
audience=audience()
)
return info['email'], info['sub']
except Exception as e:
print('Failed to validate assertion: {}'.format(e), file=sys.stderr)
return None, None | [
"def",
"validate_assertion",
"(",
"assertion",
")",
":",
"from",
"jose",
"import",
"jwt",
"try",
":",
"info",
"=",
"jwt",
".",
"decode",
"(",
"assertion",
",",
"certs",
"(",
")",
",",
"algorithms",
"=",
"[",
"'ES256'",
"]",
",",
"audience",
"=",
"audience",
"(",
")",
")",
"return",
"info",
"[",
"'email'",
"]",
",",
"info",
"[",
"'sub'",
"]",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"'Failed to validate assertion: {}'",
".",
"format",
"(",
"e",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
"None",
",",
"None"
] | [
80,
0
] | [
97,
25
] | python | en | ['en', 'en', 'en'] | True |
UserProfileSerializer.create | (self, validated_data) | Create and return a new user | Create and return a new user | def create(self, validated_data):
"""Create and return a new user"""
user = models.UserProfile.objects.create_user(
email=validated_data['email'],
name=validated_data['name'],
password=validated_data['password']
)
return user | [
"def",
"create",
"(",
"self",
",",
"validated_data",
")",
":",
"user",
"=",
"models",
".",
"UserProfile",
".",
"objects",
".",
"create_user",
"(",
"email",
"=",
"validated_data",
"[",
"'email'",
"]",
",",
"name",
"=",
"validated_data",
"[",
"'name'",
"]",
",",
"password",
"=",
"validated_data",
"[",
"'password'",
"]",
")",
"return",
"user"
] | [
23,
4
] | [
31,
19
] | python | en | ['en', 'en', 'en'] | True |
parse_docstring | (docstring) |
Parse out the parts of a docstring. Return (title, body, metadata).
|
Parse out the parts of a docstring. Return (title, body, metadata).
| def parse_docstring(docstring):
"""
Parse out the parts of a docstring. Return (title, body, metadata).
"""
if not docstring:
return '', '', {}
docstring = cleandoc(docstring)
parts = re.split(r'\n{2,}', docstring)
title = parts[0]
if len(parts) == 1:
body = ''
metadata = {}
else:
parser = HeaderParser()
try:
metadata = parser.parsestr(parts[-1])
except HeaderParseError:
metadata = {}
body = "\n\n".join(parts[1:])
else:
metadata = dict(metadata.items())
if metadata:
body = "\n\n".join(parts[1:-1])
else:
body = "\n\n".join(parts[1:])
return title, body, metadata | [
"def",
"parse_docstring",
"(",
"docstring",
")",
":",
"if",
"not",
"docstring",
":",
"return",
"''",
",",
"''",
",",
"{",
"}",
"docstring",
"=",
"cleandoc",
"(",
"docstring",
")",
"parts",
"=",
"re",
".",
"split",
"(",
"r'\\n{2,}'",
",",
"docstring",
")",
"title",
"=",
"parts",
"[",
"0",
"]",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"body",
"=",
"''",
"metadata",
"=",
"{",
"}",
"else",
":",
"parser",
"=",
"HeaderParser",
"(",
")",
"try",
":",
"metadata",
"=",
"parser",
".",
"parsestr",
"(",
"parts",
"[",
"-",
"1",
"]",
")",
"except",
"HeaderParseError",
":",
"metadata",
"=",
"{",
"}",
"body",
"=",
"\"\\n\\n\"",
".",
"join",
"(",
"parts",
"[",
"1",
":",
"]",
")",
"else",
":",
"metadata",
"=",
"dict",
"(",
"metadata",
".",
"items",
"(",
")",
")",
"if",
"metadata",
":",
"body",
"=",
"\"\\n\\n\"",
".",
"join",
"(",
"parts",
"[",
"1",
":",
"-",
"1",
"]",
")",
"else",
":",
"body",
"=",
"\"\\n\\n\"",
".",
"join",
"(",
"parts",
"[",
"1",
":",
"]",
")",
"return",
"title",
",",
"body",
",",
"metadata"
] | [
27,
0
] | [
52,
32
] | python | en | ['en', 'error', 'th'] | False |
parse_rst | (text, default_reference_context, thing_being_parsed=None) |
Convert the string from reST to an XHTML fragment.
|
Convert the string from reST to an XHTML fragment.
| def parse_rst(text, default_reference_context, thing_being_parsed=None):
"""
Convert the string from reST to an XHTML fragment.
"""
overrides = {
'doctitle_xform': True,
'initial_header_level': 3,
"default_reference_context": default_reference_context,
"link_base": reverse('django-admindocs-docroot').rstrip('/'),
'raw_enabled': False,
'file_insertion_enabled': False,
}
thing_being_parsed = thing_being_parsed and '<%s>' % thing_being_parsed
# Wrap ``text`` in some reST that sets the default role to ``cmsreference``,
# then restores it.
source = """
.. default-role:: cmsreference
%s
.. default-role::
"""
parts = docutils.core.publish_parts(
source % text,
source_path=thing_being_parsed, destination_path=None,
writer_name='html', settings_overrides=overrides,
)
return mark_safe(parts['fragment']) | [
"def",
"parse_rst",
"(",
"text",
",",
"default_reference_context",
",",
"thing_being_parsed",
"=",
"None",
")",
":",
"overrides",
"=",
"{",
"'doctitle_xform'",
":",
"True",
",",
"'initial_header_level'",
":",
"3",
",",
"\"default_reference_context\"",
":",
"default_reference_context",
",",
"\"link_base\"",
":",
"reverse",
"(",
"'django-admindocs-docroot'",
")",
".",
"rstrip",
"(",
"'/'",
")",
",",
"'raw_enabled'",
":",
"False",
",",
"'file_insertion_enabled'",
":",
"False",
",",
"}",
"thing_being_parsed",
"=",
"thing_being_parsed",
"and",
"'<%s>'",
"%",
"thing_being_parsed",
"# Wrap ``text`` in some reST that sets the default role to ``cmsreference``,",
"# then restores it.",
"source",
"=",
"\"\"\"\n.. default-role:: cmsreference\n\n%s\n\n.. default-role::\n\"\"\"",
"parts",
"=",
"docutils",
".",
"core",
".",
"publish_parts",
"(",
"source",
"%",
"text",
",",
"source_path",
"=",
"thing_being_parsed",
",",
"destination_path",
"=",
"None",
",",
"writer_name",
"=",
"'html'",
",",
"settings_overrides",
"=",
"overrides",
",",
")",
"return",
"mark_safe",
"(",
"parts",
"[",
"'fragment'",
"]",
")"
] | [
55,
0
] | [
82,
39
] | python | en | ['en', 'error', 'th'] | False |
replace_named_groups | (pattern) | r"""
Find named groups in `pattern` and replace them with the group name. E.g.,
1. ^(?P<a>\w+)/b/(\w+)$ ==> ^<a>/b/(\w+)$
2. ^(?P<a>\w+)/b/(?P<c>\w+)/$ ==> ^<a>/b/<c>/$
3. ^(?P<a>\w+)/b/(\w+) ==> ^<a>/b/(\w+)
4. ^(?P<a>\w+)/b/(?P<c>\w+) ==> ^<a>/b/<c>
| r"""
Find named groups in `pattern` and replace them with the group name. E.g.,
1. ^(?P<a>\w+)/b/(\w+)$ ==> ^<a>/b/(\w+)$
2. ^(?P<a>\w+)/b/(?P<c>\w+)/$ ==> ^<a>/b/<c>/$
3. ^(?P<a>\w+)/b/(\w+) ==> ^<a>/b/(\w+)
4. ^(?P<a>\w+)/b/(?P<c>\w+) ==> ^<a>/b/<c>
| def replace_named_groups(pattern):
r"""
Find named groups in `pattern` and replace them with the group name. E.g.,
1. ^(?P<a>\w+)/b/(\w+)$ ==> ^<a>/b/(\w+)$
2. ^(?P<a>\w+)/b/(?P<c>\w+)/$ ==> ^<a>/b/<c>/$
3. ^(?P<a>\w+)/b/(\w+) ==> ^<a>/b/(\w+)
4. ^(?P<a>\w+)/b/(?P<c>\w+) ==> ^<a>/b/<c>
"""
named_group_indices = [
(m.start(0), m.end(0), m[1])
for m in named_group_matcher.finditer(pattern)
]
# Tuples of (named capture group pattern, group name).
group_pattern_and_name = []
# Loop over the groups and their start and end indices.
for start, end, group_name in named_group_indices:
# Handle nested parentheses, e.g. '^(?P<a>(x|y))/b'.
unmatched_open_brackets, prev_char = 1, None
for idx, val in enumerate(pattern[end:]):
# Check for unescaped `(` and `)`. They mark the start and end of a
# nested group.
if val == '(' and prev_char != '\\':
unmatched_open_brackets += 1
elif val == ')' and prev_char != '\\':
unmatched_open_brackets -= 1
prev_char = val
# If brackets are balanced, the end of the string for the current
# named capture group pattern has been reached.
if unmatched_open_brackets == 0:
group_pattern_and_name.append((pattern[start:end + idx + 1], group_name))
break
# Replace the string for named capture groups with their group names.
for group_pattern, group_name in group_pattern_and_name:
pattern = pattern.replace(group_pattern, group_name)
return pattern | [
"def",
"replace_named_groups",
"(",
"pattern",
")",
":",
"named_group_indices",
"=",
"[",
"(",
"m",
".",
"start",
"(",
"0",
")",
",",
"m",
".",
"end",
"(",
"0",
")",
",",
"m",
"[",
"1",
"]",
")",
"for",
"m",
"in",
"named_group_matcher",
".",
"finditer",
"(",
"pattern",
")",
"]",
"# Tuples of (named capture group pattern, group name).",
"group_pattern_and_name",
"=",
"[",
"]",
"# Loop over the groups and their start and end indices.",
"for",
"start",
",",
"end",
",",
"group_name",
"in",
"named_group_indices",
":",
"# Handle nested parentheses, e.g. '^(?P<a>(x|y))/b'.",
"unmatched_open_brackets",
",",
"prev_char",
"=",
"1",
",",
"None",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"pattern",
"[",
"end",
":",
"]",
")",
":",
"# Check for unescaped `(` and `)`. They mark the start and end of a",
"# nested group.",
"if",
"val",
"==",
"'('",
"and",
"prev_char",
"!=",
"'\\\\'",
":",
"unmatched_open_brackets",
"+=",
"1",
"elif",
"val",
"==",
"')'",
"and",
"prev_char",
"!=",
"'\\\\'",
":",
"unmatched_open_brackets",
"-=",
"1",
"prev_char",
"=",
"val",
"# If brackets are balanced, the end of the string for the current",
"# named capture group pattern has been reached.",
"if",
"unmatched_open_brackets",
"==",
"0",
":",
"group_pattern_and_name",
".",
"append",
"(",
"(",
"pattern",
"[",
"start",
":",
"end",
"+",
"idx",
"+",
"1",
"]",
",",
"group_name",
")",
")",
"break",
"# Replace the string for named capture groups with their group names.",
"for",
"group_pattern",
",",
"group_name",
"in",
"group_pattern_and_name",
":",
"pattern",
"=",
"pattern",
".",
"replace",
"(",
"group_pattern",
",",
"group_name",
")",
"return",
"pattern"
] | [
141,
0
] | [
176,
18
] | python | cy | ['en', 'cy', 'hi'] | False |
replace_unnamed_groups | (pattern) | r"""
Find unnamed groups in `pattern` and replace them with '<var>'. E.g.,
1. ^(?P<a>\w+)/b/(\w+)$ ==> ^(?P<a>\w+)/b/<var>$
2. ^(?P<a>\w+)/b/((x|y)\w+)$ ==> ^(?P<a>\w+)/b/<var>$
3. ^(?P<a>\w+)/b/(\w+) ==> ^(?P<a>\w+)/b/<var>
4. ^(?P<a>\w+)/b/((x|y)\w+) ==> ^(?P<a>\w+)/b/<var>
| r"""
Find unnamed groups in `pattern` and replace them with '<var>'. E.g.,
1. ^(?P<a>\w+)/b/(\w+)$ ==> ^(?P<a>\w+)/b/<var>$
2. ^(?P<a>\w+)/b/((x|y)\w+)$ ==> ^(?P<a>\w+)/b/<var>$
3. ^(?P<a>\w+)/b/(\w+) ==> ^(?P<a>\w+)/b/<var>
4. ^(?P<a>\w+)/b/((x|y)\w+) ==> ^(?P<a>\w+)/b/<var>
| def replace_unnamed_groups(pattern):
r"""
Find unnamed groups in `pattern` and replace them with '<var>'. E.g.,
1. ^(?P<a>\w+)/b/(\w+)$ ==> ^(?P<a>\w+)/b/<var>$
2. ^(?P<a>\w+)/b/((x|y)\w+)$ ==> ^(?P<a>\w+)/b/<var>$
3. ^(?P<a>\w+)/b/(\w+) ==> ^(?P<a>\w+)/b/<var>
4. ^(?P<a>\w+)/b/((x|y)\w+) ==> ^(?P<a>\w+)/b/<var>
"""
unnamed_group_indices = [m.start(0) for m in unnamed_group_matcher.finditer(pattern)]
# Indices of the start of unnamed capture groups.
group_indices = []
# Loop over the start indices of the groups.
for start in unnamed_group_indices:
# Handle nested parentheses, e.g. '^b/((x|y)\w+)$'.
unmatched_open_brackets, prev_char = 1, None
for idx, val in enumerate(pattern[start + 1:]):
# Check for unescaped `(` and `)`. They mark the start and end of
# a nested group.
if val == '(' and prev_char != '\\':
unmatched_open_brackets += 1
elif val == ')' and prev_char != '\\':
unmatched_open_brackets -= 1
prev_char = val
if unmatched_open_brackets == 0:
group_indices.append((start, start + 2 + idx))
break
# Remove unnamed group matches inside other unnamed capture groups.
group_start_end_indices = []
prev_end = None
for start, end in group_indices:
if prev_end and start > prev_end or not prev_end:
group_start_end_indices.append((start, end))
prev_end = end
if group_start_end_indices:
# Replace unnamed groups with <var>. Handle the fact that replacing the
# string between indices will change string length and thus indices
# will point to the wrong substring if not corrected.
final_pattern, prev_end = [], None
for start, end in group_start_end_indices:
if prev_end:
final_pattern.append(pattern[prev_end:start])
final_pattern.append(pattern[:start] + '<var>')
prev_end = end
final_pattern.append(pattern[prev_end:])
return ''.join(final_pattern)
else:
return pattern | [
"def",
"replace_unnamed_groups",
"(",
"pattern",
")",
":",
"unnamed_group_indices",
"=",
"[",
"m",
".",
"start",
"(",
"0",
")",
"for",
"m",
"in",
"unnamed_group_matcher",
".",
"finditer",
"(",
"pattern",
")",
"]",
"# Indices of the start of unnamed capture groups.",
"group_indices",
"=",
"[",
"]",
"# Loop over the start indices of the groups.",
"for",
"start",
"in",
"unnamed_group_indices",
":",
"# Handle nested parentheses, e.g. '^b/((x|y)\\w+)$'.",
"unmatched_open_brackets",
",",
"prev_char",
"=",
"1",
",",
"None",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"pattern",
"[",
"start",
"+",
"1",
":",
"]",
")",
":",
"# Check for unescaped `(` and `)`. They mark the start and end of",
"# a nested group.",
"if",
"val",
"==",
"'('",
"and",
"prev_char",
"!=",
"'\\\\'",
":",
"unmatched_open_brackets",
"+=",
"1",
"elif",
"val",
"==",
"')'",
"and",
"prev_char",
"!=",
"'\\\\'",
":",
"unmatched_open_brackets",
"-=",
"1",
"prev_char",
"=",
"val",
"if",
"unmatched_open_brackets",
"==",
"0",
":",
"group_indices",
".",
"append",
"(",
"(",
"start",
",",
"start",
"+",
"2",
"+",
"idx",
")",
")",
"break",
"# Remove unnamed group matches inside other unnamed capture groups.",
"group_start_end_indices",
"=",
"[",
"]",
"prev_end",
"=",
"None",
"for",
"start",
",",
"end",
"in",
"group_indices",
":",
"if",
"prev_end",
"and",
"start",
">",
"prev_end",
"or",
"not",
"prev_end",
":",
"group_start_end_indices",
".",
"append",
"(",
"(",
"start",
",",
"end",
")",
")",
"prev_end",
"=",
"end",
"if",
"group_start_end_indices",
":",
"# Replace unnamed groups with <var>. Handle the fact that replacing the",
"# string between indices will change string length and thus indices",
"# will point to the wrong substring if not corrected.",
"final_pattern",
",",
"prev_end",
"=",
"[",
"]",
",",
"None",
"for",
"start",
",",
"end",
"in",
"group_start_end_indices",
":",
"if",
"prev_end",
":",
"final_pattern",
".",
"append",
"(",
"pattern",
"[",
"prev_end",
":",
"start",
"]",
")",
"final_pattern",
".",
"append",
"(",
"pattern",
"[",
":",
"start",
"]",
"+",
"'<var>'",
")",
"prev_end",
"=",
"end",
"final_pattern",
".",
"append",
"(",
"pattern",
"[",
"prev_end",
":",
"]",
")",
"return",
"''",
".",
"join",
"(",
"final_pattern",
")",
"else",
":",
"return",
"pattern"
] | [
179,
0
] | [
227,
22
] | python | cy | ['en', 'cy', 'hi'] | False |
ReindentFilter._flatten_up_to_token | (self, token) | Yields all tokens up to token but excluding current. | Yields all tokens up to token but excluding current. | def _flatten_up_to_token(self, token):
"""Yields all tokens up to token but excluding current."""
if token.is_group:
token = next(token.flatten())
for t in self._curr_stmt.flatten():
if t == token:
break
yield t | [
"def",
"_flatten_up_to_token",
"(",
"self",
",",
"token",
")",
":",
"if",
"token",
".",
"is_group",
":",
"token",
"=",
"next",
"(",
"token",
".",
"flatten",
"(",
")",
")",
"for",
"t",
"in",
"self",
".",
"_curr_stmt",
".",
"flatten",
"(",
")",
":",
"if",
"t",
"==",
"token",
":",
"break",
"yield",
"t"
] | [
27,
4
] | [
35,
19
] | python | en | ['en', 'en', 'en'] | True |
BaseDistribution.location | (self) | Where the distribution is loaded from.
A string value is not necessarily a filesystem path, since distributions
can be loaded from other sources, e.g. arbitrary zip archives. ``None``
means the distribution is created in-memory.
Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
this is a symbolic link, we want to preserve the relative path between
it and files in the distribution.
| Where the distribution is loaded from. | def location(self) -> Optional[str]:
"""Where the distribution is loaded from.
A string value is not necessarily a filesystem path, since distributions
can be loaded from other sources, e.g. arbitrary zip archives. ``None``
means the distribution is created in-memory.
Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
this is a symbolic link, we want to preserve the relative path between
it and files in the distribution.
"""
raise NotImplementedError() | [
"def",
"location",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
53,
4
] | [
64,
35
] | python | en | ['en', 'en', 'en'] | True |
BaseDistribution.info_directory | (self) | Location of the .[egg|dist]-info directory.
Similarly to ``location``, a string value is not necessarily a
filesystem path. ``None`` means the distribution is created in-memory.
For a modern .dist-info installation on disk, this should be something
like ``{location}/{raw_name}-{version}.dist-info``.
Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
this is a symbolic link, we want to preserve the relative path between
it and other files in the distribution.
| Location of the .[egg|dist]-info directory. | def info_directory(self) -> Optional[str]:
"""Location of the .[egg|dist]-info directory.
Similarly to ``location``, a string value is not necessarily a
filesystem path. ``None`` means the distribution is created in-memory.
For a modern .dist-info installation on disk, this should be something
like ``{location}/{raw_name}-{version}.dist-info``.
Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
this is a symbolic link, we want to preserve the relative path between
it and other files in the distribution.
"""
raise NotImplementedError() | [
"def",
"info_directory",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
67,
4
] | [
80,
35
] | python | en | ['en', 'en', 'en'] | True |
BaseDistribution.direct_url | (self) | Obtain a DirectUrl from this distribution.
Returns None if the distribution has no `direct_url.json` metadata,
or if `direct_url.json` is invalid.
| Obtain a DirectUrl from this distribution. | def direct_url(self) -> Optional[DirectUrl]:
"""Obtain a DirectUrl from this distribution.
Returns None if the distribution has no `direct_url.json` metadata,
or if `direct_url.json` is invalid.
"""
try:
content = self.read_text(DIRECT_URL_METADATA_NAME)
except FileNotFoundError:
return None
try:
return DirectUrl.from_json(content)
except (
UnicodeDecodeError,
json.JSONDecodeError,
DirectUrlValidationError,
) as e:
logger.warning(
"Error parsing %s for %s: %s",
DIRECT_URL_METADATA_NAME,
self.canonical_name,
e,
)
return None | [
"def",
"direct_url",
"(",
"self",
")",
"->",
"Optional",
"[",
"DirectUrl",
"]",
":",
"try",
":",
"content",
"=",
"self",
".",
"read_text",
"(",
"DIRECT_URL_METADATA_NAME",
")",
"except",
"FileNotFoundError",
":",
"return",
"None",
"try",
":",
"return",
"DirectUrl",
".",
"from_json",
"(",
"content",
")",
"except",
"(",
"UnicodeDecodeError",
",",
"json",
".",
"JSONDecodeError",
",",
"DirectUrlValidationError",
",",
")",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"\"Error parsing %s for %s: %s\"",
",",
"DIRECT_URL_METADATA_NAME",
",",
"self",
".",
"canonical_name",
",",
"e",
",",
")",
"return",
"None"
] | [
91,
4
] | [
114,
23
] | python | en | ['en', 'en', 'en'] | True |
BaseDistribution.read_text | (self, name: str) | Read a file in the .dist-info (or .egg-info) directory.
Should raise ``FileNotFoundError`` if ``name`` does not exist in the
metadata directory.
| Read a file in the .dist-info (or .egg-info) directory. | def read_text(self, name: str) -> str:
"""Read a file in the .dist-info (or .egg-info) directory.
Should raise ``FileNotFoundError`` if ``name`` does not exist in the
metadata directory.
"""
raise NotImplementedError() | [
"def",
"read_text",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"str",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
136,
4
] | [
142,
35
] | python | en | ['en', 'en', 'en'] | True |
BaseDistribution.metadata | (self) | Metadata of distribution parsed from e.g. METADATA or PKG-INFO. | Metadata of distribution parsed from e.g. METADATA or PKG-INFO. | def metadata(self) -> email.message.Message:
"""Metadata of distribution parsed from e.g. METADATA or PKG-INFO."""
raise NotImplementedError() | [
"def",
"metadata",
"(",
"self",
")",
"->",
"email",
".",
"message",
".",
"Message",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
148,
4
] | [
150,
35
] | python | en | ['en', 'en', 'en'] | True |
BaseDistribution.metadata_version | (self) | Value of "Metadata-Version:" in distribution metadata, if available. | Value of "Metadata-Version:" in distribution metadata, if available. | def metadata_version(self) -> Optional[str]:
"""Value of "Metadata-Version:" in distribution metadata, if available."""
return self.metadata.get("Metadata-Version") | [
"def",
"metadata_version",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"self",
".",
"metadata",
".",
"get",
"(",
"\"Metadata-Version\"",
")"
] | [
153,
4
] | [
155,
52
] | python | en | ['en', 'en', 'en'] | True |
BaseDistribution.raw_name | (self) | Value of "Name:" in distribution metadata. | Value of "Name:" in distribution metadata. | def raw_name(self) -> str:
"""Value of "Name:" in distribution metadata."""
# The metadata should NEVER be missing the Name: key, but if it somehow
# does not, fall back to the known canonical name.
return self.metadata.get("Name", self.canonical_name) | [
"def",
"raw_name",
"(",
"self",
")",
"->",
"str",
":",
"# The metadata should NEVER be missing the Name: key, but if it somehow",
"# does not, fall back to the known canonical name.",
"return",
"self",
".",
"metadata",
".",
"get",
"(",
"\"Name\"",
",",
"self",
".",
"canonical_name",
")"
] | [
158,
4
] | [
162,
61
] | python | en | ['en', 'en', 'en'] | True |
BaseEnvironment.get_distribution | (self, name: str) | Given a requirement name, return the installed distributions. | Given a requirement name, return the installed distributions. | def get_distribution(self, name: str) -> Optional["BaseDistribution"]:
"""Given a requirement name, return the installed distributions."""
raise NotImplementedError() | [
"def",
"get_distribution",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Optional",
"[",
"\"BaseDistribution\"",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
179,
4
] | [
181,
35
] | python | en | ['en', 'en', 'en'] | True |
BaseEnvironment._iter_distributions | (self) | Iterate through installed distributions.
This function should be implemented by subclass, but never called
directly. Use the public ``iter_distribution()`` instead, which
implements additional logic to make sure the distributions are valid.
| Iterate through installed distributions. | def _iter_distributions(self) -> Iterator["BaseDistribution"]:
"""Iterate through installed distributions.
This function should be implemented by subclass, but never called
directly. Use the public ``iter_distribution()`` instead, which
implements additional logic to make sure the distributions are valid.
"""
raise NotImplementedError() | [
"def",
"_iter_distributions",
"(",
"self",
")",
"->",
"Iterator",
"[",
"\"BaseDistribution\"",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
183,
4
] | [
190,
35
] | python | en | ['en', 'en', 'en'] | True |
BaseEnvironment.iter_distributions | (self) | Iterate through installed distributions. | Iterate through installed distributions. | def iter_distributions(self) -> Iterator["BaseDistribution"]:
"""Iterate through installed distributions."""
for dist in self._iter_distributions():
# Make sure the distribution actually comes from a valid Python
# packaging distribution. Pip's AdjacentTempDirectory leaves folders
# e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
# valid project name pattern is taken from PEP 508.
project_name_valid = re.match(
r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
dist.canonical_name,
flags=re.IGNORECASE,
)
if not project_name_valid:
logger.warning(
"Ignoring invalid distribution %s (%s)",
dist.canonical_name,
dist.location,
)
continue
yield dist | [
"def",
"iter_distributions",
"(",
"self",
")",
"->",
"Iterator",
"[",
"\"BaseDistribution\"",
"]",
":",
"for",
"dist",
"in",
"self",
".",
"_iter_distributions",
"(",
")",
":",
"# Make sure the distribution actually comes from a valid Python",
"# packaging distribution. Pip's AdjacentTempDirectory leaves folders",
"# e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The",
"# valid project name pattern is taken from PEP 508.",
"project_name_valid",
"=",
"re",
".",
"match",
"(",
"r\"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$\"",
",",
"dist",
".",
"canonical_name",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
",",
")",
"if",
"not",
"project_name_valid",
":",
"logger",
".",
"warning",
"(",
"\"Ignoring invalid distribution %s (%s)\"",
",",
"dist",
".",
"canonical_name",
",",
"dist",
".",
"location",
",",
")",
"continue",
"yield",
"dist"
] | [
192,
4
] | [
211,
22
] | python | en | ['en', 'en', 'en'] | True |
BaseEnvironment.iter_installed_distributions | (
self,
local_only: bool = True,
skip: Container[str] = stdlib_pkgs,
include_editables: bool = True,
editables_only: bool = False,
user_only: bool = False,
) | Return a list of installed distributions.
:param local_only: If True (default), only return installations
local to the current virtualenv, if in a virtualenv.
:param skip: An iterable of canonicalized project names to ignore;
defaults to ``stdlib_pkgs``.
:param include_editables: If False, don't report editables.
:param editables_only: If True, only report editables.
:param user_only: If True, only report installations in the user
site directory.
| Return a list of installed distributions. | def iter_installed_distributions(
self,
local_only: bool = True,
skip: Container[str] = stdlib_pkgs,
include_editables: bool = True,
editables_only: bool = False,
user_only: bool = False,
) -> Iterator[BaseDistribution]:
"""Return a list of installed distributions.
:param local_only: If True (default), only return installations
local to the current virtualenv, if in a virtualenv.
:param skip: An iterable of canonicalized project names to ignore;
defaults to ``stdlib_pkgs``.
:param include_editables: If False, don't report editables.
:param editables_only: If True, only report editables.
:param user_only: If True, only report installations in the user
site directory.
"""
it = self.iter_distributions()
if local_only:
it = (d for d in it if d.local)
if not include_editables:
it = (d for d in it if not d.editable)
if editables_only:
it = (d for d in it if d.editable)
if user_only:
it = (d for d in it if d.in_usersite)
return (d for d in it if d.canonical_name not in skip) | [
"def",
"iter_installed_distributions",
"(",
"self",
",",
"local_only",
":",
"bool",
"=",
"True",
",",
"skip",
":",
"Container",
"[",
"str",
"]",
"=",
"stdlib_pkgs",
",",
"include_editables",
":",
"bool",
"=",
"True",
",",
"editables_only",
":",
"bool",
"=",
"False",
",",
"user_only",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Iterator",
"[",
"BaseDistribution",
"]",
":",
"it",
"=",
"self",
".",
"iter_distributions",
"(",
")",
"if",
"local_only",
":",
"it",
"=",
"(",
"d",
"for",
"d",
"in",
"it",
"if",
"d",
".",
"local",
")",
"if",
"not",
"include_editables",
":",
"it",
"=",
"(",
"d",
"for",
"d",
"in",
"it",
"if",
"not",
"d",
".",
"editable",
")",
"if",
"editables_only",
":",
"it",
"=",
"(",
"d",
"for",
"d",
"in",
"it",
"if",
"d",
".",
"editable",
")",
"if",
"user_only",
":",
"it",
"=",
"(",
"d",
"for",
"d",
"in",
"it",
"if",
"d",
".",
"in_usersite",
")",
"return",
"(",
"d",
"for",
"d",
"in",
"it",
"if",
"d",
".",
"canonical_name",
"not",
"in",
"skip",
")"
] | [
213,
4
] | [
241,
62
] | python | en | ['en', 'en', 'en'] | True |
unicode_to_ascii | (s) | Transforms an ascii string into unicode. | Transforms an ascii string into unicode. | def unicode_to_ascii(s):
"""Transforms an ascii string into unicode."""
normalized = unicodedata.normalize('NFD', s)
return ''.join(c for c in normalized if unicodedata.category(c) != 'Mn') | [
"def",
"unicode_to_ascii",
"(",
"s",
")",
":",
"normalized",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
",",
"s",
")",
"return",
"''",
".",
"join",
"(",
"c",
"for",
"c",
"in",
"normalized",
"if",
"unicodedata",
".",
"category",
"(",
"c",
")",
"!=",
"'Mn'",
")"
] | [
7,
0
] | [
10,
76
] | python | en | ['en', 'pt', 'en'] | True |
preprocess_sentence | (w) | Lowers, strips, and adds <start> and <end> tags to a sentence.
| Lowers, strips, and adds <start> and <end> tags to a sentence.
| def preprocess_sentence(w):
"""Lowers, strips, and adds <start> and <end> tags to a sentence.
"""
w = unicode_to_ascii(w.lower().strip())
# creating a space between a word and the punctuation following it
# eg: "he is a boy." => "he is a boy ."
w = re.sub(r"([?.!,¿])", r" \1 ", w)
w = re.sub(r'[" "]+', " ", w)
# replacing everything with space except (a-z, A-Z, ".", "?", "!", ",")
w = re.sub(r"[^a-zA-Z?.!,¿]+", " ", w)
w = w.rstrip().strip()
# adding a start and an end token to the sentence
# so that the model know when to start and stop predicting.
w = '<start> ' + w + ' <end>'
return w | [
"def",
"preprocess_sentence",
"(",
"w",
")",
":",
"w",
"=",
"unicode_to_ascii",
"(",
"w",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
")",
"# creating a space between a word and the punctuation following it",
"# eg: \"he is a boy.\" => \"he is a boy .\"",
"w",
"=",
"re",
".",
"sub",
"(",
"r\"([?.!,¿])\",",
" ",
"\" \\1 \",",
" ",
")",
"",
"w",
"=",
"re",
".",
"sub",
"(",
"r'[\" \"]+'",
",",
"\" \"",
",",
"w",
")",
"# replacing everything with space except (a-z, A-Z, \".\", \"?\", \"!\", \",\")",
"w",
"=",
"re",
".",
"sub",
"(",
"r\"[^a-zA-Z?.!,¿]+\",",
" ",
" \",",
" ",
")",
"",
"w",
"=",
"w",
".",
"rstrip",
"(",
")",
".",
"strip",
"(",
")",
"# adding a start and an end token to the sentence",
"# so that the model know when to start and stop predicting.",
"w",
"=",
"'<start> '",
"+",
"w",
"+",
"' <end>'",
"return",
"w"
] | [
13,
0
] | [
32,
12
] | python | en | ['en', 'en', 'en'] | True |
tokenize | (lang, lang_tokenizer=None) | Given a list of sentences, return an integer representation
Arguments:
lang -- a python list of sentences
lang_tokenizer -- keras_preprocessing.text.Tokenizer, if None
this will be created for you
Returns:
tensor -- int tensor of shape (NUM_EXAMPLES,MAX_SENTENCE_LENGTH)
lang_tokenizer -- keras_preprocessing.text.Tokenizer
| Given a list of sentences, return an integer representation | def tokenize(lang, lang_tokenizer=None):
"""Given a list of sentences, return an integer representation
Arguments:
lang -- a python list of sentences
lang_tokenizer -- keras_preprocessing.text.Tokenizer, if None
this will be created for you
Returns:
tensor -- int tensor of shape (NUM_EXAMPLES,MAX_SENTENCE_LENGTH)
lang_tokenizer -- keras_preprocessing.text.Tokenizer
"""
if lang_tokenizer is None:
lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(
filters='')
lang_tokenizer.fit_on_texts(lang)
tensor = lang_tokenizer.texts_to_sequences(lang)
tensor = tf.keras.preprocessing.sequence.pad_sequences(
tensor, padding='post')
return tensor, lang_tokenizer | [
"def",
"tokenize",
"(",
"lang",
",",
"lang_tokenizer",
"=",
"None",
")",
":",
"if",
"lang_tokenizer",
"is",
"None",
":",
"lang_tokenizer",
"=",
"tf",
".",
"keras",
".",
"preprocessing",
".",
"text",
".",
"Tokenizer",
"(",
"filters",
"=",
"''",
")",
"lang_tokenizer",
".",
"fit_on_texts",
"(",
"lang",
")",
"tensor",
"=",
"lang_tokenizer",
".",
"texts_to_sequences",
"(",
"lang",
")",
"tensor",
"=",
"tf",
".",
"keras",
".",
"preprocessing",
".",
"sequence",
".",
"pad_sequences",
"(",
"tensor",
",",
"padding",
"=",
"'post'",
")",
"return",
"tensor",
",",
"lang_tokenizer"
] | [
35,
0
] | [
57,
33
] | python | en | ['en', 'lb', 'en'] | True |
preprocess | (sentences, tokenizer) | Preprocesses then tokenizes text
Arguments:
sentences -- a python list of of strings
tokenizer -- Tokenizer for mapping words to integers
Returns:
tensor -- int tensor of shape (NUM_EXAMPLES,MAX_SENTENCE_LENGTH)
lang_tokenizer -- keras_preprocessing.text.Tokenizer
| Preprocesses then tokenizes text | def preprocess(sentences, tokenizer):
"""Preprocesses then tokenizes text
Arguments:
sentences -- a python list of of strings
tokenizer -- Tokenizer for mapping words to integers
Returns:
tensor -- int tensor of shape (NUM_EXAMPLES,MAX_SENTENCE_LENGTH)
lang_tokenizer -- keras_preprocessing.text.Tokenizer
"""
sentences = [preprocess_sentence(sentence) for sentence in sentences]
tokens, _ = tokenize(sentences, tokenizer)
return tokens | [
"def",
"preprocess",
"(",
"sentences",
",",
"tokenizer",
")",
":",
"sentences",
"=",
"[",
"preprocess_sentence",
"(",
"sentence",
")",
"for",
"sentence",
"in",
"sentences",
"]",
"tokens",
",",
"_",
"=",
"tokenize",
"(",
"sentences",
",",
"tokenizer",
")",
"return",
"tokens"
] | [
60,
0
] | [
73,
17
] | python | en | ['en', 'el-Latn', 'en'] | True |
int2word | (tokenizer, int_sequence) | Converts integer representation to natural language representation
Arguments:
tokenizer -- keras_preprocessing.text.Tokenizer
int_sequence -- an iterable or rank 1 tensor of integers
Returns list of string tokens
| Converts integer representation to natural language representation | def int2word(tokenizer, int_sequence):
"""Converts integer representation to natural language representation
Arguments:
tokenizer -- keras_preprocessing.text.Tokenizer
int_sequence -- an iterable or rank 1 tensor of integers
Returns list of string tokens
"""
return [tokenizer.index_word[t] if t != 0 else '' for t in int_sequence] | [
"def",
"int2word",
"(",
"tokenizer",
",",
"int_sequence",
")",
":",
"return",
"[",
"tokenizer",
".",
"index_word",
"[",
"t",
"]",
"if",
"t",
"!=",
"0",
"else",
"''",
"for",
"t",
"in",
"int_sequence",
"]"
] | [
76,
0
] | [
85,
76
] | python | en | ['en', 'fil', 'en'] | True |
Schemas.__init__ | (self, discovery) | Constructor.
Args:
discovery: object, Deserialized discovery document from which we pull
out the named schema.
| Constructor. | def __init__(self, discovery):
"""Constructor.
Args:
discovery: object, Deserialized discovery document from which we pull
out the named schema.
"""
self.schemas = discovery.get('schemas', {})
# Cache of pretty printed schemas.
self.pretty = {} | [
"def",
"__init__",
"(",
"self",
",",
"discovery",
")",
":",
"self",
".",
"schemas",
"=",
"discovery",
".",
"get",
"(",
"'schemas'",
",",
"{",
"}",
")",
"# Cache of pretty printed schemas.",
"self",
".",
"pretty",
"=",
"{",
"}"
] | [
78,
2
] | [
88,
20
] | python | en | ['en', 'en', 'en'] | False |
Schemas._prettyPrintByName | (self, name, seen=None, dent=0) | Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
| Get pretty printed object prototype from the schema name. | def _prettyPrintByName(self, name, seen=None, dent=0):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
if name in seen:
# Do not fall into an infinite loop over recursive definitions.
return '# Object with schema name: %s' % name
seen.append(name)
if name not in self.pretty:
self.pretty[name] = _SchemaToStruct(self.schemas[name],
seen, dent=dent).to_str(self._prettyPrintByName)
seen.pop()
return self.pretty[name] | [
"def",
"_prettyPrintByName",
"(",
"self",
",",
"name",
",",
"seen",
"=",
"None",
",",
"dent",
"=",
"0",
")",
":",
"if",
"seen",
"is",
"None",
":",
"seen",
"=",
"[",
"]",
"if",
"name",
"in",
"seen",
":",
"# Do not fall into an infinite loop over recursive definitions.",
"return",
"'# Object with schema name: %s'",
"%",
"name",
"seen",
".",
"append",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"self",
".",
"pretty",
":",
"self",
".",
"pretty",
"[",
"name",
"]",
"=",
"_SchemaToStruct",
"(",
"self",
".",
"schemas",
"[",
"name",
"]",
",",
"seen",
",",
"dent",
"=",
"dent",
")",
".",
"to_str",
"(",
"self",
".",
"_prettyPrintByName",
")",
"seen",
".",
"pop",
"(",
")",
"return",
"self",
".",
"pretty",
"[",
"name",
"]"
] | [
91,
2
] | [
117,
28
] | python | en | ['en', 'en', 'en'] | True |
Schemas.prettyPrintByName | (self, name) | Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
| Get pretty printed object prototype from the schema name. | def prettyPrintByName(self, name):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintByName(name, seen=[], dent=1)[:-2] | [
"def",
"prettyPrintByName",
"(",
"self",
",",
"name",
")",
":",
"# Return with trailing comma and newline removed.",
"return",
"self",
".",
"_prettyPrintByName",
"(",
"name",
",",
"seen",
"=",
"[",
"]",
",",
"dent",
"=",
"1",
")",
"[",
":",
"-",
"2",
"]"
] | [
119,
2
] | [
130,
62
] | python | en | ['en', 'en', 'en'] | True |
Schemas._prettyPrintSchema | (self, schema, seen=None, dent=0) | Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
| Get pretty printed object prototype of schema. | def _prettyPrintSchema(self, schema, seen=None, dent=0):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
return _SchemaToStruct(schema, seen, dent=dent).to_str(self._prettyPrintByName) | [
"def",
"_prettyPrintSchema",
"(",
"self",
",",
"schema",
",",
"seen",
"=",
"None",
",",
"dent",
"=",
"0",
")",
":",
"if",
"seen",
"is",
"None",
":",
"seen",
"=",
"[",
"]",
"return",
"_SchemaToStruct",
"(",
"schema",
",",
"seen",
",",
"dent",
"=",
"dent",
")",
".",
"to_str",
"(",
"self",
".",
"_prettyPrintByName",
")"
] | [
133,
2
] | [
148,
83
] | python | en | ['en', 'en', 'en'] | True |
Schemas.prettyPrintSchema | (self, schema) | Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
| Get pretty printed object prototype of schema. | def prettyPrintSchema(self, schema):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintSchema(schema, dent=1)[:-2] | [
"def",
"prettyPrintSchema",
"(",
"self",
",",
"schema",
")",
":",
"# Return with trailing comma and newline removed.",
"return",
"self",
".",
"_prettyPrintSchema",
"(",
"schema",
",",
"dent",
"=",
"1",
")",
"[",
":",
"-",
"2",
"]"
] | [
150,
2
] | [
161,
55
] | python | en | ['en', 'en', 'en'] | True |
Schemas.get | (self, name) | Get deserialized JSON schema from the schema name.
Args:
name: string, Schema name.
| Get deserialized JSON schema from the schema name. | def get(self, name):
"""Get deserialized JSON schema from the schema name.
Args:
name: string, Schema name.
"""
return self.schemas[name] | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"schemas",
"[",
"name",
"]"
] | [
163,
2
] | [
169,
29
] | python | en | ['en', 'en', 'en'] | True |
_SchemaToStruct.__init__ | (self, schema, seen, dent=0) | Constructor.
Args:
schema: object, Parsed JSON schema.
seen: list, List of names of schema already seen while parsing. Used to
handle recursive definitions.
dent: int, Initial indentation depth.
| Constructor. | def __init__(self, schema, seen, dent=0):
"""Constructor.
Args:
schema: object, Parsed JSON schema.
seen: list, List of names of schema already seen while parsing. Used to
handle recursive definitions.
dent: int, Initial indentation depth.
"""
# The result of this parsing kept as list of strings.
self.value = []
# The final value of the parsing.
self.string = None
# The parsed JSON schema.
self.schema = schema
# Indentation level.
self.dent = dent
# Method that when called returns a prototype object for the schema with
# the given name.
self.from_cache = None
# List of names of schema already seen while parsing.
self.seen = seen | [
"def",
"__init__",
"(",
"self",
",",
"schema",
",",
"seen",
",",
"dent",
"=",
"0",
")",
":",
"# The result of this parsing kept as list of strings.",
"self",
".",
"value",
"=",
"[",
"]",
"# The final value of the parsing.",
"self",
".",
"string",
"=",
"None",
"# The parsed JSON schema.",
"self",
".",
"schema",
"=",
"schema",
"# Indentation level.",
"self",
".",
"dent",
"=",
"dent",
"# Method that when called returns a prototype object for the schema with",
"# the given name.",
"self",
".",
"from_cache",
"=",
"None",
"# List of names of schema already seen while parsing.",
"self",
".",
"seen",
"=",
"seen"
] | [
176,
2
] | [
202,
20
] | python | en | ['en', 'en', 'en'] | False |
_SchemaToStruct.emit | (self, text) | Add text as a line to the output.
Args:
text: string, Text to output.
| Add text as a line to the output. | def emit(self, text):
"""Add text as a line to the output.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text, '\n']) | [
"def",
"emit",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"value",
".",
"extend",
"(",
"[",
"\" \"",
"*",
"self",
".",
"dent",
",",
"text",
",",
"'\\n'",
"]",
")"
] | [
204,
2
] | [
210,
53
] | python | en | ['en', 'en', 'en'] | True |
_SchemaToStruct.emitBegin | (self, text) | Add text to the output, but with no line terminator.
Args:
text: string, Text to output.
| Add text to the output, but with no line terminator. | def emitBegin(self, text):
"""Add text to the output, but with no line terminator.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text]) | [
"def",
"emitBegin",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"value",
".",
"extend",
"(",
"[",
"\" \"",
"*",
"self",
".",
"dent",
",",
"text",
"]",
")"
] | [
212,
2
] | [
218,
47
] | python | en | ['en', 'en', 'en'] | True |
_SchemaToStruct.emitEnd | (self, text, comment) | Add text and comment to the output with line terminator.
Args:
text: string, Text to output.
comment: string, Python comment.
| Add text and comment to the output with line terminator. | def emitEnd(self, text, comment):
"""Add text and comment to the output with line terminator.
Args:
text: string, Text to output.
comment: string, Python comment.
"""
if comment:
divider = '\n' + ' ' * (self.dent + 2) + '# '
lines = comment.splitlines()
lines = [x.rstrip() for x in lines]
comment = divider.join(lines)
self.value.extend([text, ' # ', comment, '\n'])
else:
self.value.extend([text, '\n']) | [
"def",
"emitEnd",
"(",
"self",
",",
"text",
",",
"comment",
")",
":",
"if",
"comment",
":",
"divider",
"=",
"'\\n'",
"+",
"' '",
"*",
"(",
"self",
".",
"dent",
"+",
"2",
")",
"+",
"'# '",
"lines",
"=",
"comment",
".",
"splitlines",
"(",
")",
"lines",
"=",
"[",
"x",
".",
"rstrip",
"(",
")",
"for",
"x",
"in",
"lines",
"]",
"comment",
"=",
"divider",
".",
"join",
"(",
"lines",
")",
"self",
".",
"value",
".",
"extend",
"(",
"[",
"text",
",",
"' # '",
",",
"comment",
",",
"'\\n'",
"]",
")",
"else",
":",
"self",
".",
"value",
".",
"extend",
"(",
"[",
"text",
",",
"'\\n'",
"]",
")"
] | [
220,
2
] | [
234,
37
] | python | en | ['en', 'en', 'en'] | True |
_SchemaToStruct.indent | (self) | Increase indentation level. | Increase indentation level. | def indent(self):
"""Increase indentation level."""
self.dent += 1 | [
"def",
"indent",
"(",
"self",
")",
":",
"self",
".",
"dent",
"+=",
"1"
] | [
236,
2
] | [
238,
18
] | python | en | ['en', 'zu', 'en'] | True |
_SchemaToStruct.undent | (self) | Decrease indentation level. | Decrease indentation level. | def undent(self):
"""Decrease indentation level."""
self.dent -= 1 | [
"def",
"undent",
"(",
"self",
")",
":",
"self",
".",
"dent",
"-=",
"1"
] | [
240,
2
] | [
242,
18
] | python | en | ['en', 'zu', 'en'] | True |
_SchemaToStruct._to_str_impl | (self, schema) | Prototype object based on the schema, in Python code with comments.
Args:
schema: object, Parsed JSON schema file.
Returns:
Prototype object based on the schema, in Python code with comments.
| Prototype object based on the schema, in Python code with comments. | def _to_str_impl(self, schema):
"""Prototype object based on the schema, in Python code with comments.
Args:
schema: object, Parsed JSON schema file.
Returns:
Prototype object based on the schema, in Python code with comments.
"""
stype = schema.get('type')
if stype == 'object':
self.emitEnd('{', schema.get('description', ''))
self.indent()
if 'properties' in schema:
for pname, pschema in six.iteritems(schema.get('properties', {})):
self.emitBegin('"%s": ' % pname)
self._to_str_impl(pschema)
elif 'additionalProperties' in schema:
self.emitBegin('"a_key": ')
self._to_str_impl(schema['additionalProperties'])
self.undent()
self.emit('},')
elif '$ref' in schema:
schemaName = schema['$ref']
description = schema.get('description', '')
s = self.from_cache(schemaName, seen=self.seen)
parts = s.splitlines()
self.emitEnd(parts[0], description)
for line in parts[1:]:
self.emit(line.rstrip())
elif stype == 'boolean':
value = schema.get('default', 'True or False')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'string':
value = schema.get('default', 'A String')
self.emitEnd('"%s",' % str(value), schema.get('description', ''))
elif stype == 'integer':
value = schema.get('default', '42')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'number':
value = schema.get('default', '3.14')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'null':
self.emitEnd('None,', schema.get('description', ''))
elif stype == 'any':
self.emitEnd('"",', schema.get('description', ''))
elif stype == 'array':
self.emitEnd('[', schema.get('description'))
self.indent()
self.emitBegin('')
self._to_str_impl(schema['items'])
self.undent()
self.emit('],')
else:
self.emit('Unknown type! %s' % stype)
self.emitEnd('', '')
self.string = ''.join(self.value)
return self.string | [
"def",
"_to_str_impl",
"(",
"self",
",",
"schema",
")",
":",
"stype",
"=",
"schema",
".",
"get",
"(",
"'type'",
")",
"if",
"stype",
"==",
"'object'",
":",
"self",
".",
"emitEnd",
"(",
"'{'",
",",
"schema",
".",
"get",
"(",
"'description'",
",",
"''",
")",
")",
"self",
".",
"indent",
"(",
")",
"if",
"'properties'",
"in",
"schema",
":",
"for",
"pname",
",",
"pschema",
"in",
"six",
".",
"iteritems",
"(",
"schema",
".",
"get",
"(",
"'properties'",
",",
"{",
"}",
")",
")",
":",
"self",
".",
"emitBegin",
"(",
"'\"%s\": '",
"%",
"pname",
")",
"self",
".",
"_to_str_impl",
"(",
"pschema",
")",
"elif",
"'additionalProperties'",
"in",
"schema",
":",
"self",
".",
"emitBegin",
"(",
"'\"a_key\": '",
")",
"self",
".",
"_to_str_impl",
"(",
"schema",
"[",
"'additionalProperties'",
"]",
")",
"self",
".",
"undent",
"(",
")",
"self",
".",
"emit",
"(",
"'},'",
")",
"elif",
"'$ref'",
"in",
"schema",
":",
"schemaName",
"=",
"schema",
"[",
"'$ref'",
"]",
"description",
"=",
"schema",
".",
"get",
"(",
"'description'",
",",
"''",
")",
"s",
"=",
"self",
".",
"from_cache",
"(",
"schemaName",
",",
"seen",
"=",
"self",
".",
"seen",
")",
"parts",
"=",
"s",
".",
"splitlines",
"(",
")",
"self",
".",
"emitEnd",
"(",
"parts",
"[",
"0",
"]",
",",
"description",
")",
"for",
"line",
"in",
"parts",
"[",
"1",
":",
"]",
":",
"self",
".",
"emit",
"(",
"line",
".",
"rstrip",
"(",
")",
")",
"elif",
"stype",
"==",
"'boolean'",
":",
"value",
"=",
"schema",
".",
"get",
"(",
"'default'",
",",
"'True or False'",
")",
"self",
".",
"emitEnd",
"(",
"'%s,'",
"%",
"str",
"(",
"value",
")",
",",
"schema",
".",
"get",
"(",
"'description'",
",",
"''",
")",
")",
"elif",
"stype",
"==",
"'string'",
":",
"value",
"=",
"schema",
".",
"get",
"(",
"'default'",
",",
"'A String'",
")",
"self",
".",
"emitEnd",
"(",
"'\"%s\",'",
"%",
"str",
"(",
"value",
")",
",",
"schema",
".",
"get",
"(",
"'description'",
",",
"''",
")",
")",
"elif",
"stype",
"==",
"'integer'",
":",
"value",
"=",
"schema",
".",
"get",
"(",
"'default'",
",",
"'42'",
")",
"self",
".",
"emitEnd",
"(",
"'%s,'",
"%",
"str",
"(",
"value",
")",
",",
"schema",
".",
"get",
"(",
"'description'",
",",
"''",
")",
")",
"elif",
"stype",
"==",
"'number'",
":",
"value",
"=",
"schema",
".",
"get",
"(",
"'default'",
",",
"'3.14'",
")",
"self",
".",
"emitEnd",
"(",
"'%s,'",
"%",
"str",
"(",
"value",
")",
",",
"schema",
".",
"get",
"(",
"'description'",
",",
"''",
")",
")",
"elif",
"stype",
"==",
"'null'",
":",
"self",
".",
"emitEnd",
"(",
"'None,'",
",",
"schema",
".",
"get",
"(",
"'description'",
",",
"''",
")",
")",
"elif",
"stype",
"==",
"'any'",
":",
"self",
".",
"emitEnd",
"(",
"'\"\",'",
",",
"schema",
".",
"get",
"(",
"'description'",
",",
"''",
")",
")",
"elif",
"stype",
"==",
"'array'",
":",
"self",
".",
"emitEnd",
"(",
"'['",
",",
"schema",
".",
"get",
"(",
"'description'",
")",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"emitBegin",
"(",
"''",
")",
"self",
".",
"_to_str_impl",
"(",
"schema",
"[",
"'items'",
"]",
")",
"self",
".",
"undent",
"(",
")",
"self",
".",
"emit",
"(",
"'],'",
")",
"else",
":",
"self",
".",
"emit",
"(",
"'Unknown type! %s'",
"%",
"stype",
")",
"self",
".",
"emitEnd",
"(",
"''",
",",
"''",
")",
"self",
".",
"string",
"=",
"''",
".",
"join",
"(",
"self",
".",
"value",
")",
"return",
"self",
".",
"string"
] | [
244,
2
] | [
302,
22
] | python | en | ['en', 'en', 'en'] | True |
_SchemaToStruct.to_str | (self, from_cache) | Prototype object based on the schema, in Python code with comments.
Args:
from_cache: callable(name, seen), Callable that retrieves an object
prototype for a schema with the given name. Seen is a list of schema
names already seen as we recursively descend the schema definition.
Returns:
Prototype object based on the schema, in Python code with comments.
The lines of the code will all be properly indented.
| Prototype object based on the schema, in Python code with comments. | def to_str(self, from_cache):
"""Prototype object based on the schema, in Python code with comments.
Args:
from_cache: callable(name, seen), Callable that retrieves an object
prototype for a schema with the given name. Seen is a list of schema
names already seen as we recursively descend the schema definition.
Returns:
Prototype object based on the schema, in Python code with comments.
The lines of the code will all be properly indented.
"""
self.from_cache = from_cache
return self._to_str_impl(self.schema) | [
"def",
"to_str",
"(",
"self",
",",
"from_cache",
")",
":",
"self",
".",
"from_cache",
"=",
"from_cache",
"return",
"self",
".",
"_to_str_impl",
"(",
"self",
".",
"schema",
")"
] | [
304,
2
] | [
317,
41
] | python | en | ['en', 'en', 'en'] | True |
GenerateConfig | (context) | Generate configuration. | Generate configuration. | def GenerateConfig(context):
"""Generate configuration."""
name_prefix = context.env['deployment'] + '-' + context.env['name']
instance = {
'zone': context.properties['zone'],
'machineType': ZonalComputeUrl(
context.env['project'], context.properties['zone'], 'machineTypes',
'f1-micro'),
'metadata': {
'items': [{
'key': 'startup-script',
'value': context.properties['startup-script']
}]
},
'disks': [{
'deviceName': 'boot',
'type': 'PERSISTENT',
'autoDelete': True,
'boot': True,
'initializeParams': {
'diskName': name_prefix + '-disk',
'sourceImage': GlobalComputeUrl(
'debian-cloud', 'images', 'family/debian-8'
)
},
}],
'networkInterfaces': [{
'accessConfigs': [{
'name': 'external-nat',
'type': 'ONE_TO_ONE_NAT'
}],
'network': GlobalComputeUrl(
context.env['project'], 'networks', 'default')
}]
}
# Resources to return.
resources = {
'resources': [{
'name': name_prefix + '-vm',
'type': 'compute.v1.instance',
'properties': instance
}]
}
return resources | [
"def",
"GenerateConfig",
"(",
"context",
")",
":",
"name_prefix",
"=",
"context",
".",
"env",
"[",
"'deployment'",
"]",
"+",
"'-'",
"+",
"context",
".",
"env",
"[",
"'name'",
"]",
"instance",
"=",
"{",
"'zone'",
":",
"context",
".",
"properties",
"[",
"'zone'",
"]",
",",
"'machineType'",
":",
"ZonalComputeUrl",
"(",
"context",
".",
"env",
"[",
"'project'",
"]",
",",
"context",
".",
"properties",
"[",
"'zone'",
"]",
",",
"'machineTypes'",
",",
"'f1-micro'",
")",
",",
"'metadata'",
":",
"{",
"'items'",
":",
"[",
"{",
"'key'",
":",
"'startup-script'",
",",
"'value'",
":",
"context",
".",
"properties",
"[",
"'startup-script'",
"]",
"}",
"]",
"}",
",",
"'disks'",
":",
"[",
"{",
"'deviceName'",
":",
"'boot'",
",",
"'type'",
":",
"'PERSISTENT'",
",",
"'autoDelete'",
":",
"True",
",",
"'boot'",
":",
"True",
",",
"'initializeParams'",
":",
"{",
"'diskName'",
":",
"name_prefix",
"+",
"'-disk'",
",",
"'sourceImage'",
":",
"GlobalComputeUrl",
"(",
"'debian-cloud'",
",",
"'images'",
",",
"'family/debian-8'",
")",
"}",
",",
"}",
"]",
",",
"'networkInterfaces'",
":",
"[",
"{",
"'accessConfigs'",
":",
"[",
"{",
"'name'",
":",
"'external-nat'",
",",
"'type'",
":",
"'ONE_TO_ONE_NAT'",
"}",
"]",
",",
"'network'",
":",
"GlobalComputeUrl",
"(",
"context",
".",
"env",
"[",
"'project'",
"]",
",",
"'networks'",
",",
"'default'",
")",
"}",
"]",
"}",
"# Resources to return.",
"resources",
"=",
"{",
"'resources'",
":",
"[",
"{",
"'name'",
":",
"name_prefix",
"+",
"'-vm'",
",",
"'type'",
":",
"'compute.v1.instance'",
",",
"'properties'",
":",
"instance",
"}",
"]",
"}",
"return",
"resources"
] | [
30,
0
] | [
77,
18
] | python | en | ['en', 'la', 'en'] | False |
eval_setup_to_action_tier | (eval_setup_name: str) | Gets a default action tier for an eval setup. | Gets a default action tier for an eval setup. | def eval_setup_to_action_tier(eval_setup_name: str) -> str:
"""Gets a default action tier for an eval setup."""
for tier in phyre.action_mappers.ACTION_MAPPERS:
if eval_setup_name.startswith(tier):
return tier
raise ValueError('Failed to derive action tier for eval setup %s' %
eval_setup_name) | [
"def",
"eval_setup_to_action_tier",
"(",
"eval_setup_name",
":",
"str",
")",
"->",
"str",
":",
"for",
"tier",
"in",
"phyre",
".",
"action_mappers",
".",
"ACTION_MAPPERS",
":",
"if",
"eval_setup_name",
".",
"startswith",
"(",
"tier",
")",
":",
"return",
"tier",
"raise",
"ValueError",
"(",
"'Failed to derive action tier for eval setup %s'",
"%",
"eval_setup_name",
")"
] | [
56,
0
] | [
62,
37
] | python | en | ['en', 'da', 'en'] | True |
list_eval_setups | () | Get a list of names for all known eval setups. | Get a list of names for all known eval setups. | def list_eval_setups() -> Tuple[str, ...]:
"""Get a list of names for all known eval setups."""
return tuple(sorted(EVAL_SETUP_BUILDERS)) | [
"def",
"list_eval_setups",
"(",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"EVAL_SETUP_BUILDERS",
")",
")"
] | [
65,
0
] | [
67,
45
] | python | en | ['en', 'en', 'en'] | True |
get_fold | (eval_setup: str, seed: int
) | Get seed'th fold for specified evaluation setup.
Args:
eval_setup: The name of the evaluation setup to use. E.g.,
ball_cross_template.
seed: The random seed to create the fold.
Returns:
Tuple (train_ids, dev_ids, test_ids)
Contains task ids to use for each split.
Raises:
ValueError: Eval_setup is not valid evaluation setup.
| Get seed'th fold for specified evaluation setup. | def get_fold(eval_setup: str, seed: int
) -> Tuple[Tuple[str, ...], Tuple[str, ...], Tuple[str, ...]]:
"""Get seed'th fold for specified evaluation setup.
Args:
eval_setup: The name of the evaluation setup to use. E.g.,
ball_cross_template.
seed: The random seed to create the fold.
Returns:
Tuple (train_ids, dev_ids, test_ids)
Contains task ids to use for each split.
Raises:
ValueError: Eval_setup is not valid evaluation setup.
"""
try:
builder = EVAL_SETUP_BUILDERS[eval_setup]
except KeyError:
raise ValueError(f'Unknown eval setup: {eval_setup}. Chose one of'
f' {",".join(EVAL_SETUP_BUILDERS)}')
_, test_ids = _flatten_eval_setup(builder(seed))
train_ids, dev_ids = _flatten_eval_setup(builder(seed=seed, dev_seed=0))
return train_ids, dev_ids, test_ids | [
"def",
"get_fold",
"(",
"eval_setup",
":",
"str",
",",
"seed",
":",
"int",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"str",
",",
"...",
"]",
",",
"Tuple",
"[",
"str",
",",
"...",
"]",
",",
"Tuple",
"[",
"str",
",",
"...",
"]",
"]",
":",
"try",
":",
"builder",
"=",
"EVAL_SETUP_BUILDERS",
"[",
"eval_setup",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"f'Unknown eval setup: {eval_setup}. Chose one of'",
"f' {\",\".join(EVAL_SETUP_BUILDERS)}'",
")",
"_",
",",
"test_ids",
"=",
"_flatten_eval_setup",
"(",
"builder",
"(",
"seed",
")",
")",
"train_ids",
",",
"dev_ids",
"=",
"_flatten_eval_setup",
"(",
"builder",
"(",
"seed",
"=",
"seed",
",",
"dev_seed",
"=",
"0",
")",
")",
"return",
"train_ids",
",",
"dev_ids",
",",
"test_ids"
] | [
70,
0
] | [
93,
39
] | python | en | ['en', 'en', 'en'] | True |
_stable_rng | (task_id: str) | Map a string to a number in [0, 1). | Map a string to a number in [0, 1). | def _stable_rng(task_id: str) -> float:
"""Map a string to a number in [0, 1)."""
divider = 100000
return (int(hashlib.md5(task_id.encode('utf8')).hexdigest(), 16) %
divider) / divider | [
"def",
"_stable_rng",
"(",
"task_id",
":",
"str",
")",
"->",
"float",
":",
"divider",
"=",
"100000",
"return",
"(",
"int",
"(",
"hashlib",
".",
"md5",
"(",
"task_id",
".",
"encode",
"(",
"'utf8'",
")",
")",
".",
"hexdigest",
"(",
")",
",",
"16",
")",
"%",
"divider",
")",
"/",
"divider"
] | [
129,
0
] | [
133,
30
] | python | en | ['en', 'en', 'en'] | True |
get_task_ids_in_tier | (tier_name) | Returns a list of all task_ids in iter. | Returns a list of all task_ids in iter. | def get_task_ids_in_tier(tier_name):
"""Returns a list of all task_ids in iter."""
# dict of dicts: template_id -> task_id -> tier.
template_task_tiers = collections.defaultdict(dict)
for task_id, task in phyre.loader.load_compiled_task_dict().items():
template_id = task_id.split(':')[0]
template_task_tiers[template_id][task_id] = task.tier
selected_task_ids = set()
tier_name = tier_name.upper()
for template_id, task_to_tier in template_task_tiers.items():
tiers = frozenset(task_to_tier.values())
if len(tiers) == 1 and next(iter(tiers)) == tier_name:
selected_task_ids.update(task_to_tier)
return sorted(selected_task_ids) | [
"def",
"get_task_ids_in_tier",
"(",
"tier_name",
")",
":",
"# dict of dicts: template_id -> task_id -> tier.",
"template_task_tiers",
"=",
"collections",
".",
"defaultdict",
"(",
"dict",
")",
"for",
"task_id",
",",
"task",
"in",
"phyre",
".",
"loader",
".",
"load_compiled_task_dict",
"(",
")",
".",
"items",
"(",
")",
":",
"template_id",
"=",
"task_id",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"template_task_tiers",
"[",
"template_id",
"]",
"[",
"task_id",
"]",
"=",
"task",
".",
"tier",
"selected_task_ids",
"=",
"set",
"(",
")",
"tier_name",
"=",
"tier_name",
".",
"upper",
"(",
")",
"for",
"template_id",
",",
"task_to_tier",
"in",
"template_task_tiers",
".",
"items",
"(",
")",
":",
"tiers",
"=",
"frozenset",
"(",
"task_to_tier",
".",
"values",
"(",
")",
")",
"if",
"len",
"(",
"tiers",
")",
"==",
"1",
"and",
"next",
"(",
"iter",
"(",
"tiers",
")",
")",
"==",
"tier_name",
":",
"selected_task_ids",
".",
"update",
"(",
"task_to_tier",
")",
"return",
"sorted",
"(",
"selected_task_ids",
")"
] | [
136,
0
] | [
150,
36
] | python | en | ['en', 'en', 'en'] | True |
create_dev_set | (eval_setup, train_share=TRAIN_SHARE, seed=0) | Create a new train/test split from a train part of another eval setup. | Create a new train/test split from a train part of another eval setup. | def create_dev_set(eval_setup, train_share=TRAIN_SHARE, seed=0):
"""Create a new train/test split from a train part of another eval setup."""
dev_eval_setup = []
for train_task_ids, _ in eval_setup:
train_task_ids = phyre.util.stable_shuffle(train_task_ids,
f'make_dev{seed}')
num_train = int(len(train_task_ids) * train_share)
train, dev = train_task_ids[:num_train], train_task_ids[num_train:]
dev_eval_setup.append((train, [dev]))
return dev_eval_setup | [
"def",
"create_dev_set",
"(",
"eval_setup",
",",
"train_share",
"=",
"TRAIN_SHARE",
",",
"seed",
"=",
"0",
")",
":",
"dev_eval_setup",
"=",
"[",
"]",
"for",
"train_task_ids",
",",
"_",
"in",
"eval_setup",
":",
"train_task_ids",
"=",
"phyre",
".",
"util",
".",
"stable_shuffle",
"(",
"train_task_ids",
",",
"f'make_dev{seed}'",
")",
"num_train",
"=",
"int",
"(",
"len",
"(",
"train_task_ids",
")",
"*",
"train_share",
")",
"train",
",",
"dev",
"=",
"train_task_ids",
"[",
":",
"num_train",
"]",
",",
"train_task_ids",
"[",
"num_train",
":",
"]",
"dev_eval_setup",
".",
"append",
"(",
"(",
"train",
",",
"[",
"dev",
"]",
")",
")",
"return",
"dev_eval_setup"
] | [
153,
0
] | [
162,
25
] | python | en | ['en', 'en', 'en'] | True |
ball_single_instance | (max_per_tpl=10) | Eval setup where each task instance is in separate eval group.
The number of tasks that is randomly picked from each template is limited to
10.
| Eval setup where each task instance is in separate eval group. | def ball_single_instance(max_per_tpl=10) -> EvalSetup:
"""Eval setup where each task instance is in separate eval group.
The number of tasks that is randomly picked from each template is limited to
10.
"""
task_ids = get_task_ids_in_tier('ball')
tasks_per_tpl = _get_task_per_tpl(task_ids)
eval_setup = []
for _, task_ids_group in sorted(tasks_per_tpl.items()):
eval_task_ids = phyre.util.stable_shuffle(
task_ids_group, 'ball_online_ind_tasks')[:max_per_tpl]
for task_id in eval_task_ids:
eval_groups = ((task_id,),)
train_set = ()
train_group = (train_set, eval_groups)
eval_setup.append(train_group)
return eval_setup | [
"def",
"ball_single_instance",
"(",
"max_per_tpl",
"=",
"10",
")",
"->",
"EvalSetup",
":",
"task_ids",
"=",
"get_task_ids_in_tier",
"(",
"'ball'",
")",
"tasks_per_tpl",
"=",
"_get_task_per_tpl",
"(",
"task_ids",
")",
"eval_setup",
"=",
"[",
"]",
"for",
"_",
",",
"task_ids_group",
"in",
"sorted",
"(",
"tasks_per_tpl",
".",
"items",
"(",
")",
")",
":",
"eval_task_ids",
"=",
"phyre",
".",
"util",
".",
"stable_shuffle",
"(",
"task_ids_group",
",",
"'ball_online_ind_tasks'",
")",
"[",
":",
"max_per_tpl",
"]",
"for",
"task_id",
"in",
"eval_task_ids",
":",
"eval_groups",
"=",
"(",
"(",
"task_id",
",",
")",
",",
")",
"train_set",
"=",
"(",
")",
"train_group",
"=",
"(",
"train_set",
",",
"eval_groups",
")",
"eval_setup",
".",
"append",
"(",
"train_group",
")",
"return",
"eval_setup"
] | [
196,
0
] | [
214,
21
] | python | en | ['en', 'en', 'en'] | True |
ball_single_template | () | Eval setup where template tasks is a separate eval group. | Eval setup where template tasks is a separate eval group. | def ball_single_template() -> EvalSetup:
"""Eval setup where template tasks is a separate eval group."""
max_per_tpl = 10
task_ids = get_task_ids_in_tier('ball')
tasks_per_tpl = _get_task_per_tpl(task_ids)
eval_setup = []
for _, task_ids_group in sorted(tasks_per_tpl.items()):
task_ids_group = phyre.util.stable_shuffle(
task_ids_group, 'ball_online_ind_tasks')[:max_per_tpl]
eval_groups = (task_ids_group,)
train_set = ()
train_group = (train_set, eval_groups)
eval_setup.append(train_group)
return eval_setup | [
"def",
"ball_single_template",
"(",
")",
"->",
"EvalSetup",
":",
"max_per_tpl",
"=",
"10",
"task_ids",
"=",
"get_task_ids_in_tier",
"(",
"'ball'",
")",
"tasks_per_tpl",
"=",
"_get_task_per_tpl",
"(",
"task_ids",
")",
"eval_setup",
"=",
"[",
"]",
"for",
"_",
",",
"task_ids_group",
"in",
"sorted",
"(",
"tasks_per_tpl",
".",
"items",
"(",
")",
")",
":",
"task_ids_group",
"=",
"phyre",
".",
"util",
".",
"stable_shuffle",
"(",
"task_ids_group",
",",
"'ball_online_ind_tasks'",
")",
"[",
":",
"max_per_tpl",
"]",
"eval_groups",
"=",
"(",
"task_ids_group",
",",
")",
"train_set",
"=",
"(",
")",
"train_group",
"=",
"(",
"train_set",
",",
"eval_groups",
")",
"eval_setup",
".",
"append",
"(",
"train_group",
")",
"return",
"eval_setup"
] | [
233,
0
] | [
247,
21
] | python | en | ['en', 'en', 'en'] | True |
_cross_template | (tier, seed=1, dev_seed=None,
train_share=TRAIN_SHARE) | A set of train groups with half templates in train and half in test. | A set of train groups with half templates in train and half in test. | def _cross_template(tier, seed=1, dev_seed=None,
train_share=TRAIN_SHARE) -> EvalSetup:
"""A set of train groups with half templates in train and half in test."""
task_ids = get_task_ids_in_tier(tier)
tasks_per_tpl = collections.defaultdict(list)
for task_id in task_ids:
tasks_per_tpl[task_id.split(':')[0]].append(task_id)
key_order = phyre.util.stable_shuffle(list(tasks_per_tpl),
f'ball_cross_template_half_{seed}')
train_size = int(round(len(key_order) * train_share))
if dev_seed is not None:
key_order = key_order[:train_size]
key_order = phyre.util.stable_shuffle(
key_order, f'dev_ball_cross_template_half_{dev_seed}')
train_size = int(len(key_order) * train_share)
tasks_per_tpl = [tasks_per_tpl[key] for key in key_order]
train, test = tasks_per_tpl[:train_size], tasks_per_tpl[train_size:]
eval_setup = []
train_ids = sum(train, [])
eval_ids = sum(test, [])
train_group = (tuple(train_ids), [tuple(eval_ids)])
eval_setup.append(train_group)
return eval_setup | [
"def",
"_cross_template",
"(",
"tier",
",",
"seed",
"=",
"1",
",",
"dev_seed",
"=",
"None",
",",
"train_share",
"=",
"TRAIN_SHARE",
")",
"->",
"EvalSetup",
":",
"task_ids",
"=",
"get_task_ids_in_tier",
"(",
"tier",
")",
"tasks_per_tpl",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"task_id",
"in",
"task_ids",
":",
"tasks_per_tpl",
"[",
"task_id",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"]",
".",
"append",
"(",
"task_id",
")",
"key_order",
"=",
"phyre",
".",
"util",
".",
"stable_shuffle",
"(",
"list",
"(",
"tasks_per_tpl",
")",
",",
"f'ball_cross_template_half_{seed}'",
")",
"train_size",
"=",
"int",
"(",
"round",
"(",
"len",
"(",
"key_order",
")",
"*",
"train_share",
")",
")",
"if",
"dev_seed",
"is",
"not",
"None",
":",
"key_order",
"=",
"key_order",
"[",
":",
"train_size",
"]",
"key_order",
"=",
"phyre",
".",
"util",
".",
"stable_shuffle",
"(",
"key_order",
",",
"f'dev_ball_cross_template_half_{dev_seed}'",
")",
"train_size",
"=",
"int",
"(",
"len",
"(",
"key_order",
")",
"*",
"train_share",
")",
"tasks_per_tpl",
"=",
"[",
"tasks_per_tpl",
"[",
"key",
"]",
"for",
"key",
"in",
"key_order",
"]",
"train",
",",
"test",
"=",
"tasks_per_tpl",
"[",
":",
"train_size",
"]",
",",
"tasks_per_tpl",
"[",
"train_size",
":",
"]",
"eval_setup",
"=",
"[",
"]",
"train_ids",
"=",
"sum",
"(",
"train",
",",
"[",
"]",
")",
"eval_ids",
"=",
"sum",
"(",
"test",
",",
"[",
"]",
")",
"train_group",
"=",
"(",
"tuple",
"(",
"train_ids",
")",
",",
"[",
"tuple",
"(",
"eval_ids",
")",
"]",
")",
"eval_setup",
".",
"append",
"(",
"train_group",
")",
"return",
"eval_setup"
] | [
251,
0
] | [
273,
21
] | python | en | ['en', 'en', 'en'] | True |
_single_template | (tier, seed=1, dev_seed=None,
train_share=TRAIN_SHARE) | Each template is a separate group. | Each template is a separate group. | def _single_template(tier, seed=1, dev_seed=None,
train_share=TRAIN_SHARE) -> EvalSetup:
"""Each template is a separate group."""
task_ids = get_task_ids_in_tier(tier)
tasks_per_tpl = _get_task_per_tpl(task_ids)
eval_setup = []
for _, task_ids_group in sorted(tasks_per_tpl.items()):
task_ids_group = phyre.util.stable_shuffle(
task_ids_group, f'ball_online_ind_tasks{seed}')
train_size = int(round(len(task_ids_group) * train_share))
if not train_size:
continue
train_ids, eval_ids = (task_ids_group[:train_size],
task_ids_group[train_size:])
eval_groups = (tuple(eval_ids),)
train_set = tuple(train_ids)
train_group = (train_set, eval_groups)
eval_setup.append(train_group)
if dev_seed is not None:
eval_setup = create_dev_set(eval_setup, train_share, seed=dev_seed)
return eval_setup | [
"def",
"_single_template",
"(",
"tier",
",",
"seed",
"=",
"1",
",",
"dev_seed",
"=",
"None",
",",
"train_share",
"=",
"TRAIN_SHARE",
")",
"->",
"EvalSetup",
":",
"task_ids",
"=",
"get_task_ids_in_tier",
"(",
"tier",
")",
"tasks_per_tpl",
"=",
"_get_task_per_tpl",
"(",
"task_ids",
")",
"eval_setup",
"=",
"[",
"]",
"for",
"_",
",",
"task_ids_group",
"in",
"sorted",
"(",
"tasks_per_tpl",
".",
"items",
"(",
")",
")",
":",
"task_ids_group",
"=",
"phyre",
".",
"util",
".",
"stable_shuffle",
"(",
"task_ids_group",
",",
"f'ball_online_ind_tasks{seed}'",
")",
"train_size",
"=",
"int",
"(",
"round",
"(",
"len",
"(",
"task_ids_group",
")",
"*",
"train_share",
")",
")",
"if",
"not",
"train_size",
":",
"continue",
"train_ids",
",",
"eval_ids",
"=",
"(",
"task_ids_group",
"[",
":",
"train_size",
"]",
",",
"task_ids_group",
"[",
"train_size",
":",
"]",
")",
"eval_groups",
"=",
"(",
"tuple",
"(",
"eval_ids",
")",
",",
")",
"train_set",
"=",
"tuple",
"(",
"train_ids",
")",
"train_group",
"=",
"(",
"train_set",
",",
"eval_groups",
")",
"eval_setup",
".",
"append",
"(",
"train_group",
")",
"if",
"dev_seed",
"is",
"not",
"None",
":",
"eval_setup",
"=",
"create_dev_set",
"(",
"eval_setup",
",",
"train_share",
",",
"seed",
"=",
"dev_seed",
")",
"return",
"eval_setup"
] | [
277,
0
] | [
299,
21
] | python | en | ['en', 'en', 'en'] | True |
Evaluator.maybe_log_attempt | (self,
task_index: int,
status: SimulationStatusLike,
score: float = 0.0,
action: Sequence = None) | Logs status of attempt on task iff status is for a valid action.
Args:
task_index: index into task_ids of task.
status: simulation status of attempt on task.
score: Normalized (typically via sigmoid) score of how likely the
model thinks this action will solve the task.
Added by rgirdhar, optional for previous parts of code.
action: Actual action taken, to store in the results. Also added by
rgirdhar.
Returns:
True if attempt was logged (valid action, less than
MAX_TEST_ATTEMPTS made on task), else False.
Raises:
AssertionError: More than MAX_TEST_ATTEMPTS attempts were made on
the task.
| Logs status of attempt on task iff status is for a valid action. | def maybe_log_attempt(self,
task_index: int,
status: SimulationStatusLike,
score: float = 0.0,
action: Sequence = None) -> bool:
"""Logs status of attempt on task iff status is for a valid action.
Args:
task_index: index into task_ids of task.
status: simulation status of attempt on task.
score: Normalized (typically via sigmoid) score of how likely the
model thinks this action will solve the task.
Added by rgirdhar, optional for previous parts of code.
action: Actual action taken, to store in the results. Also added by
rgirdhar.
Returns:
True if attempt was logged (valid action, less than
MAX_TEST_ATTEMPTS made on task), else False.
Raises:
AssertionError: More than MAX_TEST_ATTEMPTS attempts were made on
the task.
"""
status = _normalize_sumulation_status(status)
if status.is_invalid():
return False
assert self.attempts_per_task_index[task_index] < MAX_TEST_ATTEMPTS, (
f'Task {self._task_ids[task_index]} of index {task_index} has '
f'{self.attempts_per_task_index[task_index]} attempts made, '
'greater than maximum number of test attempts '
f'{MAX_TEST_ATTEMPTS}')
task_id = self._task_ids[task_index]
data_tuple = (task_id, status, score, action.tolist())
self._log.append(data_tuple)
if task_id not in self._log_per_task_id:
self._log_per_task_id[task_id] = []
self._log_per_task_id[task_id].append(data_tuple)
self.attempts_per_task_index[task_index] += 1
return True | [
"def",
"maybe_log_attempt",
"(",
"self",
",",
"task_index",
":",
"int",
",",
"status",
":",
"SimulationStatusLike",
",",
"score",
":",
"float",
"=",
"0.0",
",",
"action",
":",
"Sequence",
"=",
"None",
")",
"->",
"bool",
":",
"status",
"=",
"_normalize_sumulation_status",
"(",
"status",
")",
"if",
"status",
".",
"is_invalid",
"(",
")",
":",
"return",
"False",
"assert",
"self",
".",
"attempts_per_task_index",
"[",
"task_index",
"]",
"<",
"MAX_TEST_ATTEMPTS",
",",
"(",
"f'Task {self._task_ids[task_index]} of index {task_index} has '",
"f'{self.attempts_per_task_index[task_index]} attempts made, '",
"'greater than maximum number of test attempts '",
"f'{MAX_TEST_ATTEMPTS}'",
")",
"task_id",
"=",
"self",
".",
"_task_ids",
"[",
"task_index",
"]",
"data_tuple",
"=",
"(",
"task_id",
",",
"status",
",",
"score",
",",
"action",
".",
"tolist",
"(",
")",
")",
"self",
".",
"_log",
".",
"append",
"(",
"data_tuple",
")",
"if",
"task_id",
"not",
"in",
"self",
".",
"_log_per_task_id",
":",
"self",
".",
"_log_per_task_id",
"[",
"task_id",
"]",
"=",
"[",
"]",
"self",
".",
"_log_per_task_id",
"[",
"task_id",
"]",
".",
"append",
"(",
"data_tuple",
")",
"self",
".",
"attempts_per_task_index",
"[",
"task_index",
"]",
"+=",
"1",
"return",
"True"
] | [
429,
4
] | [
469,
19
] | python | en | ['en', 'en', 'en'] | True |
Evaluator.compute_all_metrics | (self) | Computes metrics based on recorded log of simulation results.
Returns:
Dictionary mapping metric name to computed value.
| Computes metrics based on recorded log of simulation results. | def compute_all_metrics(self) -> Metrics:
"""Computes metrics based on recorded log of simulation results.
Returns:
Dictionary mapping metric name to computed value.
"""
return compute_metrics_normalized(self._log, len(self._task_ids)) | [
"def",
"compute_all_metrics",
"(",
"self",
")",
"->",
"Metrics",
":",
"return",
"compute_metrics_normalized",
"(",
"self",
".",
"_log",
",",
"len",
"(",
"self",
".",
"_task_ids",
")",
")"
] | [
471,
4
] | [
477,
73
] | python | en | ['en', 'en', 'en'] | True |
Evaluator.compute_all_metrics_per_task | (self) | Computes metrics for each task separately.
Returns:
Dictionary of task to dictionary mapping metric name to computed
value.
| Computes metrics for each task separately. | def compute_all_metrics_per_task(self) -> Dict[str, Metrics]:
"""Computes metrics for each task separately.
Returns:
Dictionary of task to dictionary mapping metric name to computed
value.
"""
res = {}
for task_id in self._task_ids:
if task_id in self._log_per_task_id:
res[task_id] = compute_metrics_normalized(
self._log_per_task_id[task_id], 1)
res[task_id]['logs'] = self._log_per_task_id[task_id]
else:
res[task_id] = {}
res[task_id]['logs'] = []
return res | [
"def",
"compute_all_metrics_per_task",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Metrics",
"]",
":",
"res",
"=",
"{",
"}",
"for",
"task_id",
"in",
"self",
".",
"_task_ids",
":",
"if",
"task_id",
"in",
"self",
".",
"_log_per_task_id",
":",
"res",
"[",
"task_id",
"]",
"=",
"compute_metrics_normalized",
"(",
"self",
".",
"_log_per_task_id",
"[",
"task_id",
"]",
",",
"1",
")",
"res",
"[",
"task_id",
"]",
"[",
"'logs'",
"]",
"=",
"self",
".",
"_log_per_task_id",
"[",
"task_id",
"]",
"else",
":",
"res",
"[",
"task_id",
"]",
"=",
"{",
"}",
"res",
"[",
"task_id",
"]",
"[",
"'logs'",
"]",
"=",
"[",
"]",
"return",
"res"
] | [
479,
4
] | [
495,
18
] | python | en | ['en', 'en', 'en'] | True |
Evaluator.get_auccess | (self, attempts: int = MAX_TEST_ATTEMPTS) | Calculated AUCCESS metric.
Starting in v0.0.1.1 renamed from get_aucess to get_auccess.
Args:
attempts: Number of attempts to use for calulation of auccess,
default MAX_TEST_ATTEMPTS.
Returns:
Result of AUCCESS calculation.
| Calculated AUCCESS metric. | def get_auccess(self, attempts: int = MAX_TEST_ATTEMPTS) -> float:
"""Calculated AUCCESS metric.
Starting in v0.0.1.1 renamed from get_aucess to get_auccess.
Args:
attempts: Number of attempts to use for calulation of auccess,
default MAX_TEST_ATTEMPTS.
Returns:
Result of AUCCESS calculation.
"""
metrics = self.compute_all_metrics()
return metrics[AUCCESS_METRIC][attempts] | [
"def",
"get_auccess",
"(",
"self",
",",
"attempts",
":",
"int",
"=",
"MAX_TEST_ATTEMPTS",
")",
"->",
"float",
":",
"metrics",
"=",
"self",
".",
"compute_all_metrics",
"(",
")",
"return",
"metrics",
"[",
"AUCCESS_METRIC",
"]",
"[",
"attempts",
"]"
] | [
501,
4
] | [
514,
48
] | python | en | ['en', 'en', 'en'] | True |
Evaluator.get_attempts_for_task | (self, task_index) |
Args:
task_index: index into task_ids of task.
Returns:
Number recorded attempts on task_index.
|
Args:
task_index: index into task_ids of task. | def get_attempts_for_task(self, task_index):
"""
Args:
task_index: index into task_ids of task.
Returns:
Number recorded attempts on task_index.
"""
return self.attempts_per_task_index[task_index] | [
"def",
"get_attempts_for_task",
"(",
"self",
",",
"task_index",
")",
":",
"return",
"self",
".",
"attempts_per_task_index",
"[",
"task_index",
"]"
] | [
516,
4
] | [
524,
55
] | python | en | ['en', 'error', 'th'] | False |
Evaluator.task_ids | (self) | Returns ordered list of tasks ids. | Returns ordered list of tasks ids. | def task_ids(self) -> Tuple[str, ...]:
"""Returns ordered list of tasks ids."""
return self._task_ids | [
"def",
"task_ids",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"return",
"self",
".",
"_task_ids"
] | [
527,
4
] | [
529,
29
] | python | en | ['en', 'et', 'en'] | True |