Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
list | start_point
list | end_point
list | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
_get_current_value | (caller, keyname, comparer=None, formatter=str, only_inherit=False) |
Return current value, marking if value comes from parent or set in this prototype.
Args:
keyname (str): Name of prototoype key to get current value of.
comparer (callable, optional): This will be called as comparer(prototype_value,
flattened_value) and is expected to return the value to show as the current
or inherited one. If not given, a straight comparison is used and what is returned
depends on the only_inherit setting.
formatter (callable, optional)): This will be called with the result of comparer.
only_inherit (bool, optional): If a current value should only be shown if all
the values are inherited from the prototype parent (otherwise, show an empty string).
Returns:
current (str): The current value.
|
Return current value, marking if value comes from parent or set in this prototype. | def _get_current_value(caller, keyname, comparer=None, formatter=str, only_inherit=False):
"""
Return current value, marking if value comes from parent or set in this prototype.
Args:
keyname (str): Name of prototoype key to get current value of.
comparer (callable, optional): This will be called as comparer(prototype_value,
flattened_value) and is expected to return the value to show as the current
or inherited one. If not given, a straight comparison is used and what is returned
depends on the only_inherit setting.
formatter (callable, optional)): This will be called with the result of comparer.
only_inherit (bool, optional): If a current value should only be shown if all
the values are inherited from the prototype parent (otherwise, show an empty string).
Returns:
current (str): The current value.
"""
def _default_comparer(protval, flatval):
if only_inherit:
return "" if protval else flatval
else:
return protval if protval else flatval
if not callable(comparer):
comparer = _default_comparer
prot = _get_menu_prototype(caller)
flat_prot = _get_flat_menu_prototype(caller)
out = ""
if keyname in prot:
if keyname in flat_prot:
out = formatter(comparer(prot[keyname], flat_prot[keyname]))
if only_inherit:
if str(out).strip():
return "|WCurrent|n {} |W(|binherited|W):|n {}".format(keyname, out)
return ""
else:
if out:
return "|WCurrent|n {}|W:|n {}".format(keyname, out)
return "|W[No {} set]|n".format(keyname)
elif only_inherit:
return ""
else:
out = formatter(prot[keyname])
return "|WCurrent|n {}|W:|n {}".format(keyname, out)
elif keyname in flat_prot:
out = formatter(flat_prot[keyname])
if out:
return "|WCurrent|n {} |W(|n|binherited|W):|n {}".format(keyname, out)
else:
return ""
elif only_inherit:
return ""
else:
return "|W[No {} set]|n".format(keyname) | [
"def",
"_get_current_value",
"(",
"caller",
",",
"keyname",
",",
"comparer",
"=",
"None",
",",
"formatter",
"=",
"str",
",",
"only_inherit",
"=",
"False",
")",
":",
"def",
"_default_comparer",
"(",
"protval",
",",
"flatval",
")",
":",
"if",
"only_inherit",
":",
"return",
"\"\"",
"if",
"protval",
"else",
"flatval",
"else",
":",
"return",
"protval",
"if",
"protval",
"else",
"flatval",
"if",
"not",
"callable",
"(",
"comparer",
")",
":",
"comparer",
"=",
"_default_comparer",
"prot",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"flat_prot",
"=",
"_get_flat_menu_prototype",
"(",
"caller",
")",
"out",
"=",
"\"\"",
"if",
"keyname",
"in",
"prot",
":",
"if",
"keyname",
"in",
"flat_prot",
":",
"out",
"=",
"formatter",
"(",
"comparer",
"(",
"prot",
"[",
"keyname",
"]",
",",
"flat_prot",
"[",
"keyname",
"]",
")",
")",
"if",
"only_inherit",
":",
"if",
"str",
"(",
"out",
")",
".",
"strip",
"(",
")",
":",
"return",
"\"|WCurrent|n {} |W(|binherited|W):|n {}\"",
".",
"format",
"(",
"keyname",
",",
"out",
")",
"return",
"\"\"",
"else",
":",
"if",
"out",
":",
"return",
"\"|WCurrent|n {}|W:|n {}\"",
".",
"format",
"(",
"keyname",
",",
"out",
")",
"return",
"\"|W[No {} set]|n\"",
".",
"format",
"(",
"keyname",
")",
"elif",
"only_inherit",
":",
"return",
"\"\"",
"else",
":",
"out",
"=",
"formatter",
"(",
"prot",
"[",
"keyname",
"]",
")",
"return",
"\"|WCurrent|n {}|W:|n {}\"",
".",
"format",
"(",
"keyname",
",",
"out",
")",
"elif",
"keyname",
"in",
"flat_prot",
":",
"out",
"=",
"formatter",
"(",
"flat_prot",
"[",
"keyname",
"]",
")",
"if",
"out",
":",
"return",
"\"|WCurrent|n {} |W(|n|binherited|W):|n {}\"",
".",
"format",
"(",
"keyname",
",",
"out",
")",
"else",
":",
"return",
"\"\"",
"elif",
"only_inherit",
":",
"return",
"\"\"",
"else",
":",
"return",
"\"|W[No {} set]|n\"",
".",
"format",
"(",
"keyname",
")"
] | [
286,
0
] | [
341,
48
] | python | en | ['en', 'error', 'th'] | False |
_default_parse | (raw_inp, choices, *args) |
Helper to parse default input to a node decorated with the node_list decorator on
the form l1, l 2, look 1, etc. Spaces are ignored, as is case.
Args:
raw_inp (str): Input from the user.
choices (list): List of available options on the node listing (list of strings).
args (tuples): The available actions, each specifed as a tuple (name, alias, ...)
Returns:
choice (str): A choice among the choices, or None if no match was found.
action (str): The action operating on the choice, or None.
|
Helper to parse default input to a node decorated with the node_list decorator on
the form l1, l 2, look 1, etc. Spaces are ignored, as is case. | def _default_parse(raw_inp, choices, *args):
"""
Helper to parse default input to a node decorated with the node_list decorator on
the form l1, l 2, look 1, etc. Spaces are ignored, as is case.
Args:
raw_inp (str): Input from the user.
choices (list): List of available options on the node listing (list of strings).
args (tuples): The available actions, each specifed as a tuple (name, alias, ...)
Returns:
choice (str): A choice among the choices, or None if no match was found.
action (str): The action operating on the choice, or None.
"""
raw_inp = raw_inp.lower().strip()
mapping = {t.lower(): tup[0] for tup in args for t in tup}
match = re.match(r"(%s)\s*?(\d+)$" % "|".join(mapping.keys()), raw_inp)
if match:
action = mapping.get(match.group(1), None)
num = int(match.group(2)) - 1
num = num if 0 <= num < len(choices) else None
if action is not None and num is not None:
return choices[num], action
return None, None | [
"def",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"*",
"args",
")",
":",
"raw_inp",
"=",
"raw_inp",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"mapping",
"=",
"{",
"t",
".",
"lower",
"(",
")",
":",
"tup",
"[",
"0",
"]",
"for",
"tup",
"in",
"args",
"for",
"t",
"in",
"tup",
"}",
"match",
"=",
"re",
".",
"match",
"(",
"r\"(%s)\\s*?(\\d+)$\"",
"%",
"\"|\"",
".",
"join",
"(",
"mapping",
".",
"keys",
"(",
")",
")",
",",
"raw_inp",
")",
"if",
"match",
":",
"action",
"=",
"mapping",
".",
"get",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"None",
")",
"num",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"-",
"1",
"num",
"=",
"num",
"if",
"0",
"<=",
"num",
"<",
"len",
"(",
"choices",
")",
"else",
"None",
"if",
"action",
"is",
"not",
"None",
"and",
"num",
"is",
"not",
"None",
":",
"return",
"choices",
"[",
"num",
"]",
",",
"action",
"return",
"None",
",",
"None"
] | [
344,
0
] | [
367,
21
] | python | en | ['en', 'error', 'th'] | False |
node_validate_prototype | (caller, raw_string, **kwargs) | General node to view and validate a protototype | General node to view and validate a protototype | def node_validate_prototype(caller, raw_string, **kwargs):
"""General node to view and validate a protototype"""
prototype = _get_flat_menu_prototype(caller, refresh=True, validate=False)
prev_node = kwargs.get("back", "index")
_, text = _validate_prototype(prototype)
helptext = """
The validator checks if the prototype's various values are on the expected form. It also tests
any $protfuncs.
"""
text = (text, helptext)
options = _wizard_options(None, prev_node, None)
options.append({"key": "_default",
"goto": "node_" + prev_node})
return text, options | [
"def",
"node_validate_prototype",
"(",
"caller",
",",
"raw_string",
",",
"*",
"*",
"kwargs",
")",
":",
"prototype",
"=",
"_get_flat_menu_prototype",
"(",
"caller",
",",
"refresh",
"=",
"True",
",",
"validate",
"=",
"False",
")",
"prev_node",
"=",
"kwargs",
".",
"get",
"(",
"\"back\"",
",",
"\"index\"",
")",
"_",
",",
"text",
"=",
"_validate_prototype",
"(",
"prototype",
")",
"helptext",
"=",
"\"\"\"\n The validator checks if the prototype's various values are on the expected form. It also tests\n any $protfuncs.\n\n \"\"\"",
"text",
"=",
"(",
"text",
",",
"helptext",
")",
"options",
"=",
"_wizard_options",
"(",
"None",
",",
"prev_node",
",",
"None",
")",
"options",
".",
"append",
"(",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"\"node_\"",
"+",
"prev_node",
"}",
")",
"return",
"text",
",",
"options"
] | [
376,
0
] | [
395,
24
] | python | en | ['en', 'en', 'en'] | True |
node_examine_entity | (caller, raw_string, **kwargs) |
General node to view a text and then return to previous node. Kwargs should contain "text" for
the text to show and 'back" pointing to the node to return to.
|
General node to view a text and then return to previous node. Kwargs should contain "text" for
the text to show and 'back" pointing to the node to return to.
| def node_examine_entity(caller, raw_string, **kwargs):
"""
General node to view a text and then return to previous node. Kwargs should contain "text" for
the text to show and 'back" pointing to the node to return to.
"""
text = kwargs.get("text", "Nothing was found here.")
helptext = "Use |wback|n to return to the previous node."
prev_node = kwargs.get('back', 'index')
text = (text, helptext)
options = _wizard_options(None, prev_node, None)
options.append({"key": "_default",
"goto": "node_" + prev_node})
return text, options | [
"def",
"node_examine_entity",
"(",
"caller",
",",
"raw_string",
",",
"*",
"*",
"kwargs",
")",
":",
"text",
"=",
"kwargs",
".",
"get",
"(",
"\"text\"",
",",
"\"Nothing was found here.\"",
")",
"helptext",
"=",
"\"Use |wback|n to return to the previous node.\"",
"prev_node",
"=",
"kwargs",
".",
"get",
"(",
"'back'",
",",
"'index'",
")",
"text",
"=",
"(",
"text",
",",
"helptext",
")",
"options",
"=",
"_wizard_options",
"(",
"None",
",",
"prev_node",
",",
"None",
")",
"options",
".",
"append",
"(",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"\"node_\"",
"+",
"prev_node",
"}",
")",
"return",
"text",
",",
"options"
] | [
400,
0
] | [
415,
24
] | python | en | ['en', 'error', 'th'] | False |
_search_object | (caller) | update search term based on query stored on menu; store match too | update search term based on query stored on menu; store match too | def _search_object(caller):
"update search term based on query stored on menu; store match too"
try:
searchstring = caller.ndb._menutree.olc_search_object_term.strip()
caller.ndb._menutree.olc_search_object_matches = []
except AttributeError:
return []
if not searchstring:
caller.msg("Must specify a search criterion.")
return []
is_dbref = utils.dbref(searchstring)
is_account = searchstring.startswith("*")
if is_dbref or is_account:
if is_dbref:
# a dbref search
results = caller.search(searchstring, global_search=True, quiet=True)
else:
# an account search
searchstring = searchstring.lstrip("*")
results = caller.search_account(searchstring, quiet=True)
else:
keyquery = Q(db_key__istartswith=searchstring)
aliasquery = Q(db_tags__db_key__istartswith=searchstring,
db_tags__db_tagtype__iexact="alias")
results = ObjectDB.objects.filter(keyquery | aliasquery).distinct()
caller.msg("Searching for '{}' ...".format(searchstring))
caller.ndb._menutree.olc_search_object_matches = results
return ["{}(#{})".format(obj.key, obj.id) for obj in results] | [
"def",
"_search_object",
"(",
"caller",
")",
":",
"try",
":",
"searchstring",
"=",
"caller",
".",
"ndb",
".",
"_menutree",
".",
"olc_search_object_term",
".",
"strip",
"(",
")",
"caller",
".",
"ndb",
".",
"_menutree",
".",
"olc_search_object_matches",
"=",
"[",
"]",
"except",
"AttributeError",
":",
"return",
"[",
"]",
"if",
"not",
"searchstring",
":",
"caller",
".",
"msg",
"(",
"\"Must specify a search criterion.\"",
")",
"return",
"[",
"]",
"is_dbref",
"=",
"utils",
".",
"dbref",
"(",
"searchstring",
")",
"is_account",
"=",
"searchstring",
".",
"startswith",
"(",
"\"*\"",
")",
"if",
"is_dbref",
"or",
"is_account",
":",
"if",
"is_dbref",
":",
"# a dbref search",
"results",
"=",
"caller",
".",
"search",
"(",
"searchstring",
",",
"global_search",
"=",
"True",
",",
"quiet",
"=",
"True",
")",
"else",
":",
"# an account search",
"searchstring",
"=",
"searchstring",
".",
"lstrip",
"(",
"\"*\"",
")",
"results",
"=",
"caller",
".",
"search_account",
"(",
"searchstring",
",",
"quiet",
"=",
"True",
")",
"else",
":",
"keyquery",
"=",
"Q",
"(",
"db_key__istartswith",
"=",
"searchstring",
")",
"aliasquery",
"=",
"Q",
"(",
"db_tags__db_key__istartswith",
"=",
"searchstring",
",",
"db_tags__db_tagtype__iexact",
"=",
"\"alias\"",
")",
"results",
"=",
"ObjectDB",
".",
"objects",
".",
"filter",
"(",
"keyquery",
"|",
"aliasquery",
")",
".",
"distinct",
"(",
")",
"caller",
".",
"msg",
"(",
"\"Searching for '{}' ...\"",
".",
"format",
"(",
"searchstring",
")",
")",
"caller",
".",
"ndb",
".",
"_menutree",
".",
"olc_search_object_matches",
"=",
"results",
"return",
"[",
"\"{}(#{})\"",
".",
"format",
"(",
"obj",
".",
"key",
",",
"obj",
".",
"id",
")",
"for",
"obj",
"in",
"results",
"]"
] | [
420,
0
] | [
452,
65
] | python | en | ['en', 'en', 'en'] | True |
_object_search_actions | (caller, raw_inp, **kwargs) | All this does is to queue a search query | All this does is to queue a search query | def _object_search_actions(caller, raw_inp, **kwargs):
"All this does is to queue a search query"
choices = kwargs['available_choices']
obj_entry, action = _default_parse(
raw_inp, choices, ("examine", "e"), ("create prototype from object", "create", "c"))
raw_inp = raw_inp.strip()
if obj_entry:
num = choices.index(obj_entry)
matches = caller.ndb._menutree.olc_search_object_matches
obj = matches[num]
prot = spawner.prototype_from_object(obj)
if action == "examine":
if not obj.access(caller, 'examine'):
caller.msg("\n|rYou don't have 'examine' access on this object.|n")
del caller.ndb._menutree.olc_search_object_term
return "node_search_object"
txt = protlib.prototype_to_str(prot)
return "node_examine_entity", {"text": txt, "back": "search_object"}
else:
# load prototype
if not obj.access(caller, 'control'):
caller.msg("|rYou don't have access to do this with this object.|n")
del caller.ndb._menutree.olc_search_object_term
return "node_search_object"
_set_menu_prototype(caller, prot)
caller.msg("Created prototype from object.")
return "node_index"
elif raw_inp:
caller.ndb._menutree.olc_search_object_term = raw_inp
return "node_search_object", kwargs
else:
# empty input - exit back to previous node
prev_node = "node_" + kwargs.get("back", "index")
return prev_node | [
"def",
"_object_search_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
"[",
"'available_choices'",
"]",
"obj_entry",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"\"examine\"",
",",
"\"e\"",
")",
",",
"(",
"\"create prototype from object\"",
",",
"\"create\"",
",",
"\"c\"",
")",
")",
"raw_inp",
"=",
"raw_inp",
".",
"strip",
"(",
")",
"if",
"obj_entry",
":",
"num",
"=",
"choices",
".",
"index",
"(",
"obj_entry",
")",
"matches",
"=",
"caller",
".",
"ndb",
".",
"_menutree",
".",
"olc_search_object_matches",
"obj",
"=",
"matches",
"[",
"num",
"]",
"prot",
"=",
"spawner",
".",
"prototype_from_object",
"(",
"obj",
")",
"if",
"action",
"==",
"\"examine\"",
":",
"if",
"not",
"obj",
".",
"access",
"(",
"caller",
",",
"'examine'",
")",
":",
"caller",
".",
"msg",
"(",
"\"\\n|rYou don't have 'examine' access on this object.|n\"",
")",
"del",
"caller",
".",
"ndb",
".",
"_menutree",
".",
"olc_search_object_term",
"return",
"\"node_search_object\"",
"txt",
"=",
"protlib",
".",
"prototype_to_str",
"(",
"prot",
")",
"return",
"\"node_examine_entity\"",
",",
"{",
"\"text\"",
":",
"txt",
",",
"\"back\"",
":",
"\"search_object\"",
"}",
"else",
":",
"# load prototype",
"if",
"not",
"obj",
".",
"access",
"(",
"caller",
",",
"'control'",
")",
":",
"caller",
".",
"msg",
"(",
"\"|rYou don't have access to do this with this object.|n\"",
")",
"del",
"caller",
".",
"ndb",
".",
"_menutree",
".",
"olc_search_object_term",
"return",
"\"node_search_object\"",
"_set_menu_prototype",
"(",
"caller",
",",
"prot",
")",
"caller",
".",
"msg",
"(",
"\"Created prototype from object.\"",
")",
"return",
"\"node_index\"",
"elif",
"raw_inp",
":",
"caller",
".",
"ndb",
".",
"_menutree",
".",
"olc_search_object_term",
"=",
"raw_inp",
"return",
"\"node_search_object\"",
",",
"kwargs",
"else",
":",
"# empty input - exit back to previous node",
"prev_node",
"=",
"\"node_\"",
"+",
"kwargs",
".",
"get",
"(",
"\"back\"",
",",
"\"index\"",
")",
"return",
"prev_node"
] | [
471,
0
] | [
512,
24
] | python | en | ['en', 'en', 'en'] | True |
node_search_object | (caller, raw_inp, **kwargs) |
Node for searching for an existing object.
|
Node for searching for an existing object.
| def node_search_object(caller, raw_inp, **kwargs):
"""
Node for searching for an existing object.
"""
try:
matches = caller.ndb._menutree.olc_search_object_matches
except AttributeError:
matches = []
nmatches = len(matches)
prev_node = kwargs.get("back", "index")
if matches:
text = """
Found {num} match{post}.
(|RWarning: creating a prototype will |roverwrite|r |Rthe current prototype!)|n""".format(
num=nmatches, post="es" if nmatches > 1 else "")
_set_actioninfo(caller, _format_list_actions(
"examine", "create prototype from object", prefix="Actions: "))
else:
text = "Enter search criterion."
helptext = """
You can search objects by specifying partial key, alias or its exact #dbref. Use *query to
search for an Account instead.
Once having found any matches you can choose to examine it or use |ccreate prototype from
object|n. If doing the latter, a prototype will be calculated from the selected object and
loaded as the new 'current' prototype. This is useful for having a base to build from but be
careful you are not throwing away any existing, unsaved, prototype work!
"""
text = (text, helptext)
options = _wizard_options(None, prev_node, None)
options.append({"key": "_default",
"goto": (_object_search_actions, {"back": prev_node})})
return text, options | [
"def",
"node_search_object",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"matches",
"=",
"caller",
".",
"ndb",
".",
"_menutree",
".",
"olc_search_object_matches",
"except",
"AttributeError",
":",
"matches",
"=",
"[",
"]",
"nmatches",
"=",
"len",
"(",
"matches",
")",
"prev_node",
"=",
"kwargs",
".",
"get",
"(",
"\"back\"",
",",
"\"index\"",
")",
"if",
"matches",
":",
"text",
"=",
"\"\"\"\n Found {num} match{post}.\n\n (|RWarning: creating a prototype will |roverwrite|r |Rthe current prototype!)|n\"\"\"",
".",
"format",
"(",
"num",
"=",
"nmatches",
",",
"post",
"=",
"\"es\"",
"if",
"nmatches",
">",
"1",
"else",
"\"\"",
")",
"_set_actioninfo",
"(",
"caller",
",",
"_format_list_actions",
"(",
"\"examine\"",
",",
"\"create prototype from object\"",
",",
"prefix",
"=",
"\"Actions: \"",
")",
")",
"else",
":",
"text",
"=",
"\"Enter search criterion.\"",
"helptext",
"=",
"\"\"\"\n You can search objects by specifying partial key, alias or its exact #dbref. Use *query to\n search for an Account instead.\n\n Once having found any matches you can choose to examine it or use |ccreate prototype from\n object|n. If doing the latter, a prototype will be calculated from the selected object and\n loaded as the new 'current' prototype. This is useful for having a base to build from but be\n careful you are not throwing away any existing, unsaved, prototype work!\n \"\"\"",
"text",
"=",
"(",
"text",
",",
"helptext",
")",
"options",
"=",
"_wizard_options",
"(",
"None",
",",
"prev_node",
",",
"None",
")",
"options",
".",
"append",
"(",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"(",
"_object_search_actions",
",",
"{",
"\"back\"",
":",
"prev_node",
"}",
")",
"}",
")",
"return",
"text",
",",
"options"
] | [
516,
0
] | [
554,
24
] | python | en | ['en', 'error', 'th'] | False |
_all_prototype_parents | (caller) | Return prototype_key of all available prototypes for listing in menu | Return prototype_key of all available prototypes for listing in menu | def _all_prototype_parents(caller):
"""Return prototype_key of all available prototypes for listing in menu"""
return [prototype["prototype_key"]
for prototype in protlib.search_prototype() if "prototype_key" in prototype] | [
"def",
"_all_prototype_parents",
"(",
"caller",
")",
":",
"return",
"[",
"prototype",
"[",
"\"prototype_key\"",
"]",
"for",
"prototype",
"in",
"protlib",
".",
"search_prototype",
"(",
")",
"if",
"\"prototype_key\"",
"in",
"prototype",
"]"
] | [
707,
0
] | [
710,
88
] | python | en | ['en', 'en', 'en'] | True |
_prototype_parent_actions | (caller, raw_inp, **kwargs) | Parse the default Convert prototype to a string representation for closer inspection | Parse the default Convert prototype to a string representation for closer inspection | def _prototype_parent_actions(caller, raw_inp, **kwargs):
"""Parse the default Convert prototype to a string representation for closer inspection"""
choices = kwargs.get("available_choices", [])
prototype_parent, action = _default_parse(
raw_inp, choices, ("examine", "e", "l"), ("add", "a"), ("remove", "r", 'delete', 'd'))
if prototype_parent:
# a selection of parent was made
prototype_parent = protlib.search_prototype(key=prototype_parent)[0]
prototype_parent_key = prototype_parent['prototype_key']
# which action to apply on the selection
if action == 'examine':
# examine the prototype
txt = protlib.prototype_to_str(prototype_parent)
kwargs['text'] = txt
kwargs['back'] = 'prototype_parent'
return "node_examine_entity", kwargs
elif action == 'add':
# add/append parent
prot = _get_menu_prototype(caller)
current_prot_parent = prot.get('prototype_parent', None)
if current_prot_parent:
current_prot_parent = utils.make_iter(current_prot_parent)
if prototype_parent_key in current_prot_parent:
caller.msg("Prototype_parent {} is already used.".format(prototype_parent_key))
return "node_prototype_parent"
else:
current_prot_parent.append(prototype_parent_key)
caller.msg("Add prototype parent for multi-inheritance.")
else:
current_prot_parent = prototype_parent_key
try:
if prototype_parent:
spawner.flatten_prototype(prototype_parent, validate=True)
else:
raise RuntimeError("Not found.")
except RuntimeError as err:
caller.msg("Selected prototype-parent {} "
"caused Error(s):\n|r{}|n".format(prototype_parent, err))
return "node_prototype_parent"
_set_prototype_value(caller, "prototype_parent", current_prot_parent)
_get_flat_menu_prototype(caller, refresh=True)
elif action == "remove":
# remove prototype parent
prot = _get_menu_prototype(caller)
current_prot_parent = prot.get('prototype_parent', None)
if current_prot_parent:
current_prot_parent = utils.make_iter(current_prot_parent)
try:
current_prot_parent.remove(prototype_parent_key)
_set_prototype_value(caller, 'prototype_parent', current_prot_parent)
_get_flat_menu_prototype(caller, refresh=True)
caller.msg("Removed prototype parent {}.".format(prototype_parent_key))
except ValueError:
caller.msg("|rPrototype-parent {} could not be removed.".format(
prototype_parent_key))
return 'node_prototype_parent' | [
"def",
"_prototype_parent_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"\"available_choices\"",
",",
"[",
"]",
")",
"prototype_parent",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"\"examine\"",
",",
"\"e\"",
",",
"\"l\"",
")",
",",
"(",
"\"add\"",
",",
"\"a\"",
")",
",",
"(",
"\"remove\"",
",",
"\"r\"",
",",
"'delete'",
",",
"'d'",
")",
")",
"if",
"prototype_parent",
":",
"# a selection of parent was made",
"prototype_parent",
"=",
"protlib",
".",
"search_prototype",
"(",
"key",
"=",
"prototype_parent",
")",
"[",
"0",
"]",
"prototype_parent_key",
"=",
"prototype_parent",
"[",
"'prototype_key'",
"]",
"# which action to apply on the selection",
"if",
"action",
"==",
"'examine'",
":",
"# examine the prototype",
"txt",
"=",
"protlib",
".",
"prototype_to_str",
"(",
"prototype_parent",
")",
"kwargs",
"[",
"'text'",
"]",
"=",
"txt",
"kwargs",
"[",
"'back'",
"]",
"=",
"'prototype_parent'",
"return",
"\"node_examine_entity\"",
",",
"kwargs",
"elif",
"action",
"==",
"'add'",
":",
"# add/append parent",
"prot",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"current_prot_parent",
"=",
"prot",
".",
"get",
"(",
"'prototype_parent'",
",",
"None",
")",
"if",
"current_prot_parent",
":",
"current_prot_parent",
"=",
"utils",
".",
"make_iter",
"(",
"current_prot_parent",
")",
"if",
"prototype_parent_key",
"in",
"current_prot_parent",
":",
"caller",
".",
"msg",
"(",
"\"Prototype_parent {} is already used.\"",
".",
"format",
"(",
"prototype_parent_key",
")",
")",
"return",
"\"node_prototype_parent\"",
"else",
":",
"current_prot_parent",
".",
"append",
"(",
"prototype_parent_key",
")",
"caller",
".",
"msg",
"(",
"\"Add prototype parent for multi-inheritance.\"",
")",
"else",
":",
"current_prot_parent",
"=",
"prototype_parent_key",
"try",
":",
"if",
"prototype_parent",
":",
"spawner",
".",
"flatten_prototype",
"(",
"prototype_parent",
",",
"validate",
"=",
"True",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Not found.\"",
")",
"except",
"RuntimeError",
"as",
"err",
":",
"caller",
".",
"msg",
"(",
"\"Selected prototype-parent {} \"",
"\"caused Error(s):\\n|r{}|n\"",
".",
"format",
"(",
"prototype_parent",
",",
"err",
")",
")",
"return",
"\"node_prototype_parent\"",
"_set_prototype_value",
"(",
"caller",
",",
"\"prototype_parent\"",
",",
"current_prot_parent",
")",
"_get_flat_menu_prototype",
"(",
"caller",
",",
"refresh",
"=",
"True",
")",
"elif",
"action",
"==",
"\"remove\"",
":",
"# remove prototype parent",
"prot",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"current_prot_parent",
"=",
"prot",
".",
"get",
"(",
"'prototype_parent'",
",",
"None",
")",
"if",
"current_prot_parent",
":",
"current_prot_parent",
"=",
"utils",
".",
"make_iter",
"(",
"current_prot_parent",
")",
"try",
":",
"current_prot_parent",
".",
"remove",
"(",
"prototype_parent_key",
")",
"_set_prototype_value",
"(",
"caller",
",",
"'prototype_parent'",
",",
"current_prot_parent",
")",
"_get_flat_menu_prototype",
"(",
"caller",
",",
"refresh",
"=",
"True",
")",
"caller",
".",
"msg",
"(",
"\"Removed prototype parent {}.\"",
".",
"format",
"(",
"prototype_parent_key",
")",
")",
"except",
"ValueError",
":",
"caller",
".",
"msg",
"(",
"\"|rPrototype-parent {} could not be removed.\"",
".",
"format",
"(",
"prototype_parent_key",
")",
")",
"return",
"'node_prototype_parent'"
] | [
713,
0
] | [
770,
38
] | python | en | ['en', 'en', 'en'] | True |
_all_typeclasses | (caller) | Get name of available typeclasses. | Get name of available typeclasses. | def _all_typeclasses(caller):
"""Get name of available typeclasses."""
return list(name for name in
sorted(utils.get_all_typeclasses("evennia.objects.models.ObjectDB").keys())
if name != "evennia.objects.models.ObjectDB") | [
"def",
"_all_typeclasses",
"(",
"caller",
")",
":",
"return",
"list",
"(",
"name",
"for",
"name",
"in",
"sorted",
"(",
"utils",
".",
"get_all_typeclasses",
"(",
"\"evennia.objects.models.ObjectDB\"",
")",
".",
"keys",
"(",
")",
")",
"if",
"name",
"!=",
"\"evennia.objects.models.ObjectDB\"",
")"
] | [
846,
0
] | [
850,
61
] | python | en | ['en', 'en', 'en'] | True |
_typeclass_actions | (caller, raw_inp, **kwargs) | Parse actions for typeclass listing | Parse actions for typeclass listing | def _typeclass_actions(caller, raw_inp, **kwargs):
"""Parse actions for typeclass listing"""
choices = kwargs.get("available_choices", [])
typeclass_path, action = _default_parse(
raw_inp, choices, ("examine", "e", "l"), ("remove", "r", "delete", "d"))
if typeclass_path:
if action == 'examine':
typeclass = utils.get_all_typeclasses().get(typeclass_path)
if typeclass:
docstr = []
for line in typeclass.__doc__.split("\n"):
if line.strip():
docstr.append(line)
elif docstr:
break
docstr = '\n'.join(docstr) if docstr else "<empty>"
txt = "Typeclass |c{typeclass_path}|n; " \
"First paragraph of docstring:\n\n{docstring}".format(
typeclass_path=typeclass_path, docstring=docstr)
else:
txt = "This is typeclass |y{}|n.".format(typeclass)
return "node_examine_entity", {"text": txt, "back": "typeclass"}
elif action == 'remove':
prototype = _get_menu_prototype(caller)
old_typeclass = prototype.pop('typeclass', None)
if old_typeclass:
_set_menu_prototype(caller, prototype)
caller.msg("Cleared typeclass {}.".format(old_typeclass))
else:
caller.msg("No typeclass to remove.")
return "node_typeclass" | [
"def",
"_typeclass_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"\"available_choices\"",
",",
"[",
"]",
")",
"typeclass_path",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"\"examine\"",
",",
"\"e\"",
",",
"\"l\"",
")",
",",
"(",
"\"remove\"",
",",
"\"r\"",
",",
"\"delete\"",
",",
"\"d\"",
")",
")",
"if",
"typeclass_path",
":",
"if",
"action",
"==",
"'examine'",
":",
"typeclass",
"=",
"utils",
".",
"get_all_typeclasses",
"(",
")",
".",
"get",
"(",
"typeclass_path",
")",
"if",
"typeclass",
":",
"docstr",
"=",
"[",
"]",
"for",
"line",
"in",
"typeclass",
".",
"__doc__",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"line",
".",
"strip",
"(",
")",
":",
"docstr",
".",
"append",
"(",
"line",
")",
"elif",
"docstr",
":",
"break",
"docstr",
"=",
"'\\n'",
".",
"join",
"(",
"docstr",
")",
"if",
"docstr",
"else",
"\"<empty>\"",
"txt",
"=",
"\"Typeclass |c{typeclass_path}|n; \"",
"\"First paragraph of docstring:\\n\\n{docstring}\"",
".",
"format",
"(",
"typeclass_path",
"=",
"typeclass_path",
",",
"docstring",
"=",
"docstr",
")",
"else",
":",
"txt",
"=",
"\"This is typeclass |y{}|n.\"",
".",
"format",
"(",
"typeclass",
")",
"return",
"\"node_examine_entity\"",
",",
"{",
"\"text\"",
":",
"txt",
",",
"\"back\"",
":",
"\"typeclass\"",
"}",
"elif",
"action",
"==",
"'remove'",
":",
"prototype",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"old_typeclass",
"=",
"prototype",
".",
"pop",
"(",
"'typeclass'",
",",
"None",
")",
"if",
"old_typeclass",
":",
"_set_menu_prototype",
"(",
"caller",
",",
"prototype",
")",
"caller",
".",
"msg",
"(",
"\"Cleared typeclass {}.\"",
".",
"format",
"(",
"old_typeclass",
")",
")",
"else",
":",
"caller",
".",
"msg",
"(",
"\"No typeclass to remove.\"",
")",
"return",
"\"node_typeclass\""
] | [
853,
0
] | [
885,
31
] | python | en | ['en', 'en', 'en'] | True |
_typeclass_select | (caller, typeclass) | Select typeclass from list and add it to prototype. Return next node to go to. | Select typeclass from list and add it to prototype. Return next node to go to. | def _typeclass_select(caller, typeclass):
"""Select typeclass from list and add it to prototype. Return next node to go to."""
ret = _set_property(caller, typeclass, prop='typeclass', processor=str)
caller.msg("Selected typeclass |c{}|n.".format(typeclass))
return ret | [
"def",
"_typeclass_select",
"(",
"caller",
",",
"typeclass",
")",
":",
"ret",
"=",
"_set_property",
"(",
"caller",
",",
"typeclass",
",",
"prop",
"=",
"'typeclass'",
",",
"processor",
"=",
"str",
")",
"caller",
".",
"msg",
"(",
"\"Selected typeclass |c{}|n.\"",
".",
"format",
"(",
"typeclass",
")",
")",
"return",
"ret"
] | [
888,
0
] | [
892,
14
] | python | en | ['en', 'en', 'en'] | True |
_all_aliases | (caller) | Get aliases in prototype | Get aliases in prototype | def _all_aliases(caller):
"Get aliases in prototype"
prototype = _get_menu_prototype(caller)
return prototype.get("aliases", []) | [
"def",
"_all_aliases",
"(",
"caller",
")",
":",
"prototype",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"return",
"prototype",
".",
"get",
"(",
"\"aliases\"",
",",
"[",
"]",
")"
] | [
956,
0
] | [
959,
39
] | python | en | ['en', 'sr', 'en'] | True |
_aliases_select | (caller, alias) | Add numbers as aliases | Add numbers as aliases | def _aliases_select(caller, alias):
"Add numbers as aliases"
aliases = _all_aliases(caller)
try:
ind = str(aliases.index(alias) + 1)
if ind not in aliases:
aliases.append(ind)
_set_prototype_value(caller, "aliases", aliases)
caller.msg("Added alias '{}'.".format(ind))
except (IndexError, ValueError) as err:
caller.msg("Error: {}".format(err))
return "node_aliases" | [
"def",
"_aliases_select",
"(",
"caller",
",",
"alias",
")",
":",
"aliases",
"=",
"_all_aliases",
"(",
"caller",
")",
"try",
":",
"ind",
"=",
"str",
"(",
"aliases",
".",
"index",
"(",
"alias",
")",
"+",
"1",
")",
"if",
"ind",
"not",
"in",
"aliases",
":",
"aliases",
".",
"append",
"(",
"ind",
")",
"_set_prototype_value",
"(",
"caller",
",",
"\"aliases\"",
",",
"aliases",
")",
"caller",
".",
"msg",
"(",
"\"Added alias '{}'.\"",
".",
"format",
"(",
"ind",
")",
")",
"except",
"(",
"IndexError",
",",
"ValueError",
")",
"as",
"err",
":",
"caller",
".",
"msg",
"(",
"\"Error: {}\"",
".",
"format",
"(",
"err",
")",
")",
"return",
"\"node_aliases\""
] | [
962,
0
] | [
974,
25
] | python | en | ['en', 'en', 'en'] | True |
_aliases_actions | (caller, raw_inp, **kwargs) | Parse actions for aliases listing | Parse actions for aliases listing | def _aliases_actions(caller, raw_inp, **kwargs):
"""Parse actions for aliases listing"""
choices = kwargs.get("available_choices", [])
alias, action = _default_parse(
raw_inp, choices, ("remove", "r", "delete", "d"))
aliases = _all_aliases(caller)
if alias and action == 'remove':
try:
aliases.remove(alias)
_set_prototype_value(caller, "aliases", aliases)
caller.msg("Removed alias '{}'.".format(alias))
except ValueError:
caller.msg("No matching alias found to remove.")
else:
# if not a valid remove, add as a new alias
alias = raw_inp.lower().strip()
if alias and alias not in aliases:
aliases.append(alias)
_set_prototype_value(caller, "aliases", aliases)
caller.msg("Added alias '{}'.".format(alias))
else:
caller.msg("Alias '{}' was already set.".format(alias))
return "node_aliases" | [
"def",
"_aliases_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"\"available_choices\"",
",",
"[",
"]",
")",
"alias",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"\"remove\"",
",",
"\"r\"",
",",
"\"delete\"",
",",
"\"d\"",
")",
")",
"aliases",
"=",
"_all_aliases",
"(",
"caller",
")",
"if",
"alias",
"and",
"action",
"==",
"'remove'",
":",
"try",
":",
"aliases",
".",
"remove",
"(",
"alias",
")",
"_set_prototype_value",
"(",
"caller",
",",
"\"aliases\"",
",",
"aliases",
")",
"caller",
".",
"msg",
"(",
"\"Removed alias '{}'.\"",
".",
"format",
"(",
"alias",
")",
")",
"except",
"ValueError",
":",
"caller",
".",
"msg",
"(",
"\"No matching alias found to remove.\"",
")",
"else",
":",
"# if not a valid remove, add as a new alias",
"alias",
"=",
"raw_inp",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"alias",
"and",
"alias",
"not",
"in",
"aliases",
":",
"aliases",
".",
"append",
"(",
"alias",
")",
"_set_prototype_value",
"(",
"caller",
",",
"\"aliases\"",
",",
"aliases",
")",
"caller",
".",
"msg",
"(",
"\"Added alias '{}'.\"",
".",
"format",
"(",
"alias",
")",
")",
"else",
":",
"caller",
".",
"msg",
"(",
"\"Alias '{}' was already set.\"",
".",
"format",
"(",
"alias",
")",
")",
"return",
"\"node_aliases\""
] | [
977,
0
] | [
1000,
25
] | python | en | ['en', 'en', 'en'] | True |
_display_attribute | (attr_tuple) | Pretty-print attribute tuple | Pretty-print attribute tuple | def _display_attribute(attr_tuple):
"""Pretty-print attribute tuple"""
attrkey, value, category, locks = attr_tuple
value = protlib.protfunc_parser(value)
typ = type(value)
out = ("{attrkey} |c=|n {value} |W({typ}{category}{locks})|n".format(
attrkey=attrkey,
value=value,
typ=typ,
category=", category={}".format(category) if category else '',
locks=", locks={}".format(";".join(locks)) if any(locks) else ''))
return out | [
"def",
"_display_attribute",
"(",
"attr_tuple",
")",
":",
"attrkey",
",",
"value",
",",
"category",
",",
"locks",
"=",
"attr_tuple",
"value",
"=",
"protlib",
".",
"protfunc_parser",
"(",
"value",
")",
"typ",
"=",
"type",
"(",
"value",
")",
"out",
"=",
"(",
"\"{attrkey} |c=|n {value} |W({typ}{category}{locks})|n\"",
".",
"format",
"(",
"attrkey",
"=",
"attrkey",
",",
"value",
"=",
"value",
",",
"typ",
"=",
"typ",
",",
"category",
"=",
"\", category={}\"",
".",
"format",
"(",
"category",
")",
"if",
"category",
"else",
"''",
",",
"locks",
"=",
"\", locks={}\"",
".",
"format",
"(",
"\";\"",
".",
"join",
"(",
"locks",
")",
")",
"if",
"any",
"(",
"locks",
")",
"else",
"''",
")",
")",
"return",
"out"
] | [
1056,
0
] | [
1068,
14
] | python | en | ['en', 'it', 'en'] | True |
_add_attr | (caller, attr_string, **kwargs) |
Add new attribute, parsing input.
Args:
caller (Object): Caller of menu.
attr_string (str): Input from user
attr is entered on these forms
attr = value
attr;category = value
attr;category;lockstring = value
Kwargs:
delete (str): If this is set, attr_string is
considered the name of the attribute to delete and
no further parsing happens.
Returns:
result (str): Result string of action.
|
Add new attribute, parsing input. | def _add_attr(caller, attr_string, **kwargs):
"""
Add new attribute, parsing input.
Args:
caller (Object): Caller of menu.
attr_string (str): Input from user
attr is entered on these forms
attr = value
attr;category = value
attr;category;lockstring = value
Kwargs:
delete (str): If this is set, attr_string is
considered the name of the attribute to delete and
no further parsing happens.
Returns:
result (str): Result string of action.
"""
attrname = ''
value = ''
category = None
locks = ''
if 'delete' in kwargs:
attrname = attr_string.lower().strip()
elif '=' in attr_string:
attrname, value = (part.strip() for part in attr_string.split('=', 1))
attrname = attrname.lower()
nameparts = attrname.split(";", 2)
nparts = len(nameparts)
if nparts == 2:
attrname, category = nameparts
elif nparts > 2:
attrname, category, locks = nameparts
attr_tuple = (attrname, value, category, str(locks))
if attrname:
prot = _get_menu_prototype(caller)
attrs = prot.get('attrs', [])
if 'delete' in kwargs:
try:
ind = [tup[0] for tup in attrs].index(attrname)
del attrs[ind]
_set_prototype_value(caller, "attrs", attrs)
return "Removed Attribute '{}'".format(attrname)
except IndexError:
return "Attribute to delete not found."
try:
# replace existing attribute with the same name in the prototype
ind = [tup[0] for tup in attrs].index(attrname)
attrs[ind] = attr_tuple
text = "Edited Attribute '{}'.".format(attrname)
except ValueError:
attrs.append(attr_tuple)
text = "Added Attribute " + _display_attribute(attr_tuple)
_set_prototype_value(caller, "attrs", attrs)
else:
text = "Attribute must be given as 'attrname[;category;locks] = <value>'."
return text | [
"def",
"_add_attr",
"(",
"caller",
",",
"attr_string",
",",
"*",
"*",
"kwargs",
")",
":",
"attrname",
"=",
"''",
"value",
"=",
"''",
"category",
"=",
"None",
"locks",
"=",
"''",
"if",
"'delete'",
"in",
"kwargs",
":",
"attrname",
"=",
"attr_string",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"elif",
"'='",
"in",
"attr_string",
":",
"attrname",
",",
"value",
"=",
"(",
"part",
".",
"strip",
"(",
")",
"for",
"part",
"in",
"attr_string",
".",
"split",
"(",
"'='",
",",
"1",
")",
")",
"attrname",
"=",
"attrname",
".",
"lower",
"(",
")",
"nameparts",
"=",
"attrname",
".",
"split",
"(",
"\";\"",
",",
"2",
")",
"nparts",
"=",
"len",
"(",
"nameparts",
")",
"if",
"nparts",
"==",
"2",
":",
"attrname",
",",
"category",
"=",
"nameparts",
"elif",
"nparts",
">",
"2",
":",
"attrname",
",",
"category",
",",
"locks",
"=",
"nameparts",
"attr_tuple",
"=",
"(",
"attrname",
",",
"value",
",",
"category",
",",
"str",
"(",
"locks",
")",
")",
"if",
"attrname",
":",
"prot",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"attrs",
"=",
"prot",
".",
"get",
"(",
"'attrs'",
",",
"[",
"]",
")",
"if",
"'delete'",
"in",
"kwargs",
":",
"try",
":",
"ind",
"=",
"[",
"tup",
"[",
"0",
"]",
"for",
"tup",
"in",
"attrs",
"]",
".",
"index",
"(",
"attrname",
")",
"del",
"attrs",
"[",
"ind",
"]",
"_set_prototype_value",
"(",
"caller",
",",
"\"attrs\"",
",",
"attrs",
")",
"return",
"\"Removed Attribute '{}'\"",
".",
"format",
"(",
"attrname",
")",
"except",
"IndexError",
":",
"return",
"\"Attribute to delete not found.\"",
"try",
":",
"# replace existing attribute with the same name in the prototype",
"ind",
"=",
"[",
"tup",
"[",
"0",
"]",
"for",
"tup",
"in",
"attrs",
"]",
".",
"index",
"(",
"attrname",
")",
"attrs",
"[",
"ind",
"]",
"=",
"attr_tuple",
"text",
"=",
"\"Edited Attribute '{}'.\"",
".",
"format",
"(",
"attrname",
")",
"except",
"ValueError",
":",
"attrs",
".",
"append",
"(",
"attr_tuple",
")",
"text",
"=",
"\"Added Attribute \"",
"+",
"_display_attribute",
"(",
"attr_tuple",
")",
"_set_prototype_value",
"(",
"caller",
",",
"\"attrs\"",
",",
"attrs",
")",
"else",
":",
"text",
"=",
"\"Attribute must be given as 'attrname[;category;locks] = <value>'.\"",
"return",
"text"
] | [
1071,
0
] | [
1133,
15
] | python | en | ['en', 'error', 'th'] | False |
_attrs_actions | (caller, raw_inp, **kwargs) | Parse actions for attribute listing | Parse actions for attribute listing | def _attrs_actions(caller, raw_inp, **kwargs):
"""Parse actions for attribute listing"""
choices = kwargs.get("available_choices", [])
attrstr, action = _default_parse(
raw_inp, choices, ('examine', 'e'), ('remove', 'r', 'delete', 'd'))
if attrstr is None:
attrstr = raw_inp
try:
attrname, _ = attrstr.split("=", 1)
except ValueError:
caller.msg("|rNeed to enter the attribute on the form attrname=value.|n")
return "node_attrs"
attrname = attrname.strip()
attr_tup = _get_tup_by_attrname(caller, attrname)
if action and attr_tup:
if action == 'examine':
return "node_examine_entity", \
{"text": _display_attribute(attr_tup), "back": "attrs"}
elif action == 'remove':
res = _add_attr(caller, attrname, delete=True)
caller.msg(res)
else:
res = _add_attr(caller, raw_inp)
caller.msg(res)
return "node_attrs" | [
"def",
"_attrs_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"\"available_choices\"",
",",
"[",
"]",
")",
"attrstr",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"'examine'",
",",
"'e'",
")",
",",
"(",
"'remove'",
",",
"'r'",
",",
"'delete'",
",",
"'d'",
")",
")",
"if",
"attrstr",
"is",
"None",
":",
"attrstr",
"=",
"raw_inp",
"try",
":",
"attrname",
",",
"_",
"=",
"attrstr",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"except",
"ValueError",
":",
"caller",
".",
"msg",
"(",
"\"|rNeed to enter the attribute on the form attrname=value.|n\"",
")",
"return",
"\"node_attrs\"",
"attrname",
"=",
"attrname",
".",
"strip",
"(",
")",
"attr_tup",
"=",
"_get_tup_by_attrname",
"(",
"caller",
",",
"attrname",
")",
"if",
"action",
"and",
"attr_tup",
":",
"if",
"action",
"==",
"'examine'",
":",
"return",
"\"node_examine_entity\"",
",",
"{",
"\"text\"",
":",
"_display_attribute",
"(",
"attr_tup",
")",
",",
"\"back\"",
":",
"\"attrs\"",
"}",
"elif",
"action",
"==",
"'remove'",
":",
"res",
"=",
"_add_attr",
"(",
"caller",
",",
"attrname",
",",
"delete",
"=",
"True",
")",
"caller",
".",
"msg",
"(",
"res",
")",
"else",
":",
"res",
"=",
"_add_attr",
"(",
"caller",
",",
"raw_inp",
")",
"caller",
".",
"msg",
"(",
"res",
")",
"return",
"\"node_attrs\""
] | [
1149,
0
] | [
1175,
23
] | python | en | ['en', 'en', 'en'] | True |
_display_tag | (tag_tuple) | Pretty-print tag tuple | Pretty-print tag tuple | def _display_tag(tag_tuple):
"""Pretty-print tag tuple"""
tagkey, category, data = tag_tuple
out = ("Tag: '{tagkey}' (category: {category}{dat})".format(
tagkey=tagkey, category=category, dat=", data: {}".format(data) if data else ""))
return out | [
"def",
"_display_tag",
"(",
"tag_tuple",
")",
":",
"tagkey",
",",
"category",
",",
"data",
"=",
"tag_tuple",
"out",
"=",
"(",
"\"Tag: '{tagkey}' (category: {category}{dat})\"",
".",
"format",
"(",
"tagkey",
"=",
"tagkey",
",",
"category",
"=",
"category",
",",
"dat",
"=",
"\", data: {}\"",
".",
"format",
"(",
"data",
")",
"if",
"data",
"else",
"\"\"",
")",
")",
"return",
"out"
] | [
1244,
0
] | [
1249,
14
] | python | en | ['en', 'hmn', 'en'] | True |
_add_tag | (caller, tag_string, **kwargs) |
Add tags to the system, parsing input
Args:
caller (Object): Caller of menu.
tag_string (str): Input from user on one of these forms
tagname
tagname;category
tagname;category;data
Kwargs:
delete (str): If this is set, tag_string is considered
the name of the tag to delete.
Returns:
result (str): Result string of action.
|
Add tags to the system, parsing input | def _add_tag(caller, tag_string, **kwargs):
"""
Add tags to the system, parsing input
Args:
caller (Object): Caller of menu.
tag_string (str): Input from user on one of these forms
tagname
tagname;category
tagname;category;data
Kwargs:
delete (str): If this is set, tag_string is considered
the name of the tag to delete.
Returns:
result (str): Result string of action.
"""
tag = tag_string.strip().lower()
category = None
data = ""
if 'delete' in kwargs:
tag = tag_string.lower().strip()
else:
nameparts = tag.split(";", 2)
ntuple = len(nameparts)
if ntuple == 2:
tag, category = nameparts
elif ntuple > 2:
tag, category, data = nameparts[:3]
tag_tuple = (tag.lower(), category.lower() if category else None, data)
if tag:
prot = _get_menu_prototype(caller)
tags = prot.get('tags', [])
old_tag = _get_tup_by_tagname(caller, tag)
if 'delete' in kwargs:
if old_tag:
tags.pop(tags.index(old_tag))
text = "Removed Tag '{}'.".format(tag)
else:
text = "Found no Tag to remove."
elif not old_tag:
# a fresh, new tag
tags.append(tag_tuple)
text = "Added Tag '{}'".format(tag)
else:
# old tag exists; editing a tag means replacing old with new
ind = tags.index(old_tag)
tags[ind] = tag_tuple
text = "Edited Tag '{}'".format(tag)
_set_prototype_value(caller, "tags", tags)
else:
text = "Tag must be given as 'tag[;category;data]'."
return text | [
"def",
"_add_tag",
"(",
"caller",
",",
"tag_string",
",",
"*",
"*",
"kwargs",
")",
":",
"tag",
"=",
"tag_string",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"category",
"=",
"None",
"data",
"=",
"\"\"",
"if",
"'delete'",
"in",
"kwargs",
":",
"tag",
"=",
"tag_string",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"else",
":",
"nameparts",
"=",
"tag",
".",
"split",
"(",
"\";\"",
",",
"2",
")",
"ntuple",
"=",
"len",
"(",
"nameparts",
")",
"if",
"ntuple",
"==",
"2",
":",
"tag",
",",
"category",
"=",
"nameparts",
"elif",
"ntuple",
">",
"2",
":",
"tag",
",",
"category",
",",
"data",
"=",
"nameparts",
"[",
":",
"3",
"]",
"tag_tuple",
"=",
"(",
"tag",
".",
"lower",
"(",
")",
",",
"category",
".",
"lower",
"(",
")",
"if",
"category",
"else",
"None",
",",
"data",
")",
"if",
"tag",
":",
"prot",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"tags",
"=",
"prot",
".",
"get",
"(",
"'tags'",
",",
"[",
"]",
")",
"old_tag",
"=",
"_get_tup_by_tagname",
"(",
"caller",
",",
"tag",
")",
"if",
"'delete'",
"in",
"kwargs",
":",
"if",
"old_tag",
":",
"tags",
".",
"pop",
"(",
"tags",
".",
"index",
"(",
"old_tag",
")",
")",
"text",
"=",
"\"Removed Tag '{}'.\"",
".",
"format",
"(",
"tag",
")",
"else",
":",
"text",
"=",
"\"Found no Tag to remove.\"",
"elif",
"not",
"old_tag",
":",
"# a fresh, new tag",
"tags",
".",
"append",
"(",
"tag_tuple",
")",
"text",
"=",
"\"Added Tag '{}'\"",
".",
"format",
"(",
"tag",
")",
"else",
":",
"# old tag exists; editing a tag means replacing old with new",
"ind",
"=",
"tags",
".",
"index",
"(",
"old_tag",
")",
"tags",
"[",
"ind",
"]",
"=",
"tag_tuple",
"text",
"=",
"\"Edited Tag '{}'\"",
".",
"format",
"(",
"tag",
")",
"_set_prototype_value",
"(",
"caller",
",",
"\"tags\"",
",",
"tags",
")",
"else",
":",
"text",
"=",
"\"Tag must be given as 'tag[;category;data]'.\"",
"return",
"text"
] | [
1252,
0
] | [
1314,
15
] | python | en | ['en', 'error', 'th'] | False |
_tags_actions | (caller, raw_inp, **kwargs) | Parse actions for tags listing | Parse actions for tags listing | def _tags_actions(caller, raw_inp, **kwargs):
"""Parse actions for tags listing"""
choices = kwargs.get("available_choices", [])
tagname, action = _default_parse(
raw_inp, choices, ('examine', 'e'), ('remove', 'r', 'delete', 'd'))
if tagname is None:
tagname = raw_inp.lower().strip()
tag_tup = _get_tup_by_tagname(caller, tagname)
if tag_tup:
if action == 'examine':
return "node_examine_entity", \
{"text": _display_tag(tag_tup), 'back': 'tags'}
elif action == 'remove':
res = _add_tag(caller, tagname, delete=True)
caller.msg(res)
else:
res = _add_tag(caller, raw_inp)
caller.msg(res)
return "node_tags" | [
"def",
"_tags_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"\"available_choices\"",
",",
"[",
"]",
")",
"tagname",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"'examine'",
",",
"'e'",
")",
",",
"(",
"'remove'",
",",
"'r'",
",",
"'delete'",
",",
"'d'",
")",
")",
"if",
"tagname",
"is",
"None",
":",
"tagname",
"=",
"raw_inp",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"tag_tup",
"=",
"_get_tup_by_tagname",
"(",
"caller",
",",
"tagname",
")",
"if",
"tag_tup",
":",
"if",
"action",
"==",
"'examine'",
":",
"return",
"\"node_examine_entity\"",
",",
"{",
"\"text\"",
":",
"_display_tag",
"(",
"tag_tup",
")",
",",
"'back'",
":",
"'tags'",
"}",
"elif",
"action",
"==",
"'remove'",
":",
"res",
"=",
"_add_tag",
"(",
"caller",
",",
"tagname",
",",
"delete",
"=",
"True",
")",
"caller",
".",
"msg",
"(",
"res",
")",
"else",
":",
"res",
"=",
"_add_tag",
"(",
"caller",
",",
"raw_inp",
")",
"caller",
".",
"msg",
"(",
"res",
")",
"return",
"\"node_tags\""
] | [
1327,
0
] | [
1348,
22
] | python | en | ['en', 'en', 'en'] | True |
_permissions_actions | (caller, raw_inp, **kwargs) | Parse actions for permission listing | Parse actions for permission listing | def _permissions_actions(caller, raw_inp, **kwargs):
"""Parse actions for permission listing"""
choices = kwargs.get("available_choices", [])
perm, action = _default_parse(
raw_inp, choices, ('examine', 'e'), ('remove', 'r', 'delete', 'd'))
if perm:
if action == 'examine':
return "node_examine_entity", \
{"text": _display_perm(caller, perm), "back": "permissions"}
elif action == 'remove':
res = _add_perm(caller, perm, delete=True)
caller.msg(res)
else:
res = _add_perm(caller, raw_inp.strip())
caller.msg(res)
return "node_permissions" | [
"def",
"_permissions_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"\"available_choices\"",
",",
"[",
"]",
")",
"perm",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"'examine'",
",",
"'e'",
")",
",",
"(",
"'remove'",
",",
"'r'",
",",
"'delete'",
",",
"'d'",
")",
")",
"if",
"perm",
":",
"if",
"action",
"==",
"'examine'",
":",
"return",
"\"node_examine_entity\"",
",",
"{",
"\"text\"",
":",
"_display_perm",
"(",
"caller",
",",
"perm",
")",
",",
"\"back\"",
":",
"\"permissions\"",
"}",
"elif",
"action",
"==",
"'remove'",
":",
"res",
"=",
"_add_perm",
"(",
"caller",
",",
"perm",
",",
"delete",
"=",
"True",
")",
"caller",
".",
"msg",
"(",
"res",
")",
"else",
":",
"res",
"=",
"_add_perm",
"(",
"caller",
",",
"raw_inp",
".",
"strip",
"(",
")",
")",
"caller",
".",
"msg",
"(",
"res",
")",
"return",
"\"node_permissions\""
] | [
1556,
0
] | [
1572,
29
] | python | en | ['en', 'en', 'en'] | True |
_add_prototype_tag | (caller, tag_string, **kwargs) |
Add prototype_tags to the system. We only support straight tags, no
categories (category is assigned automatically).
Args:
caller (Object): Caller of menu.
tag_string (str): Input from user - only tagname
Kwargs:
delete (str): If this is set, tag_string is considered
the name of the tag to delete.
Returns:
result (str): Result string of action.
|
Add prototype_tags to the system. We only support straight tags, no
categories (category is assigned automatically). | def _add_prototype_tag(caller, tag_string, **kwargs):
"""
Add prototype_tags to the system. We only support straight tags, no
categories (category is assigned automatically).
Args:
caller (Object): Caller of menu.
tag_string (str): Input from user - only tagname
Kwargs:
delete (str): If this is set, tag_string is considered
the name of the tag to delete.
Returns:
result (str): Result string of action.
"""
tag = tag_string.strip().lower()
if tag:
prot = _get_menu_prototype(caller)
tags = prot.get('prototype_tags', [])
exists = tag in tags
if 'delete' in kwargs:
if exists:
tags.pop(tags.index(tag))
text = "Removed Prototype-Tag '{}'.".format(tag)
else:
text = "Found no Prototype-Tag to remove."
elif not exists:
# a fresh, new tag
tags.append(tag)
text = "Added Prototype-Tag '{}'.".format(tag)
else:
text = "Prototype-Tag already added."
_set_prototype_value(caller, "prototype_tags", tags)
else:
text = "No Prototype-Tag specified."
return text | [
"def",
"_add_prototype_tag",
"(",
"caller",
",",
"tag_string",
",",
"*",
"*",
"kwargs",
")",
":",
"tag",
"=",
"tag_string",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"tag",
":",
"prot",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"tags",
"=",
"prot",
".",
"get",
"(",
"'prototype_tags'",
",",
"[",
"]",
")",
"exists",
"=",
"tag",
"in",
"tags",
"if",
"'delete'",
"in",
"kwargs",
":",
"if",
"exists",
":",
"tags",
".",
"pop",
"(",
"tags",
".",
"index",
"(",
"tag",
")",
")",
"text",
"=",
"\"Removed Prototype-Tag '{}'.\"",
".",
"format",
"(",
"tag",
")",
"else",
":",
"text",
"=",
"\"Found no Prototype-Tag to remove.\"",
"elif",
"not",
"exists",
":",
"# a fresh, new tag",
"tags",
".",
"append",
"(",
"tag",
")",
"text",
"=",
"\"Added Prototype-Tag '{}'.\"",
".",
"format",
"(",
"tag",
")",
"else",
":",
"text",
"=",
"\"Prototype-Tag already added.\"",
"_set_prototype_value",
"(",
"caller",
",",
"\"prototype_tags\"",
",",
"tags",
")",
"else",
":",
"text",
"=",
"\"No Prototype-Tag specified.\"",
"return",
"text"
] | [
1750,
0
] | [
1791,
15
] | python | en | ['en', 'error', 'th'] | False |
_prototype_tags_actions | (caller, raw_inp, **kwargs) | Parse actions for tags listing | Parse actions for tags listing | def _prototype_tags_actions(caller, raw_inp, **kwargs):
"""Parse actions for tags listing"""
choices = kwargs.get("available_choices", [])
tagname, action = _default_parse(
raw_inp, choices, ('remove', 'r', 'delete', 'd'))
if tagname:
if action == 'remove':
res = _add_prototype_tag(caller, tagname, delete=True)
caller.msg(res)
else:
res = _add_prototype_tag(caller, raw_inp.lower().strip())
caller.msg(res)
return "node_prototype_tags" | [
"def",
"_prototype_tags_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"\"available_choices\"",
",",
"[",
"]",
")",
"tagname",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"'remove'",
",",
"'r'",
",",
"'delete'",
",",
"'d'",
")",
")",
"if",
"tagname",
":",
"if",
"action",
"==",
"'remove'",
":",
"res",
"=",
"_add_prototype_tag",
"(",
"caller",
",",
"tagname",
",",
"delete",
"=",
"True",
")",
"caller",
".",
"msg",
"(",
"res",
")",
"else",
":",
"res",
"=",
"_add_prototype_tag",
"(",
"caller",
",",
"raw_inp",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
")",
"caller",
".",
"msg",
"(",
"res",
")",
"return",
"\"node_prototype_tags\""
] | [
1799,
0
] | [
1812,
32
] | python | en | ['en', 'en', 'en'] | True |
_apply_diff | (caller, **kwargs) | update existing objects | update existing objects | def _apply_diff(caller, **kwargs):
"""update existing objects"""
prototype = kwargs['prototype']
objects = kwargs['objects']
back_node = kwargs['back_node']
diff = kwargs.get('diff', None)
num_changed = spawner.batch_update_objects_with_prototype(prototype, diff=diff, objects=objects)
caller.msg("|g{num} objects were updated successfully.|n".format(num=num_changed))
return back_node | [
"def",
"_apply_diff",
"(",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"prototype",
"=",
"kwargs",
"[",
"'prototype'",
"]",
"objects",
"=",
"kwargs",
"[",
"'objects'",
"]",
"back_node",
"=",
"kwargs",
"[",
"'back_node'",
"]",
"diff",
"=",
"kwargs",
".",
"get",
"(",
"'diff'",
",",
"None",
")",
"num_changed",
"=",
"spawner",
".",
"batch_update_objects_with_prototype",
"(",
"prototype",
",",
"diff",
"=",
"diff",
",",
"objects",
"=",
"objects",
")",
"caller",
".",
"msg",
"(",
"\"|g{num} objects were updated successfully.|n\"",
".",
"format",
"(",
"num",
"=",
"num_changed",
")",
")",
"return",
"back_node"
] | [
1946,
0
] | [
1954,
20
] | python | en | ['es', 'en', 'en'] | True |
_keep_diff | (caller, **kwargs) | Change to KEEP setting for a given section of a diff | Change to KEEP setting for a given section of a diff | def _keep_diff(caller, **kwargs):
"""Change to KEEP setting for a given section of a diff"""
# from evennia import set_trace;set_trace(term_size=(182, 50))
path = kwargs['path']
diff = kwargs['diff']
tmp = diff
for key in path[:-1]:
tmp = tmp[key]
tmp[path[-1]] = tuple(list(tmp[path[-1]][:-1]) + ["KEEP"]) | [
"def",
"_keep_diff",
"(",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"# from evennia import set_trace;set_trace(term_size=(182, 50))",
"path",
"=",
"kwargs",
"[",
"'path'",
"]",
"diff",
"=",
"kwargs",
"[",
"'diff'",
"]",
"tmp",
"=",
"diff",
"for",
"key",
"in",
"path",
"[",
":",
"-",
"1",
"]",
":",
"tmp",
"=",
"tmp",
"[",
"key",
"]",
"tmp",
"[",
"path",
"[",
"-",
"1",
"]",
"]",
"=",
"tuple",
"(",
"list",
"(",
"tmp",
"[",
"path",
"[",
"-",
"1",
"]",
"]",
"[",
":",
"-",
"1",
"]",
")",
"+",
"[",
"\"KEEP\"",
"]",
")"
] | [
1957,
0
] | [
1965,
62
] | python | en | ['en', 'en', 'en'] | True |
_format_diff_text_and_options | (diff, **kwargs) |
Reformat the diff in a way suitable for the olc menu.
Args:
diff (dict): A diff as produced by `prototype_diff`.
Kwargs:
any (any): Forwarded into the generated options as arguments to the callable.
Returns:
texts (list): List of texts.
options (list): List of options dict.
|
Reformat the diff in a way suitable for the olc menu. | def _format_diff_text_and_options(diff, **kwargs):
"""
Reformat the diff in a way suitable for the olc menu.
Args:
diff (dict): A diff as produced by `prototype_diff`.
Kwargs:
any (any): Forwarded into the generated options as arguments to the callable.
Returns:
texts (list): List of texts.
options (list): List of options dict.
"""
valid_instructions = ('KEEP', 'REMOVE', 'ADD', 'UPDATE')
def _visualize(obj, rootname, get_name=False):
if utils.is_iter(obj):
if get_name:
return obj[0] if obj[0] else "<unset>"
if rootname == "attrs":
return "{} |W=|n {} |W(category:|n {}|W, locks:|n {}|W)|n".format(*obj)
elif rootname == "tags":
return "{} |W(category:|n {}|W)|n".format(obj[0], obj[1])
return "{}".format(obj)
def _parse_diffpart(diffpart, optnum, *args):
typ = type(diffpart)
texts = []
options = []
if typ == tuple and len(diffpart) == 3 and diffpart[2] in valid_instructions:
rootname = args[0]
old, new, instruction = diffpart
if instruction == 'KEEP':
texts.append(" |gKEEP|W:|n {old}".format(old=_visualize(old, rootname)))
else:
vold = _visualize(old, rootname)
vnew = _visualize(new, rootname)
vsep = "" if len(vold) < 78 else "\n"
vinst = "|rREMOVE|n" if instruction == 'REMOVE' else "|y{}|n".format(instruction)
texts.append(" |c[{num}] {inst}|W:|n {old} |W->|n{sep} {new}".format(
inst=vinst, num=optnum, old=vold, sep=vsep, new=vnew))
options.append({"key": str(optnum),
"desc": "|gKEEP|n ({}) {}".format(
rootname, _visualize(old, args[-1], get_name=True)),
"goto": (_keep_diff, dict((("path", args),
("diff", diff)), **kwargs))})
optnum += 1
else:
for key, subdiffpart in diffpart.items():
text, option, optnum = _parse_diffpart(
subdiffpart, optnum, *(args + (key, )))
texts.extend(text)
options.extend(option)
return texts, options, optnum
texts = []
options = []
# we use this to allow for skipping full KEEP instructions
optnum = 1
for root_key in sorted(diff):
diffpart = diff[root_key]
text, option, optnum = _parse_diffpart(diffpart, optnum, root_key)
heading = "- |w{}:|n ".format(root_key)
if root_key in ("attrs", "tags", "permissions"):
texts.append(heading)
elif text:
text = [heading + text[0]] + text[1:]
else:
text = [heading]
texts.extend(text)
options.extend(option)
return texts, options | [
"def",
"_format_diff_text_and_options",
"(",
"diff",
",",
"*",
"*",
"kwargs",
")",
":",
"valid_instructions",
"=",
"(",
"'KEEP'",
",",
"'REMOVE'",
",",
"'ADD'",
",",
"'UPDATE'",
")",
"def",
"_visualize",
"(",
"obj",
",",
"rootname",
",",
"get_name",
"=",
"False",
")",
":",
"if",
"utils",
".",
"is_iter",
"(",
"obj",
")",
":",
"if",
"get_name",
":",
"return",
"obj",
"[",
"0",
"]",
"if",
"obj",
"[",
"0",
"]",
"else",
"\"<unset>\"",
"if",
"rootname",
"==",
"\"attrs\"",
":",
"return",
"\"{} |W=|n {} |W(category:|n {}|W, locks:|n {}|W)|n\"",
".",
"format",
"(",
"*",
"obj",
")",
"elif",
"rootname",
"==",
"\"tags\"",
":",
"return",
"\"{} |W(category:|n {}|W)|n\"",
".",
"format",
"(",
"obj",
"[",
"0",
"]",
",",
"obj",
"[",
"1",
"]",
")",
"return",
"\"{}\"",
".",
"format",
"(",
"obj",
")",
"def",
"_parse_diffpart",
"(",
"diffpart",
",",
"optnum",
",",
"*",
"args",
")",
":",
"typ",
"=",
"type",
"(",
"diffpart",
")",
"texts",
"=",
"[",
"]",
"options",
"=",
"[",
"]",
"if",
"typ",
"==",
"tuple",
"and",
"len",
"(",
"diffpart",
")",
"==",
"3",
"and",
"diffpart",
"[",
"2",
"]",
"in",
"valid_instructions",
":",
"rootname",
"=",
"args",
"[",
"0",
"]",
"old",
",",
"new",
",",
"instruction",
"=",
"diffpart",
"if",
"instruction",
"==",
"'KEEP'",
":",
"texts",
".",
"append",
"(",
"\" |gKEEP|W:|n {old}\"",
".",
"format",
"(",
"old",
"=",
"_visualize",
"(",
"old",
",",
"rootname",
")",
")",
")",
"else",
":",
"vold",
"=",
"_visualize",
"(",
"old",
",",
"rootname",
")",
"vnew",
"=",
"_visualize",
"(",
"new",
",",
"rootname",
")",
"vsep",
"=",
"\"\"",
"if",
"len",
"(",
"vold",
")",
"<",
"78",
"else",
"\"\\n\"",
"vinst",
"=",
"\"|rREMOVE|n\"",
"if",
"instruction",
"==",
"'REMOVE'",
"else",
"\"|y{}|n\"",
".",
"format",
"(",
"instruction",
")",
"texts",
".",
"append",
"(",
"\" |c[{num}] {inst}|W:|n {old} |W->|n{sep} {new}\"",
".",
"format",
"(",
"inst",
"=",
"vinst",
",",
"num",
"=",
"optnum",
",",
"old",
"=",
"vold",
",",
"sep",
"=",
"vsep",
",",
"new",
"=",
"vnew",
")",
")",
"options",
".",
"append",
"(",
"{",
"\"key\"",
":",
"str",
"(",
"optnum",
")",
",",
"\"desc\"",
":",
"\"|gKEEP|n ({}) {}\"",
".",
"format",
"(",
"rootname",
",",
"_visualize",
"(",
"old",
",",
"args",
"[",
"-",
"1",
"]",
",",
"get_name",
"=",
"True",
")",
")",
",",
"\"goto\"",
":",
"(",
"_keep_diff",
",",
"dict",
"(",
"(",
"(",
"\"path\"",
",",
"args",
")",
",",
"(",
"\"diff\"",
",",
"diff",
")",
")",
",",
"*",
"*",
"kwargs",
")",
")",
"}",
")",
"optnum",
"+=",
"1",
"else",
":",
"for",
"key",
",",
"subdiffpart",
"in",
"diffpart",
".",
"items",
"(",
")",
":",
"text",
",",
"option",
",",
"optnum",
"=",
"_parse_diffpart",
"(",
"subdiffpart",
",",
"optnum",
",",
"*",
"(",
"args",
"+",
"(",
"key",
",",
")",
")",
")",
"texts",
".",
"extend",
"(",
"text",
")",
"options",
".",
"extend",
"(",
"option",
")",
"return",
"texts",
",",
"options",
",",
"optnum",
"texts",
"=",
"[",
"]",
"options",
"=",
"[",
"]",
"# we use this to allow for skipping full KEEP instructions",
"optnum",
"=",
"1",
"for",
"root_key",
"in",
"sorted",
"(",
"diff",
")",
":",
"diffpart",
"=",
"diff",
"[",
"root_key",
"]",
"text",
",",
"option",
",",
"optnum",
"=",
"_parse_diffpart",
"(",
"diffpart",
",",
"optnum",
",",
"root_key",
")",
"heading",
"=",
"\"- |w{}:|n \"",
".",
"format",
"(",
"root_key",
")",
"if",
"root_key",
"in",
"(",
"\"attrs\"",
",",
"\"tags\"",
",",
"\"permissions\"",
")",
":",
"texts",
".",
"append",
"(",
"heading",
")",
"elif",
"text",
":",
"text",
"=",
"[",
"heading",
"+",
"text",
"[",
"0",
"]",
"]",
"+",
"text",
"[",
"1",
":",
"]",
"else",
":",
"text",
"=",
"[",
"heading",
"]",
"texts",
".",
"extend",
"(",
"text",
")",
"options",
".",
"extend",
"(",
"option",
")",
"return",
"texts",
",",
"options"
] | [
1968,
0
] | [
2045,
25
] | python | en | ['en', 'error', 'th'] | False |
node_apply_diff | (caller, **kwargs) | Offer options for updating objects | Offer options for updating objects | def node_apply_diff(caller, **kwargs):
"""Offer options for updating objects"""
def _keep_option(keyname, prototype, base_obj, obj_prototype, diff, objects, back_node):
"""helper returning an option dict"""
options = {"desc": "Keep {} as-is".format(keyname),
"goto": (_keep_diff,
{"key": keyname, "prototype": prototype,
"base_obj": base_obj, "obj_prototype": obj_prototype,
"diff": diff, "objects": objects, "back_node": back_node})}
return options
prototype = kwargs.get("prototype", None)
update_objects = kwargs.get("objects", None)
back_node = kwargs.get("back_node", "node_index")
obj_prototype = kwargs.get("obj_prototype", None)
base_obj = kwargs.get("base_obj", None)
diff = kwargs.get("diff", None)
custom_location = kwargs.get("custom_location", None)
if not update_objects:
text = "There are no existing objects to update."
options = {"key": "_default",
"goto": back_node}
return text, options
if not diff:
# use one random object as a reference to calculate a diff
base_obj = choice(update_objects)
diff, obj_prototype = spawner.prototype_diff_from_object(prototype, base_obj)
helptext = """
This will go through all existing objects and apply the changes you accept.
Be careful with this operation! The upgrade mechanism will try to automatically estimate
what changes need to be applied. But the estimate is |wonly based on the analysis of one
randomly selected object|n among all objects spawned by this prototype. If that object
happens to be unusual in some way the estimate will be off and may lead to unexpected
results for other objects. Always test your objects carefully after an upgrade and consider
being conservative (switch to KEEP) for things you are unsure of. For complex upgrades it
may be better to get help from an administrator with access to the `@py` command for doing
this manually.
Note that the `location` will never be auto-adjusted because it's so rare to want to
homogenize the location of all object instances."""
if not custom_location:
diff.pop("location", None)
txt, options = _format_diff_text_and_options(diff, objects=update_objects, base_obj=base_obj)
if options:
text = ["Suggested changes to {} objects. ".format(len(update_objects)),
"Showing random example obj to change: {name} ({dbref}))\n".format(
name=base_obj.key, dbref=base_obj.dbref)] + txt
options.extend(
[{"key": ("|wu|Wpdate {} objects".format(len(update_objects)), "update", "u"),
"desc": "Update {} objects".format(len(update_objects)),
"goto": (_apply_diff, {"prototype": prototype, "objects": update_objects,
"back_node": back_node, "diff": diff, "base_obj": base_obj})},
{"key": ("|wr|Weset changes", "reset", "r"),
"goto": ("node_apply_diff", {"prototype": prototype, "back_node": back_node,
"objects": update_objects})}])
else:
text = ["Analyzed a random sample object (out of {}) - "
"found no changes to apply.".format(len(update_objects))]
options.extend(_wizard_options("update_objects", back_node[5:], None))
options.append({"key": "_default",
"goto": back_node})
text = "\n".join(text)
text = (text, helptext)
return text, options | [
"def",
"node_apply_diff",
"(",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_keep_option",
"(",
"keyname",
",",
"prototype",
",",
"base_obj",
",",
"obj_prototype",
",",
"diff",
",",
"objects",
",",
"back_node",
")",
":",
"\"\"\"helper returning an option dict\"\"\"",
"options",
"=",
"{",
"\"desc\"",
":",
"\"Keep {} as-is\"",
".",
"format",
"(",
"keyname",
")",
",",
"\"goto\"",
":",
"(",
"_keep_diff",
",",
"{",
"\"key\"",
":",
"keyname",
",",
"\"prototype\"",
":",
"prototype",
",",
"\"base_obj\"",
":",
"base_obj",
",",
"\"obj_prototype\"",
":",
"obj_prototype",
",",
"\"diff\"",
":",
"diff",
",",
"\"objects\"",
":",
"objects",
",",
"\"back_node\"",
":",
"back_node",
"}",
")",
"}",
"return",
"options",
"prototype",
"=",
"kwargs",
".",
"get",
"(",
"\"prototype\"",
",",
"None",
")",
"update_objects",
"=",
"kwargs",
".",
"get",
"(",
"\"objects\"",
",",
"None",
")",
"back_node",
"=",
"kwargs",
".",
"get",
"(",
"\"back_node\"",
",",
"\"node_index\"",
")",
"obj_prototype",
"=",
"kwargs",
".",
"get",
"(",
"\"obj_prototype\"",
",",
"None",
")",
"base_obj",
"=",
"kwargs",
".",
"get",
"(",
"\"base_obj\"",
",",
"None",
")",
"diff",
"=",
"kwargs",
".",
"get",
"(",
"\"diff\"",
",",
"None",
")",
"custom_location",
"=",
"kwargs",
".",
"get",
"(",
"\"custom_location\"",
",",
"None",
")",
"if",
"not",
"update_objects",
":",
"text",
"=",
"\"There are no existing objects to update.\"",
"options",
"=",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"back_node",
"}",
"return",
"text",
",",
"options",
"if",
"not",
"diff",
":",
"# use one random object as a reference to calculate a diff",
"base_obj",
"=",
"choice",
"(",
"update_objects",
")",
"diff",
",",
"obj_prototype",
"=",
"spawner",
".",
"prototype_diff_from_object",
"(",
"prototype",
",",
"base_obj",
")",
"helptext",
"=",
"\"\"\"\n This will go through all existing objects and apply the changes you accept.\n\n Be careful with this operation! The upgrade mechanism will try to automatically estimate\n what changes need to be applied. But the estimate is |wonly based on the analysis of one\n randomly selected object|n among all objects spawned by this prototype. If that object\n happens to be unusual in some way the estimate will be off and may lead to unexpected\n results for other objects. Always test your objects carefully after an upgrade and consider\n being conservative (switch to KEEP) for things you are unsure of. For complex upgrades it\n may be better to get help from an administrator with access to the `@py` command for doing\n this manually.\n\n Note that the `location` will never be auto-adjusted because it's so rare to want to\n homogenize the location of all object instances.\"\"\"",
"if",
"not",
"custom_location",
":",
"diff",
".",
"pop",
"(",
"\"location\"",
",",
"None",
")",
"txt",
",",
"options",
"=",
"_format_diff_text_and_options",
"(",
"diff",
",",
"objects",
"=",
"update_objects",
",",
"base_obj",
"=",
"base_obj",
")",
"if",
"options",
":",
"text",
"=",
"[",
"\"Suggested changes to {} objects. \"",
".",
"format",
"(",
"len",
"(",
"update_objects",
")",
")",
",",
"\"Showing random example obj to change: {name} ({dbref}))\\n\"",
".",
"format",
"(",
"name",
"=",
"base_obj",
".",
"key",
",",
"dbref",
"=",
"base_obj",
".",
"dbref",
")",
"]",
"+",
"txt",
"options",
".",
"extend",
"(",
"[",
"{",
"\"key\"",
":",
"(",
"\"|wu|Wpdate {} objects\"",
".",
"format",
"(",
"len",
"(",
"update_objects",
")",
")",
",",
"\"update\"",
",",
"\"u\"",
")",
",",
"\"desc\"",
":",
"\"Update {} objects\"",
".",
"format",
"(",
"len",
"(",
"update_objects",
")",
")",
",",
"\"goto\"",
":",
"(",
"_apply_diff",
",",
"{",
"\"prototype\"",
":",
"prototype",
",",
"\"objects\"",
":",
"update_objects",
",",
"\"back_node\"",
":",
"back_node",
",",
"\"diff\"",
":",
"diff",
",",
"\"base_obj\"",
":",
"base_obj",
"}",
")",
"}",
",",
"{",
"\"key\"",
":",
"(",
"\"|wr|Weset changes\"",
",",
"\"reset\"",
",",
"\"r\"",
")",
",",
"\"goto\"",
":",
"(",
"\"node_apply_diff\"",
",",
"{",
"\"prototype\"",
":",
"prototype",
",",
"\"back_node\"",
":",
"back_node",
",",
"\"objects\"",
":",
"update_objects",
"}",
")",
"}",
"]",
")",
"else",
":",
"text",
"=",
"[",
"\"Analyzed a random sample object (out of {}) - \"",
"\"found no changes to apply.\"",
".",
"format",
"(",
"len",
"(",
"update_objects",
")",
")",
"]",
"options",
".",
"extend",
"(",
"_wizard_options",
"(",
"\"update_objects\"",
",",
"back_node",
"[",
"5",
":",
"]",
",",
"None",
")",
")",
"options",
".",
"append",
"(",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"back_node",
"}",
")",
"text",
"=",
"\"\\n\"",
".",
"join",
"(",
"text",
")",
"text",
"=",
"(",
"text",
",",
"helptext",
")",
"return",
"text",
",",
"options"
] | [
2048,
0
] | [
2123,
24
] | python | en | ['en', 'en', 'en'] | True |
node_prototype_save | (caller, **kwargs) | Save prototype to disk | Save prototype to disk | def node_prototype_save(caller, **kwargs):
"""Save prototype to disk """
# these are only set if we selected 'yes' to save on a previous pass
prototype = kwargs.get("prototype", None)
# set to True/False if answered, None if first pass
accept_save = kwargs.get("accept_save", None)
if accept_save and prototype:
# we already validated and accepted the save, so this node acts as a goto callback and
# should now only return the next node
prototype_key = prototype.get("prototype_key")
protlib.save_prototype(**prototype)
spawned_objects = protlib.search_objects_with_prototype(prototype_key)
nspawned = spawned_objects.count()
text = ["|gPrototype saved.|n"]
if nspawned:
text.append("\nDo you want to update {} object(s) "
"already using this prototype?".format(nspawned))
options = (
{"key": ("|wY|Wes|n", "yes", "y"),
"desc": "Go to updating screen",
"goto": ("node_apply_diff",
{"accept_update": True, "objects": spawned_objects,
"prototype": prototype, "back_node": "node_prototype_save"})},
{"key": ("[|wN|Wo|n]", "n"),
"desc": "Return to index",
"goto": "node_index"},
{"key": "_default",
"goto": "node_index"})
else:
text.append("(press Return to continue)")
options = {"key": "_default",
"goto": "node_index"}
text = "\n".join(text)
helptext = """
Updating objects means that the spawner will find all objects previously created by this
prototype. You will be presented with a list of the changes the system will try to apply to
each of these objects and you can choose to customize that change if needed. If you have
done a lot of manual changes to your objects after spawning, you might want to update those
objects manually instead.
"""
text = (text, helptext)
return text, options
# not validated yet
prototype = _get_menu_prototype(caller)
error, text = _validate_prototype(prototype)
text = [text]
if error:
# abort save
text.append(
"\n|yValidation errors were found. They need to be corrected before this prototype "
"can be saved (or used to spawn).|n")
options = _wizard_options("prototype_save", "index", None)
options.append({"key": "_default",
"goto": "node_index"})
return "\n".join(text), options
prototype_key = prototype['prototype_key']
if protlib.search_prototype(prototype_key):
text.append("\nDo you want to save/overwrite the existing prototype '{name}'?".format(
name=prototype_key))
else:
text.append("\nDo you want to save the prototype as '{name}'?".format(name=prototype_key))
text = "\n".join(text)
helptext = """
Saving the prototype makes it available for use later. It can also be used to inherit from,
by name. Depending on |cprototype-locks|n it also makes the prototype usable and/or
editable by others. Consider setting good |cPrototype-tags|n and to give a useful, brief
|cPrototype-desc|n to make the prototype easy to find later.
"""
text = (text, helptext)
options = (
{"key": ("[|wY|Wes|n]", "yes", "y"),
"desc": "Save prototype",
"goto": ("node_prototype_save",
{"accept_save": True, "prototype": prototype})},
{"key": ("|wN|Wo|n", "n"),
"desc": "Abort and return to Index",
"goto": "node_index"},
{"key": "_default",
"goto": ("node_prototype_save",
{"accept_save": True, "prototype": prototype})})
return text, options | [
"def",
"node_prototype_save",
"(",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"# these are only set if we selected 'yes' to save on a previous pass",
"prototype",
"=",
"kwargs",
".",
"get",
"(",
"\"prototype\"",
",",
"None",
")",
"# set to True/False if answered, None if first pass",
"accept_save",
"=",
"kwargs",
".",
"get",
"(",
"\"accept_save\"",
",",
"None",
")",
"if",
"accept_save",
"and",
"prototype",
":",
"# we already validated and accepted the save, so this node acts as a goto callback and",
"# should now only return the next node",
"prototype_key",
"=",
"prototype",
".",
"get",
"(",
"\"prototype_key\"",
")",
"protlib",
".",
"save_prototype",
"(",
"*",
"*",
"prototype",
")",
"spawned_objects",
"=",
"protlib",
".",
"search_objects_with_prototype",
"(",
"prototype_key",
")",
"nspawned",
"=",
"spawned_objects",
".",
"count",
"(",
")",
"text",
"=",
"[",
"\"|gPrototype saved.|n\"",
"]",
"if",
"nspawned",
":",
"text",
".",
"append",
"(",
"\"\\nDo you want to update {} object(s) \"",
"\"already using this prototype?\"",
".",
"format",
"(",
"nspawned",
")",
")",
"options",
"=",
"(",
"{",
"\"key\"",
":",
"(",
"\"|wY|Wes|n\"",
",",
"\"yes\"",
",",
"\"y\"",
")",
",",
"\"desc\"",
":",
"\"Go to updating screen\"",
",",
"\"goto\"",
":",
"(",
"\"node_apply_diff\"",
",",
"{",
"\"accept_update\"",
":",
"True",
",",
"\"objects\"",
":",
"spawned_objects",
",",
"\"prototype\"",
":",
"prototype",
",",
"\"back_node\"",
":",
"\"node_prototype_save\"",
"}",
")",
"}",
",",
"{",
"\"key\"",
":",
"(",
"\"[|wN|Wo|n]\"",
",",
"\"n\"",
")",
",",
"\"desc\"",
":",
"\"Return to index\"",
",",
"\"goto\"",
":",
"\"node_index\"",
"}",
",",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"\"node_index\"",
"}",
")",
"else",
":",
"text",
".",
"append",
"(",
"\"(press Return to continue)\"",
")",
"options",
"=",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"\"node_index\"",
"}",
"text",
"=",
"\"\\n\"",
".",
"join",
"(",
"text",
")",
"helptext",
"=",
"\"\"\"\n Updating objects means that the spawner will find all objects previously created by this\n prototype. You will be presented with a list of the changes the system will try to apply to\n each of these objects and you can choose to customize that change if needed. If you have\n done a lot of manual changes to your objects after spawning, you might want to update those\n objects manually instead.\n \"\"\"",
"text",
"=",
"(",
"text",
",",
"helptext",
")",
"return",
"text",
",",
"options",
"# not validated yet",
"prototype",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"error",
",",
"text",
"=",
"_validate_prototype",
"(",
"prototype",
")",
"text",
"=",
"[",
"text",
"]",
"if",
"error",
":",
"# abort save",
"text",
".",
"append",
"(",
"\"\\n|yValidation errors were found. They need to be corrected before this prototype \"",
"\"can be saved (or used to spawn).|n\"",
")",
"options",
"=",
"_wizard_options",
"(",
"\"prototype_save\"",
",",
"\"index\"",
",",
"None",
")",
"options",
".",
"append",
"(",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"\"node_index\"",
"}",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"text",
")",
",",
"options",
"prototype_key",
"=",
"prototype",
"[",
"'prototype_key'",
"]",
"if",
"protlib",
".",
"search_prototype",
"(",
"prototype_key",
")",
":",
"text",
".",
"append",
"(",
"\"\\nDo you want to save/overwrite the existing prototype '{name}'?\"",
".",
"format",
"(",
"name",
"=",
"prototype_key",
")",
")",
"else",
":",
"text",
".",
"append",
"(",
"\"\\nDo you want to save the prototype as '{name}'?\"",
".",
"format",
"(",
"name",
"=",
"prototype_key",
")",
")",
"text",
"=",
"\"\\n\"",
".",
"join",
"(",
"text",
")",
"helptext",
"=",
"\"\"\"\n Saving the prototype makes it available for use later. It can also be used to inherit from,\n by name. Depending on |cprototype-locks|n it also makes the prototype usable and/or\n editable by others. Consider setting good |cPrototype-tags|n and to give a useful, brief\n |cPrototype-desc|n to make the prototype easy to find later.\n\n \"\"\"",
"text",
"=",
"(",
"text",
",",
"helptext",
")",
"options",
"=",
"(",
"{",
"\"key\"",
":",
"(",
"\"[|wY|Wes|n]\"",
",",
"\"yes\"",
",",
"\"y\"",
")",
",",
"\"desc\"",
":",
"\"Save prototype\"",
",",
"\"goto\"",
":",
"(",
"\"node_prototype_save\"",
",",
"{",
"\"accept_save\"",
":",
"True",
",",
"\"prototype\"",
":",
"prototype",
"}",
")",
"}",
",",
"{",
"\"key\"",
":",
"(",
"\"|wN|Wo|n\"",
",",
"\"n\"",
")",
",",
"\"desc\"",
":",
"\"Abort and return to Index\"",
",",
"\"goto\"",
":",
"\"node_index\"",
"}",
",",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"(",
"\"node_prototype_save\"",
",",
"{",
"\"accept_save\"",
":",
"True",
",",
"\"prototype\"",
":",
"prototype",
"}",
")",
"}",
")",
"return",
"text",
",",
"options"
] | [
2129,
0
] | [
2227,
25
] | python | en | ['en', 'en', 'en'] | True |
_spawn | (caller, **kwargs) | Spawn prototype | Spawn prototype | def _spawn(caller, **kwargs):
"""Spawn prototype"""
prototype = kwargs["prototype"].copy()
new_location = kwargs.get('location', None)
if new_location:
prototype['location'] = new_location
if not prototype.get('location'):
prototype['location'] = caller
obj = spawner.spawn(prototype)
if obj:
obj = obj[0]
text = "|gNew instance|n {key} ({dbref}) |gspawned at location |n{loc}|n|g.|n".format(
key=obj.key, dbref=obj.dbref, loc=prototype['location'])
else:
text = "|rError: Spawner did not return a new instance.|n"
return "node_examine_entity", {"text": text, "back": "prototype_spawn"} | [
"def",
"_spawn",
"(",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"prototype",
"=",
"kwargs",
"[",
"\"prototype\"",
"]",
".",
"copy",
"(",
")",
"new_location",
"=",
"kwargs",
".",
"get",
"(",
"'location'",
",",
"None",
")",
"if",
"new_location",
":",
"prototype",
"[",
"'location'",
"]",
"=",
"new_location",
"if",
"not",
"prototype",
".",
"get",
"(",
"'location'",
")",
":",
"prototype",
"[",
"'location'",
"]",
"=",
"caller",
"obj",
"=",
"spawner",
".",
"spawn",
"(",
"prototype",
")",
"if",
"obj",
":",
"obj",
"=",
"obj",
"[",
"0",
"]",
"text",
"=",
"\"|gNew instance|n {key} ({dbref}) |gspawned at location |n{loc}|n|g.|n\"",
".",
"format",
"(",
"key",
"=",
"obj",
".",
"key",
",",
"dbref",
"=",
"obj",
".",
"dbref",
",",
"loc",
"=",
"prototype",
"[",
"'location'",
"]",
")",
"else",
":",
"text",
"=",
"\"|rError: Spawner did not return a new instance.|n\"",
"return",
"\"node_examine_entity\"",
",",
"{",
"\"text\"",
":",
"text",
",",
"\"back\"",
":",
"\"prototype_spawn\"",
"}"
] | [
2233,
0
] | [
2249,
75
] | python | en | ['en', 'sr', 'en'] | False |
node_prototype_spawn | (caller, **kwargs) | Submenu for spawning the prototype | Submenu for spawning the prototype | def node_prototype_spawn(caller, **kwargs):
"""Submenu for spawning the prototype"""
prototype = _get_menu_prototype(caller)
already_validated = kwargs.get("already_validated", False)
if already_validated:
error, text = None, []
else:
error, text = _validate_prototype(prototype)
text = [text]
if error:
text.append("\n|rPrototype validation failed. Correct the errors before spawning.|n")
options = _wizard_options("prototype_spawn", "index", None)
return "\n".join(text), options
text = "\n".join(text)
helptext = """
Spawning is the act of instantiating a prototype into an actual object. As a new object is
spawned, every $protfunc in the prototype is called anew. Since this is a common thing to
do, you may also temporarily change the |clocation|n of this prototype to bypass whatever
value is set in the prototype.
"""
text = (text, helptext)
# show spawn submenu options
options = []
prototype_key = prototype['prototype_key']
location = prototype.get('location', None)
if location:
options.append(
{"desc": "Spawn in prototype's defined location ({loc})".format(loc=location),
"goto": (_spawn,
dict(prototype=prototype, location=location, custom_location=True))})
caller_loc = caller.location
if location != caller_loc:
options.append(
{"desc": "Spawn in {caller}'s location ({loc})".format(
caller=caller, loc=caller_loc),
"goto": (_spawn,
dict(prototype=prototype, location=caller_loc))})
if location != caller_loc != caller:
options.append(
{"desc": "Spawn in {caller}'s inventory".format(caller=caller),
"goto": (_spawn,
dict(prototype=prototype, location=caller))})
spawned_objects = protlib.search_objects_with_prototype(prototype_key)
nspawned = spawned_objects.count()
if spawned_objects:
options.append(
{"desc": "Update {num} existing objects with this prototype".format(num=nspawned),
"goto": ("node_apply_diff",
{"objects": list(spawned_objects),
"prototype": prototype,
"back_node": "node_prototype_spawn"})})
options.extend(_wizard_options("prototype_spawn", "index", None))
options.append({"key": "_default",
"goto": "node_index"})
return text, options | [
"def",
"node_prototype_spawn",
"(",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"prototype",
"=",
"_get_menu_prototype",
"(",
"caller",
")",
"already_validated",
"=",
"kwargs",
".",
"get",
"(",
"\"already_validated\"",
",",
"False",
")",
"if",
"already_validated",
":",
"error",
",",
"text",
"=",
"None",
",",
"[",
"]",
"else",
":",
"error",
",",
"text",
"=",
"_validate_prototype",
"(",
"prototype",
")",
"text",
"=",
"[",
"text",
"]",
"if",
"error",
":",
"text",
".",
"append",
"(",
"\"\\n|rPrototype validation failed. Correct the errors before spawning.|n\"",
")",
"options",
"=",
"_wizard_options",
"(",
"\"prototype_spawn\"",
",",
"\"index\"",
",",
"None",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"text",
")",
",",
"options",
"text",
"=",
"\"\\n\"",
".",
"join",
"(",
"text",
")",
"helptext",
"=",
"\"\"\"\n Spawning is the act of instantiating a prototype into an actual object. As a new object is\n spawned, every $protfunc in the prototype is called anew. Since this is a common thing to\n do, you may also temporarily change the |clocation|n of this prototype to bypass whatever\n value is set in the prototype.\n\n \"\"\"",
"text",
"=",
"(",
"text",
",",
"helptext",
")",
"# show spawn submenu options",
"options",
"=",
"[",
"]",
"prototype_key",
"=",
"prototype",
"[",
"'prototype_key'",
"]",
"location",
"=",
"prototype",
".",
"get",
"(",
"'location'",
",",
"None",
")",
"if",
"location",
":",
"options",
".",
"append",
"(",
"{",
"\"desc\"",
":",
"\"Spawn in prototype's defined location ({loc})\"",
".",
"format",
"(",
"loc",
"=",
"location",
")",
",",
"\"goto\"",
":",
"(",
"_spawn",
",",
"dict",
"(",
"prototype",
"=",
"prototype",
",",
"location",
"=",
"location",
",",
"custom_location",
"=",
"True",
")",
")",
"}",
")",
"caller_loc",
"=",
"caller",
".",
"location",
"if",
"location",
"!=",
"caller_loc",
":",
"options",
".",
"append",
"(",
"{",
"\"desc\"",
":",
"\"Spawn in {caller}'s location ({loc})\"",
".",
"format",
"(",
"caller",
"=",
"caller",
",",
"loc",
"=",
"caller_loc",
")",
",",
"\"goto\"",
":",
"(",
"_spawn",
",",
"dict",
"(",
"prototype",
"=",
"prototype",
",",
"location",
"=",
"caller_loc",
")",
")",
"}",
")",
"if",
"location",
"!=",
"caller_loc",
"!=",
"caller",
":",
"options",
".",
"append",
"(",
"{",
"\"desc\"",
":",
"\"Spawn in {caller}'s inventory\"",
".",
"format",
"(",
"caller",
"=",
"caller",
")",
",",
"\"goto\"",
":",
"(",
"_spawn",
",",
"dict",
"(",
"prototype",
"=",
"prototype",
",",
"location",
"=",
"caller",
")",
")",
"}",
")",
"spawned_objects",
"=",
"protlib",
".",
"search_objects_with_prototype",
"(",
"prototype_key",
")",
"nspawned",
"=",
"spawned_objects",
".",
"count",
"(",
")",
"if",
"spawned_objects",
":",
"options",
".",
"append",
"(",
"{",
"\"desc\"",
":",
"\"Update {num} existing objects with this prototype\"",
".",
"format",
"(",
"num",
"=",
"nspawned",
")",
",",
"\"goto\"",
":",
"(",
"\"node_apply_diff\"",
",",
"{",
"\"objects\"",
":",
"list",
"(",
"spawned_objects",
")",
",",
"\"prototype\"",
":",
"prototype",
",",
"\"back_node\"",
":",
"\"node_prototype_spawn\"",
"}",
")",
"}",
")",
"options",
".",
"extend",
"(",
"_wizard_options",
"(",
"\"prototype_spawn\"",
",",
"\"index\"",
",",
"None",
")",
")",
"options",
".",
"append",
"(",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"\"node_index\"",
"}",
")",
"return",
"text",
",",
"options"
] | [
2252,
0
] | [
2317,
24
] | python | en | ['en', 'en', 'en'] | True |
_prototype_load_actions | (caller, raw_inp, **kwargs) | Parse the default Convert prototype to a string representation for closer inspection | Parse the default Convert prototype to a string representation for closer inspection | def _prototype_load_actions(caller, raw_inp, **kwargs):
"""Parse the default Convert prototype to a string representation for closer inspection"""
choices = kwargs.get("available_choices", [])
prototype, action = _default_parse(
raw_inp, choices, ("examine", "e", "l"), ("delete", "del", "d"))
if prototype:
# which action to apply on the selection
if action == 'examine':
# examine the prototype
prototype = protlib.search_prototype(key=prototype)[0]
txt = protlib.prototype_to_str(prototype)
return "node_examine_entity", {"text": txt, "back": 'prototype_load'}
elif action == 'delete':
# delete prototype from disk
try:
protlib.delete_prototype(prototype, caller=caller)
except protlib.PermissionError as err:
txt = "|rDeletion error:|n {}".format(err)
else:
txt = "|gPrototype {} was deleted.|n".format(prototype)
return "node_examine_entity", {"text": txt, "back": "prototype_load"}
return 'node_prototype_load' | [
"def",
"_prototype_load_actions",
"(",
"caller",
",",
"raw_inp",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"kwargs",
".",
"get",
"(",
"\"available_choices\"",
",",
"[",
"]",
")",
"prototype",
",",
"action",
"=",
"_default_parse",
"(",
"raw_inp",
",",
"choices",
",",
"(",
"\"examine\"",
",",
"\"e\"",
",",
"\"l\"",
")",
",",
"(",
"\"delete\"",
",",
"\"del\"",
",",
"\"d\"",
")",
")",
"if",
"prototype",
":",
"# which action to apply on the selection",
"if",
"action",
"==",
"'examine'",
":",
"# examine the prototype",
"prototype",
"=",
"protlib",
".",
"search_prototype",
"(",
"key",
"=",
"prototype",
")",
"[",
"0",
"]",
"txt",
"=",
"protlib",
".",
"prototype_to_str",
"(",
"prototype",
")",
"return",
"\"node_examine_entity\"",
",",
"{",
"\"text\"",
":",
"txt",
",",
"\"back\"",
":",
"'prototype_load'",
"}",
"elif",
"action",
"==",
"'delete'",
":",
"# delete prototype from disk",
"try",
":",
"protlib",
".",
"delete_prototype",
"(",
"prototype",
",",
"caller",
"=",
"caller",
")",
"except",
"protlib",
".",
"PermissionError",
"as",
"err",
":",
"txt",
"=",
"\"|rDeletion error:|n {}\"",
".",
"format",
"(",
"err",
")",
"else",
":",
"txt",
"=",
"\"|gPrototype {} was deleted.|n\"",
".",
"format",
"(",
"prototype",
")",
"return",
"\"node_examine_entity\"",
",",
"{",
"\"text\"",
":",
"txt",
",",
"\"back\"",
":",
"\"prototype_load\"",
"}",
"return",
"'node_prototype_load'"
] | [
2336,
0
] | [
2360,
32
] | python | en | ['en', 'en', 'en'] | True |
node_prototype_load | (caller, **kwargs) | Load prototype | Load prototype | def node_prototype_load(caller, **kwargs):
"""Load prototype"""
text = """
Select a prototype to load. This will replace any prototype currently being edited!
"""
_set_actioninfo(caller, _format_list_actions("examine", "delete"))
helptext = """
Loading a prototype will load it and return you to the main index. It can be a good idea
to examine the prototype before loading it.
"""
text = (text, helptext)
options = _wizard_options("prototype_load", "index", None)
options.append({"key": "_default",
"goto": _prototype_load_actions})
return text, options | [
"def",
"node_prototype_load",
"(",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"text",
"=",
"\"\"\"\n Select a prototype to load. This will replace any prototype currently being edited!\n \"\"\"",
"_set_actioninfo",
"(",
"caller",
",",
"_format_list_actions",
"(",
"\"examine\"",
",",
"\"delete\"",
")",
")",
"helptext",
"=",
"\"\"\"\n Loading a prototype will load it and return you to the main index. It can be a good idea\n to examine the prototype before loading it.\n \"\"\"",
"text",
"=",
"(",
"text",
",",
"helptext",
")",
"options",
"=",
"_wizard_options",
"(",
"\"prototype_load\"",
",",
"\"index\"",
",",
"None",
")",
"options",
".",
"append",
"(",
"{",
"\"key\"",
":",
"\"_default\"",
",",
"\"goto\"",
":",
"_prototype_load_actions",
"}",
")",
"return",
"text",
",",
"options"
] | [
2364,
0
] | [
2383,
24
] | python | en | ['en', 'sr', 'en'] | False |
start_olc | (caller, session=None, prototype=None) |
Start menu-driven olc system for prototypes.
Args:
caller (Object or Account): The entity starting the menu.
session (Session, optional): The individual session to get data.
prototype (dict, optional): Given when editing an existing
prototype rather than creating a new one.
|
Start menu-driven olc system for prototypes. | def start_olc(caller, session=None, prototype=None):
"""
Start menu-driven olc system for prototypes.
Args:
caller (Object or Account): The entity starting the menu.
session (Session, optional): The individual session to get data.
prototype (dict, optional): Given when editing an existing
prototype rather than creating a new one.
"""
menudata = {"node_index": node_index,
"node_validate_prototype": node_validate_prototype,
"node_examine_entity": node_examine_entity,
"node_search_object": node_search_object,
"node_prototype_key": node_prototype_key,
"node_prototype_parent": node_prototype_parent,
"node_typeclass": node_typeclass,
"node_key": node_key,
"node_aliases": node_aliases,
"node_attrs": node_attrs,
"node_tags": node_tags,
"node_locks": node_locks,
"node_permissions": node_permissions,
"node_location": node_location,
"node_home": node_home,
"node_destination": node_destination,
"node_apply_diff": node_apply_diff,
"node_prototype_desc": node_prototype_desc,
"node_prototype_tags": node_prototype_tags,
"node_prototype_locks": node_prototype_locks,
"node_prototype_load": node_prototype_load,
"node_prototype_save": node_prototype_save,
"node_prototype_spawn": node_prototype_spawn
}
OLCMenu(caller, menudata, startnode='node_index', session=session,
olc_prototype=prototype, debug=True) | [
"def",
"start_olc",
"(",
"caller",
",",
"session",
"=",
"None",
",",
"prototype",
"=",
"None",
")",
":",
"menudata",
"=",
"{",
"\"node_index\"",
":",
"node_index",
",",
"\"node_validate_prototype\"",
":",
"node_validate_prototype",
",",
"\"node_examine_entity\"",
":",
"node_examine_entity",
",",
"\"node_search_object\"",
":",
"node_search_object",
",",
"\"node_prototype_key\"",
":",
"node_prototype_key",
",",
"\"node_prototype_parent\"",
":",
"node_prototype_parent",
",",
"\"node_typeclass\"",
":",
"node_typeclass",
",",
"\"node_key\"",
":",
"node_key",
",",
"\"node_aliases\"",
":",
"node_aliases",
",",
"\"node_attrs\"",
":",
"node_attrs",
",",
"\"node_tags\"",
":",
"node_tags",
",",
"\"node_locks\"",
":",
"node_locks",
",",
"\"node_permissions\"",
":",
"node_permissions",
",",
"\"node_location\"",
":",
"node_location",
",",
"\"node_home\"",
":",
"node_home",
",",
"\"node_destination\"",
":",
"node_destination",
",",
"\"node_apply_diff\"",
":",
"node_apply_diff",
",",
"\"node_prototype_desc\"",
":",
"node_prototype_desc",
",",
"\"node_prototype_tags\"",
":",
"node_prototype_tags",
",",
"\"node_prototype_locks\"",
":",
"node_prototype_locks",
",",
"\"node_prototype_load\"",
":",
"node_prototype_load",
",",
"\"node_prototype_save\"",
":",
"node_prototype_save",
",",
"\"node_prototype_spawn\"",
":",
"node_prototype_spawn",
"}",
"OLCMenu",
"(",
"caller",
",",
"menudata",
",",
"startnode",
"=",
"'node_index'",
",",
"session",
"=",
"session",
",",
"olc_prototype",
"=",
"prototype",
",",
"debug",
"=",
"True",
")"
] | [
2437,
0
] | [
2473,
48
] | python | en | ['en', 'error', 'th'] | False |
OLCMenu.nodetext_formatter | (self, nodetext) |
Format the node text itself.
|
Format the node text itself. | def nodetext_formatter(self, nodetext):
"""
Format the node text itself.
"""
return super(OLCMenu, self).nodetext_formatter(nodetext) | [
"def",
"nodetext_formatter",
"(",
"self",
",",
"nodetext",
")",
":",
"return",
"super",
"(",
"OLCMenu",
",",
"self",
")",
".",
"nodetext_formatter",
"(",
"nodetext",
")"
] | [
2394,
4
] | [
2399,
64
] | python | en | ['en', 'error', 'th'] | False |
OLCMenu.options_formatter | (self, optionlist) |
Split the options into two blocks - olc options and normal options
|
Split the options into two blocks - olc options and normal options | def options_formatter(self, optionlist):
"""
Split the options into two blocks - olc options and normal options
"""
olc_keys = ("index", "forward", "back", "previous", "next", "validate prototype",
"save prototype", "load prototype", "spawn prototype", "search objects")
actioninfo = self.actioninfo + "\n" if hasattr(self, 'actioninfo') else ''
self.actioninfo = '' # important, or this could bleed over to other nodes
olc_options = []
other_options = []
for key, desc in optionlist:
raw_key = strip_ansi(key).lower()
if raw_key in olc_keys:
desc = " {}".format(desc) if desc else ""
olc_options.append("|lc{}|lt{}|le{}".format(raw_key, key, desc))
else:
other_options.append((key, desc))
olc_options = actioninfo + \
" |W|||n ".join(olc_options) + " |W|||n " + "|wQ|Wuit" if olc_options else ""
other_options = super(OLCMenu, self).options_formatter(other_options)
sep = "\n\n" if olc_options and other_options else ""
return "{}{}{}".format(olc_options, sep, other_options) | [
"def",
"options_formatter",
"(",
"self",
",",
"optionlist",
")",
":",
"olc_keys",
"=",
"(",
"\"index\"",
",",
"\"forward\"",
",",
"\"back\"",
",",
"\"previous\"",
",",
"\"next\"",
",",
"\"validate prototype\"",
",",
"\"save prototype\"",
",",
"\"load prototype\"",
",",
"\"spawn prototype\"",
",",
"\"search objects\"",
")",
"actioninfo",
"=",
"self",
".",
"actioninfo",
"+",
"\"\\n\"",
"if",
"hasattr",
"(",
"self",
",",
"'actioninfo'",
")",
"else",
"''",
"self",
".",
"actioninfo",
"=",
"''",
"# important, or this could bleed over to other nodes",
"olc_options",
"=",
"[",
"]",
"other_options",
"=",
"[",
"]",
"for",
"key",
",",
"desc",
"in",
"optionlist",
":",
"raw_key",
"=",
"strip_ansi",
"(",
"key",
")",
".",
"lower",
"(",
")",
"if",
"raw_key",
"in",
"olc_keys",
":",
"desc",
"=",
"\" {}\"",
".",
"format",
"(",
"desc",
")",
"if",
"desc",
"else",
"\"\"",
"olc_options",
".",
"append",
"(",
"\"|lc{}|lt{}|le{}\"",
".",
"format",
"(",
"raw_key",
",",
"key",
",",
"desc",
")",
")",
"else",
":",
"other_options",
".",
"append",
"(",
"(",
"key",
",",
"desc",
")",
")",
"olc_options",
"=",
"actioninfo",
"+",
"\" |W|||n \"",
".",
"join",
"(",
"olc_options",
")",
"+",
"\" |W|||n \"",
"+",
"\"|wQ|Wuit\"",
"if",
"olc_options",
"else",
"\"\"",
"other_options",
"=",
"super",
"(",
"OLCMenu",
",",
"self",
")",
".",
"options_formatter",
"(",
"other_options",
")",
"sep",
"=",
"\"\\n\\n\"",
"if",
"olc_options",
"and",
"other_options",
"else",
"\"\"",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"olc_options",
",",
"sep",
",",
"other_options",
")"
] | [
2401,
4
] | [
2425,
63
] | python | en | ['en', 'error', 'th'] | False |
OLCMenu.helptext_formatter | (self, helptext) |
Show help text
|
Show help text
| def helptext_formatter(self, helptext):
"""
Show help text
"""
return "|c --- Help ---|n\n" + utils.dedent(helptext) | [
"def",
"helptext_formatter",
"(",
"self",
",",
"helptext",
")",
":",
"return",
"\"|c --- Help ---|n\\n\"",
"+",
"utils",
".",
"dedent",
"(",
"helptext",
")"
] | [
2427,
4
] | [
2431,
61
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.color | (self) |
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
|
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen | def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
"""
return self["color"] | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
63,
28
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.family | (self) |
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
|
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string | def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"] | [
"def",
"family",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"family\"",
"]"
] | [
72,
4
] | [
94,
29
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.size | (self) |
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
|
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf] | def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"] | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
103,
4
] | [
112,
27
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.__init__ | (self, arg=None, color=None, family=None, size=None, **kwargs) |
Construct a new Tickfont object
Sets the color bar's tick label font
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.contourcarpet.
colorbar.Tickfont`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Tickfont
|
Construct a new Tickfont object
Sets the color bar's tick label font | def __init__(self, arg=None, color=None, family=None, size=None, **kwargs):
"""
Construct a new Tickfont object
Sets the color bar's tick label font
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.contourcarpet.
colorbar.Tickfont`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Tickfont
"""
super(Tickfont, self).__init__("tickfont")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.contourcarpet.colorbar.Tickfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.contourcarpet.colorbar.Tickfont`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"family",
"=",
"None",
",",
"size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Tickfont",
",",
"self",
")",
".",
"__init__",
"(",
"\"tickfont\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.contourcarpet.colorbar.Tickfont \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.contourcarpet.colorbar.Tickfont`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"color\"",
",",
"None",
")",
"_v",
"=",
"color",
"if",
"color",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"color\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"family\"",
",",
"None",
")",
"_v",
"=",
"family",
"if",
"family",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"family\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"size\"",
",",
"None",
")",
"_v",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"size\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
143,
4
] | [
226,
34
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.dtickrange | (self) |
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type
Returns
-------
list
|
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type | def dtickrange(self):
"""
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type
Returns
-------
list
"""
return self["dtickrange"] | [
"def",
"dtickrange",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"dtickrange\"",
"]"
] | [
15,
4
] | [
31,
33
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.enabled | (self) |
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False) | def enabled(self):
"""
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["enabled"] | [
"def",
"enabled",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"enabled\"",
"]"
] | [
40,
4
] | [
52,
30
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.name | (self) |
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
|
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string | def name(self):
"""
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["name"] | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"name\"",
"]"
] | [
61,
4
] | [
79,
27
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.templateitemname | (self) |
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
|
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string | def templateitemname(self):
"""
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["templateitemname"] | [
"def",
"templateitemname",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"templateitemname\"",
"]"
] | [
88,
4
] | [
107,
39
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.value | (self) |
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
|
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string | def value(self):
"""
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["value"] | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"value\"",
"]"
] | [
116,
4
] | [
129,
28
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.__init__ | (
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs
) |
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.indicator.gaug
e.axis.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
|
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.indicator.gaug
e.axis.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat" | def __init__(
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs
):
"""
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.indicator.gaug
e.axis.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
"""
super(Tickformatstop, self).__init__("tickformatstops")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.indicator.gauge.axis.Tickformatstop
constructor must be a dict or
an instance of :class:`plotly.graph_objs.indicator.gauge.axis.Tickformatstop`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("dtickrange", None)
_v = dtickrange if dtickrange is not None else _v
if _v is not None:
self["dtickrange"] = _v
_v = arg.pop("enabled", None)
_v = enabled if enabled is not None else _v
if _v is not None:
self["enabled"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("templateitemname", None)
_v = templateitemname if templateitemname is not None else _v
if _v is not None:
self["templateitemname"] = _v
_v = arg.pop("value", None)
_v = value if value is not None else _v
if _v is not None:
self["value"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"dtickrange",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"name",
"=",
"None",
",",
"templateitemname",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Tickformatstop",
",",
"self",
")",
".",
"__init__",
"(",
"\"tickformatstops\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.indicator.gauge.axis.Tickformatstop \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.indicator.gauge.axis.Tickformatstop`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"dtickrange\"",
",",
"None",
")",
"_v",
"=",
"dtickrange",
"if",
"dtickrange",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"dtickrange\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"enabled\"",
",",
"None",
")",
"_v",
"=",
"enabled",
"if",
"enabled",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"enabled\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"name\"",
",",
"None",
")",
"_v",
"=",
"name",
"if",
"name",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"name\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"templateitemname\"",
",",
"None",
")",
"_v",
"=",
"templateitemname",
"if",
"templateitemname",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"templateitemname\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"value\"",
",",
"None",
")",
"_v",
"=",
"value",
"if",
"value",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"value\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
172,
4
] | [
282,
34
] | python | en | ['en', 'error', 'th'] | False |
TypeclassBase.__new__ | (cls, name, bases, attrs) |
We must define our Typeclasses as proxies. We also store the
path directly on the class, this is required by managers.
|
We must define our Typeclasses as proxies. We also store the
path directly on the class, this is required by managers.
| def __new__(cls, name, bases, attrs):
"""
We must define our Typeclasses as proxies. We also store the
path directly on the class, this is required by managers.
"""
# storage of stats
attrs["typename"] = name
attrs["path"] = "%s.%s" % (attrs["__module__"], name)
# typeclass proxy setup
if "Meta" not in attrs:
class Meta(object):
proxy = True
app_label = attrs.get("__applabel__", "typeclasses")
attrs["Meta"] = Meta
attrs["Meta"].proxy = True
new_class = ModelBase.__new__(cls, name, bases, attrs)
# attach signals
signals.post_save.connect(post_save, sender=new_class)
signals.pre_delete.connect(remove_attributes_on_delete, sender=new_class)
return new_class | [
"def",
"__new__",
"(",
"cls",
",",
"name",
",",
"bases",
",",
"attrs",
")",
":",
"# storage of stats",
"attrs",
"[",
"\"typename\"",
"]",
"=",
"name",
"attrs",
"[",
"\"path\"",
"]",
"=",
"\"%s.%s\"",
"%",
"(",
"attrs",
"[",
"\"__module__\"",
"]",
",",
"name",
")",
"# typeclass proxy setup",
"if",
"\"Meta\"",
"not",
"in",
"attrs",
":",
"class",
"Meta",
"(",
"object",
")",
":",
"proxy",
"=",
"True",
"app_label",
"=",
"attrs",
".",
"get",
"(",
"\"__applabel__\"",
",",
"\"typeclasses\"",
")",
"attrs",
"[",
"\"Meta\"",
"]",
"=",
"Meta",
"attrs",
"[",
"\"Meta\"",
"]",
".",
"proxy",
"=",
"True",
"new_class",
"=",
"ModelBase",
".",
"__new__",
"(",
"cls",
",",
"name",
",",
"bases",
",",
"attrs",
")",
"# attach signals",
"signals",
".",
"post_save",
".",
"connect",
"(",
"post_save",
",",
"sender",
"=",
"new_class",
")",
"signals",
".",
"pre_delete",
".",
"connect",
"(",
"remove_attributes_on_delete",
",",
"sender",
"=",
"new_class",
")",
"return",
"new_class"
] | [
78,
4
] | [
101,
24
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.__init__ | (self, *args, **kwargs) |
The `__init__` method of typeclasses is the core operational
code of the typeclass system, where it dynamically re-applies
a class based on the db_typeclass_path database field rather
than use the one in the model.
Args:
Passed through to parent.
Kwargs:
Passed through to parent.
Notes:
The loading mechanism will attempt the following steps:
1. Attempt to load typeclass given on command line
2. Attempt to load typeclass stored in db_typeclass_path
3. Attempt to load `__settingsclasspath__`, which is by the
default classes defined to be the respective user-set
base typeclass settings, like `BASE_OBJECT_TYPECLASS`.
4. Attempt to load `__defaultclasspath__`, which is the
base classes in the library, like DefaultObject etc.
5. If everything else fails, use the database model.
Normal operation is to load successfully at either step 1
or 2 depending on how the class was called. Tracebacks
will be logged for every step the loader must take beyond
2.
|
The `__init__` method of typeclasses is the core operational
code of the typeclass system, where it dynamically re-applies
a class based on the db_typeclass_path database field rather
than use the one in the model. | def __init__(self, *args, **kwargs):
"""
The `__init__` method of typeclasses is the core operational
code of the typeclass system, where it dynamically re-applies
a class based on the db_typeclass_path database field rather
than use the one in the model.
Args:
Passed through to parent.
Kwargs:
Passed through to parent.
Notes:
The loading mechanism will attempt the following steps:
1. Attempt to load typeclass given on command line
2. Attempt to load typeclass stored in db_typeclass_path
3. Attempt to load `__settingsclasspath__`, which is by the
default classes defined to be the respective user-set
base typeclass settings, like `BASE_OBJECT_TYPECLASS`.
4. Attempt to load `__defaultclasspath__`, which is the
base classes in the library, like DefaultObject etc.
5. If everything else fails, use the database model.
Normal operation is to load successfully at either step 1
or 2 depending on how the class was called. Tracebacks
will be logged for every step the loader must take beyond
2.
"""
typeclass_path = kwargs.pop("typeclass", None)
super(TypedObject, self).__init__(*args, **kwargs)
self.set_class_from_typeclass(typeclass_path=typeclass_path) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"typeclass_path",
"=",
"kwargs",
".",
"pop",
"(",
"\"typeclass\"",
",",
"None",
")",
"super",
"(",
"TypedObject",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"set_class_from_typeclass",
"(",
"typeclass_path",
"=",
"typeclass_path",
")"
] | [
226,
4
] | [
259,
68
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.__dbid_get | (self) |
Caches and returns the unique id of the object.
Use this instead of self.id, which is not cached.
|
Caches and returns the unique id of the object.
Use this instead of self.id, which is not cached.
| def __dbid_get(self):
"""
Caches and returns the unique id of the object.
Use this instead of self.id, which is not cached.
"""
return self.id | [
"def",
"__dbid_get",
"(",
"self",
")",
":",
"return",
"self",
".",
"id"
] | [
345,
4
] | [
350,
22
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.__dbref_get | (self) |
Returns the object's dbref on the form #NN.
|
Returns the object's dbref on the form #NN.
| def __dbref_get(self):
"""
Returns the object's dbref on the form #NN.
"""
return "#%s" % self.id | [
"def",
"__dbref_get",
"(",
"self",
")",
":",
"return",
"\"#%s\"",
"%",
"self",
".",
"id"
] | [
360,
4
] | [
364,
30
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.at_idmapper_flush | (self) |
This is called when the idmapper cache is flushed and
allows customized actions when this happens.
Returns:
do_flush (bool): If True, flush this object as normal. If
False, don't flush and expect this object to handle
the flushing on its own.
Notes:
The default implementation relies on being able to clear
Django's Foreignkey cache on objects not affected by the
flush (notably objects with an NAttribute stored). We rely
on this cache being stored on the format "_<fieldname>_cache".
If Django were to change this name internally, we need to
update here (unlikely, but marking just in case).
|
This is called when the idmapper cache is flushed and
allows customized actions when this happens. | def at_idmapper_flush(self):
"""
This is called when the idmapper cache is flushed and
allows customized actions when this happens.
Returns:
do_flush (bool): If True, flush this object as normal. If
False, don't flush and expect this object to handle
the flushing on its own.
Notes:
The default implementation relies on being able to clear
Django's Foreignkey cache on objects not affected by the
flush (notably objects with an NAttribute stored). We rely
on this cache being stored on the format "_<fieldname>_cache".
If Django were to change this name internally, we need to
update here (unlikely, but marking just in case).
"""
if self.nattributes.all():
# we can't flush this object if we have non-persistent
# attributes stored - those would get lost! Nevertheless
# we try to flush as many references as we can.
self.attributes.reset_cache()
self.tags.reset_cache()
# flush caches for all related fields
for field in self._meta.fields:
name = "_%s_cache" % field.name
if field.is_relation and name in self.__dict__:
# a foreignkey - remove its cache
del self.__dict__[name]
return False
# a normal flush
return True | [
"def",
"at_idmapper_flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"nattributes",
".",
"all",
"(",
")",
":",
"# we can't flush this object if we have non-persistent",
"# attributes stored - those would get lost! Nevertheless",
"# we try to flush as many references as we can.",
"self",
".",
"attributes",
".",
"reset_cache",
"(",
")",
"self",
".",
"tags",
".",
"reset_cache",
"(",
")",
"# flush caches for all related fields",
"for",
"field",
"in",
"self",
".",
"_meta",
".",
"fields",
":",
"name",
"=",
"\"_%s_cache\"",
"%",
"field",
".",
"name",
"if",
"field",
".",
"is_relation",
"and",
"name",
"in",
"self",
".",
"__dict__",
":",
"# a foreignkey - remove its cache",
"del",
"self",
".",
"__dict__",
"[",
"name",
"]",
"return",
"False",
"# a normal flush",
"return",
"True"
] | [
373,
4
] | [
406,
19
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.is_typeclass | (self, typeclass, exact=True) |
Returns true if this object has this type OR has a typeclass
which is an subclass of the given typeclass. This operates on
the actually loaded typeclass (this is important since a
failing typeclass may instead have its default currently
loaded) typeclass - can be a class object or the python path
to such an object to match against.
Args:
typeclass (str or class): A class or the full python path
to the class to check.
exact (bool, optional): Returns true only if the object's
type is exactly this typeclass, ignoring parents.
Returns:
is_typeclass (bool): If this typeclass matches the given
typeclass.
|
Returns true if this object has this type OR has a typeclass
which is an subclass of the given typeclass. This operates on
the actually loaded typeclass (this is important since a
failing typeclass may instead have its default currently
loaded) typeclass - can be a class object or the python path
to such an object to match against. | def is_typeclass(self, typeclass, exact=True):
"""
Returns true if this object has this type OR has a typeclass
which is an subclass of the given typeclass. This operates on
the actually loaded typeclass (this is important since a
failing typeclass may instead have its default currently
loaded) typeclass - can be a class object or the python path
to such an object to match against.
Args:
typeclass (str or class): A class or the full python path
to the class to check.
exact (bool, optional): Returns true only if the object's
type is exactly this typeclass, ignoring parents.
Returns:
is_typeclass (bool): If this typeclass matches the given
typeclass.
"""
if isinstance(typeclass, basestring):
typeclass = [typeclass] + ["%s.%s" % (prefix, typeclass) for prefix in settings.TYPECLASS_PATHS]
else:
typeclass = [typeclass.path]
selfpath = self.path
if exact:
# check only exact match
return selfpath in typeclass
else:
# check parent chain
return any(hasattr(cls, "path") and cls.path in typeclass for cls in self.__class__.mro()) | [
"def",
"is_typeclass",
"(",
"self",
",",
"typeclass",
",",
"exact",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"typeclass",
",",
"basestring",
")",
":",
"typeclass",
"=",
"[",
"typeclass",
"]",
"+",
"[",
"\"%s.%s\"",
"%",
"(",
"prefix",
",",
"typeclass",
")",
"for",
"prefix",
"in",
"settings",
".",
"TYPECLASS_PATHS",
"]",
"else",
":",
"typeclass",
"=",
"[",
"typeclass",
".",
"path",
"]",
"selfpath",
"=",
"self",
".",
"path",
"if",
"exact",
":",
"# check only exact match",
"return",
"selfpath",
"in",
"typeclass",
"else",
":",
"# check parent chain",
"return",
"any",
"(",
"hasattr",
"(",
"cls",
",",
"\"path\"",
")",
"and",
"cls",
".",
"path",
"in",
"typeclass",
"for",
"cls",
"in",
"self",
".",
"__class__",
".",
"mro",
"(",
")",
")"
] | [
412,
4
] | [
443,
102
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.swap_typeclass | (self, new_typeclass, clean_attributes=False,
run_start_hooks="all", no_default=True, clean_cmdsets=False) |
This performs an in-situ swap of the typeclass. This means
that in-game, this object will suddenly be something else.
Account will not be affected. To 'move' an account to a different
object entirely (while retaining this object's type), use
self.account.swap_object().
Note that this might be an error prone operation if the
old/new typeclass was heavily customized - your code
might expect one and not the other, so be careful to
bug test your code if using this feature! Often its easiest
to create a new object and just swap the account over to
that one instead.
Args:
new_typeclass (str or classobj): Type to switch to.
clean_attributes (bool or list, optional): Will delete all
attributes stored on this object (but not any of the
database fields such as name or location). You can't get
attributes back, but this is often the safest bet to make
sure nothing in the new typeclass clashes with the old
one. If you supply a list, only those named attributes
will be cleared.
run_start_hooks (str or None, optional): This is either None,
to not run any hooks, "all" to run all hooks defined by
at_first_start, or a string giving the name of the hook
to run (for example 'at_object_creation'). This will
always be called without arguments.
no_default (bool, optiona): If set, the swapper will not
allow for swapping to a default typeclass in case the
given one fails for some reason. Instead the old one will
be preserved.
clean_cmdsets (bool, optional): Delete all cmdsets on the object.
|
This performs an in-situ swap of the typeclass. This means
that in-game, this object will suddenly be something else.
Account will not be affected. To 'move' an account to a different
object entirely (while retaining this object's type), use
self.account.swap_object(). | def swap_typeclass(self, new_typeclass, clean_attributes=False,
run_start_hooks="all", no_default=True, clean_cmdsets=False):
"""
This performs an in-situ swap of the typeclass. This means
that in-game, this object will suddenly be something else.
Account will not be affected. To 'move' an account to a different
object entirely (while retaining this object's type), use
self.account.swap_object().
Note that this might be an error prone operation if the
old/new typeclass was heavily customized - your code
might expect one and not the other, so be careful to
bug test your code if using this feature! Often its easiest
to create a new object and just swap the account over to
that one instead.
Args:
new_typeclass (str or classobj): Type to switch to.
clean_attributes (bool or list, optional): Will delete all
attributes stored on this object (but not any of the
database fields such as name or location). You can't get
attributes back, but this is often the safest bet to make
sure nothing in the new typeclass clashes with the old
one. If you supply a list, only those named attributes
will be cleared.
run_start_hooks (str or None, optional): This is either None,
to not run any hooks, "all" to run all hooks defined by
at_first_start, or a string giving the name of the hook
to run (for example 'at_object_creation'). This will
always be called without arguments.
no_default (bool, optiona): If set, the swapper will not
allow for swapping to a default typeclass in case the
given one fails for some reason. Instead the old one will
be preserved.
clean_cmdsets (bool, optional): Delete all cmdsets on the object.
"""
if not callable(new_typeclass):
# this is an actual class object - build the path
new_typeclass = class_from_module(new_typeclass, defaultpaths=settings.TYPECLASS_PATHS)
# if we get to this point, the class is ok.
if inherits_from(self, "evennia.scripts.models.ScriptDB"):
if self.interval > 0:
raise RuntimeError("Cannot use swap_typeclass on time-dependent "
"Script '%s'.\nStop and start a new Script of the "
"right type instead." % self.key)
self.typeclass_path = new_typeclass.path
self.__class__ = new_typeclass
if clean_attributes:
# Clean out old attributes
if is_iter(clean_attributes):
for attr in clean_attributes:
self.attributes.remove(attr)
for nattr in clean_attributes:
if hasattr(self.ndb, nattr):
self.nattributes.remove(nattr)
else:
self.attributes.clear()
self.nattributes.clear()
if clean_cmdsets:
# purge all cmdsets
self.cmdset.clear()
self.cmdset.remove_default()
if run_start_hooks == 'all':
# fake this call to mimic the first save
self.at_first_save()
elif run_start_hooks:
# a custom hook-name to call.
getattr(self, run_start_hooks)() | [
"def",
"swap_typeclass",
"(",
"self",
",",
"new_typeclass",
",",
"clean_attributes",
"=",
"False",
",",
"run_start_hooks",
"=",
"\"all\"",
",",
"no_default",
"=",
"True",
",",
"clean_cmdsets",
"=",
"False",
")",
":",
"if",
"not",
"callable",
"(",
"new_typeclass",
")",
":",
"# this is an actual class object - build the path",
"new_typeclass",
"=",
"class_from_module",
"(",
"new_typeclass",
",",
"defaultpaths",
"=",
"settings",
".",
"TYPECLASS_PATHS",
")",
"# if we get to this point, the class is ok.",
"if",
"inherits_from",
"(",
"self",
",",
"\"evennia.scripts.models.ScriptDB\"",
")",
":",
"if",
"self",
".",
"interval",
">",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot use swap_typeclass on time-dependent \"",
"\"Script '%s'.\\nStop and start a new Script of the \"",
"\"right type instead.\"",
"%",
"self",
".",
"key",
")",
"self",
".",
"typeclass_path",
"=",
"new_typeclass",
".",
"path",
"self",
".",
"__class__",
"=",
"new_typeclass",
"if",
"clean_attributes",
":",
"# Clean out old attributes",
"if",
"is_iter",
"(",
"clean_attributes",
")",
":",
"for",
"attr",
"in",
"clean_attributes",
":",
"self",
".",
"attributes",
".",
"remove",
"(",
"attr",
")",
"for",
"nattr",
"in",
"clean_attributes",
":",
"if",
"hasattr",
"(",
"self",
".",
"ndb",
",",
"nattr",
")",
":",
"self",
".",
"nattributes",
".",
"remove",
"(",
"nattr",
")",
"else",
":",
"self",
".",
"attributes",
".",
"clear",
"(",
")",
"self",
".",
"nattributes",
".",
"clear",
"(",
")",
"if",
"clean_cmdsets",
":",
"# purge all cmdsets",
"self",
".",
"cmdset",
".",
"clear",
"(",
")",
"self",
".",
"cmdset",
".",
"remove_default",
"(",
")",
"if",
"run_start_hooks",
"==",
"'all'",
":",
"# fake this call to mimic the first save",
"self",
".",
"at_first_save",
"(",
")",
"elif",
"run_start_hooks",
":",
"# a custom hook-name to call.",
"getattr",
"(",
"self",
",",
"run_start_hooks",
")",
"(",
")"
] | [
445,
4
] | [
519,
44
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.access | (self, accessing_obj, access_type='read', default=False, no_superuser_bypass=False, **kwargs) |
Determines if another object has permission to access this one.
Args:
accessing_obj (str): Object trying to access this one.
access_type (str, optional): Type of access sought.
default (bool, optional): What to return if no lock of
access_type was found
no_superuser_bypass (bool, optional): Turn off the
superuser lock bypass (be careful with this one).
Kwargs:
kwargs (any): Ignored, but is there to make the api
consistent with the object-typeclass method access, which
use it to feed to its hook methods.
|
Determines if another object has permission to access this one. | def access(self, accessing_obj, access_type='read', default=False, no_superuser_bypass=False, **kwargs):
"""
Determines if another object has permission to access this one.
Args:
accessing_obj (str): Object trying to access this one.
access_type (str, optional): Type of access sought.
default (bool, optional): What to return if no lock of
access_type was found
no_superuser_bypass (bool, optional): Turn off the
superuser lock bypass (be careful with this one).
Kwargs:
kwargs (any): Ignored, but is there to make the api
consistent with the object-typeclass method access, which
use it to feed to its hook methods.
"""
return self.locks.check(accessing_obj, access_type=access_type, default=default,
no_superuser_bypass=no_superuser_bypass) | [
"def",
"access",
"(",
"self",
",",
"accessing_obj",
",",
"access_type",
"=",
"'read'",
",",
"default",
"=",
"False",
",",
"no_superuser_bypass",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"locks",
".",
"check",
"(",
"accessing_obj",
",",
"access_type",
"=",
"access_type",
",",
"default",
"=",
"default",
",",
"no_superuser_bypass",
"=",
"no_superuser_bypass",
")"
] | [
525,
4
] | [
544,
72
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.check_permstring | (self, permstring) |
This explicitly checks if we hold particular permission
without involving any locks.
Args:
permstring (str): The permission string to check against.
Returns:
result (bool): If the permstring is passed or not.
|
This explicitly checks if we hold particular permission
without involving any locks. | def check_permstring(self, permstring):
"""
This explicitly checks if we hold particular permission
without involving any locks.
Args:
permstring (str): The permission string to check against.
Returns:
result (bool): If the permstring is passed or not.
"""
if hasattr(self, "account"):
if self.account and self.account.is_superuser and not self.account.attributes.get("_quell"):
return True
else:
if self.is_superuser and not self.attributes.get("_quell"):
return True
if not permstring:
return False
perm = permstring.lower()
perms = [p.lower() for p in self.permissions.all()]
if perm in perms:
# simplest case - we have a direct match
return True
if perm in _PERMISSION_HIERARCHY:
# check if we have a higher hierarchy position
ppos = _PERMISSION_HIERARCHY.index(perm)
return any(True for hpos, hperm in enumerate(_PERMISSION_HIERARCHY)
if hperm in perms and hpos > ppos)
# we ignore pluralization (english only)
if perm.endswith("s"):
return self.check_permstring(perm[:-1])
return False | [
"def",
"check_permstring",
"(",
"self",
",",
"permstring",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"account\"",
")",
":",
"if",
"self",
".",
"account",
"and",
"self",
".",
"account",
".",
"is_superuser",
"and",
"not",
"self",
".",
"account",
".",
"attributes",
".",
"get",
"(",
"\"_quell\"",
")",
":",
"return",
"True",
"else",
":",
"if",
"self",
".",
"is_superuser",
"and",
"not",
"self",
".",
"attributes",
".",
"get",
"(",
"\"_quell\"",
")",
":",
"return",
"True",
"if",
"not",
"permstring",
":",
"return",
"False",
"perm",
"=",
"permstring",
".",
"lower",
"(",
")",
"perms",
"=",
"[",
"p",
".",
"lower",
"(",
")",
"for",
"p",
"in",
"self",
".",
"permissions",
".",
"all",
"(",
")",
"]",
"if",
"perm",
"in",
"perms",
":",
"# simplest case - we have a direct match",
"return",
"True",
"if",
"perm",
"in",
"_PERMISSION_HIERARCHY",
":",
"# check if we have a higher hierarchy position",
"ppos",
"=",
"_PERMISSION_HIERARCHY",
".",
"index",
"(",
"perm",
")",
"return",
"any",
"(",
"True",
"for",
"hpos",
",",
"hperm",
"in",
"enumerate",
"(",
"_PERMISSION_HIERARCHY",
")",
"if",
"hperm",
"in",
"perms",
"and",
"hpos",
">",
"ppos",
")",
"# we ignore pluralization (english only)",
"if",
"perm",
".",
"endswith",
"(",
"\"s\"",
")",
":",
"return",
"self",
".",
"check_permstring",
"(",
"perm",
"[",
":",
"-",
"1",
"]",
")",
"return",
"False"
] | [
546,
4
] | [
581,
20
] | python | en | ['en', 'error', 'th'] | False |
TypedObject._deleted | (self, *args, **kwargs) |
Scrambling method for already deleted objects
|
Scrambling method for already deleted objects
| def _deleted(self, *args, **kwargs):
"""
Scrambling method for already deleted objects
"""
raise ObjectDoesNotExist("This object was already deleted!") | [
"def",
"_deleted",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"ObjectDoesNotExist",
"(",
"\"This object was already deleted!\"",
")"
] | [
587,
4
] | [
591,
68
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.delete | (self) |
Cleaning up handlers on the typeclass level
|
Cleaning up handlers on the typeclass level | def delete(self):
"""
Cleaning up handlers on the typeclass level
"""
global TICKER_HANDLER
self.permissions.clear()
self.attributes.clear()
self.aliases.clear()
if hasattr(self, "nicks"):
self.nicks.clear()
# scrambling properties
self.delete = self._deleted
super(TypedObject, self).delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"global",
"TICKER_HANDLER",
"self",
".",
"permissions",
".",
"clear",
"(",
")",
"self",
".",
"attributes",
".",
"clear",
"(",
")",
"self",
".",
"aliases",
".",
"clear",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"\"nicks\"",
")",
":",
"self",
".",
"nicks",
".",
"clear",
"(",
")",
"# scrambling properties",
"self",
".",
"delete",
"=",
"self",
".",
"_deleted",
"super",
"(",
"TypedObject",
",",
"self",
")",
".",
"delete",
"(",
")"
] | [
593,
4
] | [
606,
41
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.__db_get | (self) |
Attribute handler wrapper. Allows for the syntax
obj.db.attrname = value
and
value = obj.db.attrname
and
del obj.db.attrname
and
all_attr = obj.db.all() (unless there is an attribute
named 'all', in which case that will be returned instead).
|
Attribute handler wrapper. Allows for the syntax
obj.db.attrname = value
and
value = obj.db.attrname
and
del obj.db.attrname
and
all_attr = obj.db.all() (unless there is an attribute
named 'all', in which case that will be returned instead).
| def __db_get(self):
"""
Attribute handler wrapper. Allows for the syntax
obj.db.attrname = value
and
value = obj.db.attrname
and
del obj.db.attrname
and
all_attr = obj.db.all() (unless there is an attribute
named 'all', in which case that will be returned instead).
"""
try:
return self._db_holder
except AttributeError:
self._db_holder = DbHolder(self, 'attributes')
return self._db_holder | [
"def",
"__db_get",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_db_holder",
"except",
"AttributeError",
":",
"self",
".",
"_db_holder",
"=",
"DbHolder",
"(",
"self",
",",
"'attributes'",
")",
"return",
"self",
".",
"_db_holder"
] | [
613,
4
] | [
629,
34
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.__db_set | (self, value) | Stop accidentally replacing the db object | Stop accidentally replacing the db object | def __db_set(self, value):
"Stop accidentally replacing the db object"
string = "Cannot assign directly to db object! "
string += "Use db.attr=value instead."
raise Exception(string) | [
"def",
"__db_set",
"(",
"self",
",",
"value",
")",
":",
"string",
"=",
"\"Cannot assign directly to db object! \"",
"string",
"+=",
"\"Use db.attr=value instead.\"",
"raise",
"Exception",
"(",
"string",
")"
] | [
632,
4
] | [
636,
31
] | python | en | ['en', 'en', 'en'] | True |
TypedObject.__db_del | (self) | Stop accidental deletion. | Stop accidental deletion. | def __db_del(self):
"Stop accidental deletion."
raise Exception("Cannot delete the db object!") | [
"def",
"__db_del",
"(",
"self",
")",
":",
"raise",
"Exception",
"(",
"\"Cannot delete the db object!\"",
")"
] | [
639,
4
] | [
641,
55
] | python | en | ['es', 'en', 'en'] | True |
TypedObject.__ndb_get | (self) |
A non-attr_obj store (ndb: NonDataBase). Everything stored
to this is guaranteed to be cleared when a server is shutdown.
Syntax is same as for the _get_db_holder() method and
property, e.g. obj.ndb.attr = value etc.
|
A non-attr_obj store (ndb: NonDataBase). Everything stored
to this is guaranteed to be cleared when a server is shutdown.
Syntax is same as for the _get_db_holder() method and
property, e.g. obj.ndb.attr = value etc.
| def __ndb_get(self):
"""
A non-attr_obj store (ndb: NonDataBase). Everything stored
to this is guaranteed to be cleared when a server is shutdown.
Syntax is same as for the _get_db_holder() method and
property, e.g. obj.ndb.attr = value etc.
"""
try:
return self._ndb_holder
except AttributeError:
self._ndb_holder = DbHolder(self, "nattrhandler", manager_name='nattributes')
return self._ndb_holder | [
"def",
"__ndb_get",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_ndb_holder",
"except",
"AttributeError",
":",
"self",
".",
"_ndb_holder",
"=",
"DbHolder",
"(",
"self",
",",
"\"nattrhandler\"",
",",
"manager_name",
"=",
"'nattributes'",
")",
"return",
"self",
".",
"_ndb_holder"
] | [
649,
4
] | [
660,
35
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.__ndb_set | (self, value) | Stop accidentally replacing the ndb object | Stop accidentally replacing the ndb object | def __ndb_set(self, value):
"Stop accidentally replacing the ndb object"
string = "Cannot assign directly to ndb object! "
string += "Use ndb.attr=value instead."
raise Exception(string) | [
"def",
"__ndb_set",
"(",
"self",
",",
"value",
")",
":",
"string",
"=",
"\"Cannot assign directly to ndb object! \"",
"string",
"+=",
"\"Use ndb.attr=value instead.\"",
"raise",
"Exception",
"(",
"string",
")"
] | [
663,
4
] | [
667,
31
] | python | en | ['en', 'en', 'en'] | True |
TypedObject.__ndb_del | (self) | Stop accidental deletion. | Stop accidental deletion. | def __ndb_del(self):
"Stop accidental deletion."
raise Exception("Cannot delete the ndb object!") | [
"def",
"__ndb_del",
"(",
"self",
")",
":",
"raise",
"Exception",
"(",
"\"Cannot delete the ndb object!\"",
")"
] | [
670,
4
] | [
672,
56
] | python | en | ['es', 'en', 'en'] | True |
TypedObject.get_display_name | (self, looker, **kwargs) |
Displays the name of the object in a viewer-aware manner.
Args:
looker (TypedObject, optional): The object or account that is looking
at/getting inforamtion for this object. If not given, some
'safe' minimum level should be returned.
Returns:
name (str): A string containing the name of the object,
including the DBREF if this user is privileged to control
said object.
Notes:
This function could be extended to change how object names
appear to users in character, but be wary. This function
does not change an object's keys or aliases when
searching, and is expected to produce something useful for
builders.
|
Displays the name of the object in a viewer-aware manner. | def get_display_name(self, looker, **kwargs):
"""
Displays the name of the object in a viewer-aware manner.
Args:
looker (TypedObject, optional): The object or account that is looking
at/getting inforamtion for this object. If not given, some
'safe' minimum level should be returned.
Returns:
name (str): A string containing the name of the object,
including the DBREF if this user is privileged to control
said object.
Notes:
This function could be extended to change how object names
appear to users in character, but be wary. This function
does not change an object's keys or aliases when
searching, and is expected to produce something useful for
builders.
"""
if self.access(looker, access_type='controls'):
return "{}(#{})".format(self.name, self.id)
return self.name | [
"def",
"get_display_name",
"(",
"self",
",",
"looker",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"access",
"(",
"looker",
",",
"access_type",
"=",
"'controls'",
")",
":",
"return",
"\"{}(#{})\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"id",
")",
"return",
"self",
".",
"name"
] | [
675,
4
] | [
699,
24
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.get_extra_info | (self, looker, **kwargs) |
Used when an object is in a list of ambiguous objects as an
additional information tag.
For instance, if you had potions which could have varying
levels of liquid left in them, you might want to display how
many drinks are left in each when selecting which to drop, but
not in your normal inventory listing.
Args:
looker (TypedObject): The object or account that is looking
at/getting information for this object.
Returns:
info (str): A string with disambiguating information,
conventionally with a leading space.
|
Used when an object is in a list of ambiguous objects as an
additional information tag. | def get_extra_info(self, looker, **kwargs):
"""
Used when an object is in a list of ambiguous objects as an
additional information tag.
For instance, if you had potions which could have varying
levels of liquid left in them, you might want to display how
many drinks are left in each when selecting which to drop, but
not in your normal inventory listing.
Args:
looker (TypedObject): The object or account that is looking
at/getting information for this object.
Returns:
info (str): A string with disambiguating information,
conventionally with a leading space.
"""
if self.location == looker:
return " (carried)"
return "" | [
"def",
"get_extra_info",
"(",
"self",
",",
"looker",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"location",
"==",
"looker",
":",
"return",
"\" (carried)\"",
"return",
"\"\""
] | [
701,
4
] | [
723,
17
] | python | en | ['en', 'error', 'th'] | False |
TypedObject.at_rename | (self, oldname, newname) |
This Hook is called by @name on a successful rename.
Args:
oldname (str): The instance's original name.
newname (str): The new name for the instance.
|
This Hook is called by @name on a successful rename. | def at_rename(self, oldname, newname):
"""
This Hook is called by @name on a successful rename.
Args:
oldname (str): The instance's original name.
newname (str): The new name for the instance.
"""
pass | [
"def",
"at_rename",
"(",
"self",
",",
"oldname",
",",
"newname",
")",
":",
"pass"
] | [
725,
4
] | [
734,
12
] | python | en | ['en', 'error', 'th'] | False |
dataHex | (data, prefix="") | Converts binary string data to display representation form | Converts binary string data to display representation form | def dataHex(data, prefix=""):
"""Converts binary string data to display representation form"""
res = ""
for i in range(0, (len(data)+15)/16):
res += "%s0x%02X | " % (prefix, i*16)
d = map(lambda x:ord(x), data[i*16:i*16+17])
for ch in d:
res += "%02X " % ch
for i in range(0,17-len(d)):
res += " "
res += "| "
for ch in d:
if (ch < 32) or (ch > 127):
res += ". "
else:
res += "%c " % ch
res += "\n"
return res | [
"def",
"dataHex",
"(",
"data",
",",
"prefix",
"=",
"\"\"",
")",
":",
"res",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"(",
"len",
"(",
"data",
")",
"+",
"15",
")",
"/",
"16",
")",
":",
"res",
"+=",
"\"%s0x%02X | \"",
"%",
"(",
"prefix",
",",
"i",
"*",
"16",
")",
"d",
"=",
"map",
"(",
"lambda",
"x",
":",
"ord",
"(",
"x",
")",
",",
"data",
"[",
"i",
"*",
"16",
":",
"i",
"*",
"16",
"+",
"17",
"]",
")",
"for",
"ch",
"in",
"d",
":",
"res",
"+=",
"\"%02X \"",
"%",
"ch",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"17",
"-",
"len",
"(",
"d",
")",
")",
":",
"res",
"+=",
"\" \"",
"res",
"+=",
"\"| \"",
"for",
"ch",
"in",
"d",
":",
"if",
"(",
"ch",
"<",
"32",
")",
"or",
"(",
"ch",
">",
"127",
")",
":",
"res",
"+=",
"\". \"",
"else",
":",
"res",
"+=",
"\"%c \"",
"%",
"ch",
"res",
"+=",
"\"\\n\"",
"return",
"res"
] | [
37,
0
] | [
54,
14
] | python | en | ['en', 'en', 'en'] | True |
logDnsMsg | (qstate) | Logs response | Logs response | def logDnsMsg(qstate):
"""Logs response"""
r = qstate.return_msg.rep
q = qstate.return_msg.qinfo
print "-"*100
print("Query: %s, type: %s (%d), class: %s (%d) " % (
qstate.qinfo.qname_str, qstate.qinfo.qtype_str, qstate.qinfo.qtype,
qstate.qinfo.qclass_str, qstate.qinfo.qclass))
print "-"*100
print "Return reply :: flags: %04X, QDcount: %d, Security:%d, TTL=%d" % (r.flags, r.qdcount, r.security, r.ttl)
print " qinfo :: qname: %s %s, qtype: %s, qclass: %s" % (str(q.qname_list), q.qname_str, q.qtype_str, q.qclass_str)
if (r):
print "Reply:"
for i in range(0, r.rrset_count):
rr = r.rrsets[i]
rk = rr.rk
print i,":",rk.dname_list, rk.dname_str, "flags: %04X" % rk.flags,
print "type:",rk.type_str,"(%d)" % ntohs(rk.type), "class:",rk.rrset_class_str,"(%d)" % ntohs(rk.rrset_class)
d = rr.entry.data
for j in range(0,d.count+d.rrsig_count):
print " ",j,":","TTL=",d.rr_ttl[j],
if (j >= d.count): print "rrsig",
print
print dataHex(d.rr_data[j]," ")
print "-"*100 | [
"def",
"logDnsMsg",
"(",
"qstate",
")",
":",
"r",
"=",
"qstate",
".",
"return_msg",
".",
"rep",
"q",
"=",
"qstate",
".",
"return_msg",
".",
"qinfo",
"print",
"\"-\"",
"*",
"100",
"print",
"(",
"\"Query: %s, type: %s (%d), class: %s (%d) \"",
"%",
"(",
"qstate",
".",
"qinfo",
".",
"qname_str",
",",
"qstate",
".",
"qinfo",
".",
"qtype_str",
",",
"qstate",
".",
"qinfo",
".",
"qtype",
",",
"qstate",
".",
"qinfo",
".",
"qclass_str",
",",
"qstate",
".",
"qinfo",
".",
"qclass",
")",
")",
"print",
"\"-\"",
"*",
"100",
"print",
"\"Return reply :: flags: %04X, QDcount: %d, Security:%d, TTL=%d\"",
"%",
"(",
"r",
".",
"flags",
",",
"r",
".",
"qdcount",
",",
"r",
".",
"security",
",",
"r",
".",
"ttl",
")",
"print",
"\" qinfo :: qname: %s %s, qtype: %s, qclass: %s\"",
"%",
"(",
"str",
"(",
"q",
".",
"qname_list",
")",
",",
"q",
".",
"qname_str",
",",
"q",
".",
"qtype_str",
",",
"q",
".",
"qclass_str",
")",
"if",
"(",
"r",
")",
":",
"print",
"\"Reply:\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"r",
".",
"rrset_count",
")",
":",
"rr",
"=",
"r",
".",
"rrsets",
"[",
"i",
"]",
"rk",
"=",
"rr",
".",
"rk",
"print",
"i",
",",
"\":\"",
",",
"rk",
".",
"dname_list",
",",
"rk",
".",
"dname_str",
",",
"\"flags: %04X\"",
"%",
"rk",
".",
"flags",
",",
"print",
"\"type:\"",
",",
"rk",
".",
"type_str",
",",
"\"(%d)\"",
"%",
"ntohs",
"(",
"rk",
".",
"type",
")",
",",
"\"class:\"",
",",
"rk",
".",
"rrset_class_str",
",",
"\"(%d)\"",
"%",
"ntohs",
"(",
"rk",
".",
"rrset_class",
")",
"d",
"=",
"rr",
".",
"entry",
".",
"data",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"d",
".",
"count",
"+",
"d",
".",
"rrsig_count",
")",
":",
"print",
"\" \"",
",",
"j",
",",
"\":\"",
",",
"\"TTL=\"",
",",
"d",
".",
"rr_ttl",
"[",
"j",
"]",
",",
"if",
"(",
"j",
">=",
"d",
".",
"count",
")",
":",
"print",
"\"rrsig\"",
",",
"print",
"print",
"dataHex",
"(",
"d",
".",
"rr_data",
"[",
"j",
"]",
",",
"\" \"",
")",
"print",
"\"-\"",
"*",
"100"
] | [
56,
0
] | [
86,
17
] | python | en | ['en', 'jv', 'en'] | False |
AgentMessage.__init__ | (self, _id: str = None, _decorators: BaseDecoratorSet = None) |
Initialize base agent message object.
Args:
_id: Agent message id
_decorators: Message decorators
Raises:
TypeError: If message type is missing on subclass Meta class
|
Initialize base agent message object. | def __init__(self, _id: str = None, _decorators: BaseDecoratorSet = None):
"""
Initialize base agent message object.
Args:
_id: Agent message id
_decorators: Message decorators
Raises:
TypeError: If message type is missing on subclass Meta class
"""
super(AgentMessage, self).__init__()
if _id:
self._message_id = _id
self._message_new_id = False
else:
self._message_id = str(uuid.uuid4())
self._message_new_id = True
self._message_decorators = (
_decorators if _decorators is not None else DecoratorSet()
)
if not self.Meta.message_type:
raise TypeError(
"Can't instantiate abstract class {} with no message_type".format(
self.__class__.__name__
)
) | [
"def",
"__init__",
"(",
"self",
",",
"_id",
":",
"str",
"=",
"None",
",",
"_decorators",
":",
"BaseDecoratorSet",
"=",
"None",
")",
":",
"super",
"(",
"AgentMessage",
",",
"self",
")",
".",
"__init__",
"(",
")",
"if",
"_id",
":",
"self",
".",
"_message_id",
"=",
"_id",
"self",
".",
"_message_new_id",
"=",
"False",
"else",
":",
"self",
".",
"_message_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"self",
".",
"_message_new_id",
"=",
"True",
"self",
".",
"_message_decorators",
"=",
"(",
"_decorators",
"if",
"_decorators",
"is",
"not",
"None",
"else",
"DecoratorSet",
"(",
")",
")",
"if",
"not",
"self",
".",
"Meta",
".",
"message_type",
":",
"raise",
"TypeError",
"(",
"\"Can't instantiate abstract class {} with no message_type\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")"
] | [
45,
4
] | [
72,
13
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage._get_handler_class | (cls) |
Get handler class.
Returns:
The resolved class defined on `Meta.handler_class`
|
Get handler class. | def _get_handler_class(cls):
"""
Get handler class.
Returns:
The resolved class defined on `Meta.handler_class`
"""
return resolve_class(cls.Meta.handler_class, cls) | [
"def",
"_get_handler_class",
"(",
"cls",
")",
":",
"return",
"resolve_class",
"(",
"cls",
".",
"Meta",
".",
"handler_class",
",",
"cls",
")"
] | [
80,
4
] | [
88,
57
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage.Handler | (self) |
Accessor for the agent message's handler class.
Returns:
Handler class
|
Accessor for the agent message's handler class. | def Handler(self) -> type:
"""
Accessor for the agent message's handler class.
Returns:
Handler class
"""
return self._get_handler_class() | [
"def",
"Handler",
"(",
"self",
")",
"->",
"type",
":",
"return",
"self",
".",
"_get_handler_class",
"(",
")"
] | [
91,
4
] | [
99,
40
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage._type | (self) |
Accessor for the message type identifier.
Returns:
Message type defined on `Meta.message_type`
|
Accessor for the message type identifier. | def _type(self) -> str:
"""
Accessor for the message type identifier.
Returns:
Message type defined on `Meta.message_type`
"""
return self.Meta.message_type | [
"def",
"_type",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"Meta",
".",
"message_type"
] | [
102,
4
] | [
110,
37
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage._id | (self) |
Accessor for the unique message identifier.
Returns:
The id of this message
|
Accessor for the unique message identifier. | def _id(self) -> str:
"""
Accessor for the unique message identifier.
Returns:
The id of this message
"""
return self._message_id | [
"def",
"_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_message_id"
] | [
113,
4
] | [
121,
31
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage._id | (self, val: str) | Set the unique message identifier. | Set the unique message identifier. | def _id(self, val: str):
"""Set the unique message identifier."""
self._message_id = val | [
"def",
"_id",
"(",
"self",
",",
"val",
":",
"str",
")",
":",
"self",
".",
"_message_id",
"=",
"val"
] | [
124,
4
] | [
126,
30
] | python | en | ['en', 'fr', 'en'] | True |
AgentMessage._decorators | (self) | Fetch the message's decorator set. | Fetch the message's decorator set. | def _decorators(self) -> BaseDecoratorSet:
"""Fetch the message's decorator set."""
return self._message_decorators | [
"def",
"_decorators",
"(",
"self",
")",
"->",
"BaseDecoratorSet",
":",
"return",
"self",
".",
"_message_decorators"
] | [
129,
4
] | [
131,
39
] | python | en | ['en', 'fr', 'en'] | True |
AgentMessage._decorators | (self, value: BaseDecoratorSet) | Fetch the message's decorator set. | Fetch the message's decorator set. | def _decorators(self, value: BaseDecoratorSet):
"""Fetch the message's decorator set."""
self._message_decorators = value | [
"def",
"_decorators",
"(",
"self",
",",
"value",
":",
"BaseDecoratorSet",
")",
":",
"self",
".",
"_message_decorators",
"=",
"value"
] | [
134,
4
] | [
136,
40
] | python | en | ['en', 'fr', 'en'] | True |
AgentMessage.get_signature | (self, field_name: str) |
Get the signature for a named field.
Args:
field_name: Field name to get the signature for
Returns:
A SignatureDecorator for the requested field name
|
Get the signature for a named field. | def get_signature(self, field_name: str) -> SignatureDecorator:
"""
Get the signature for a named field.
Args:
field_name: Field name to get the signature for
Returns:
A SignatureDecorator for the requested field name
"""
return self._decorators.field(field_name).get("sig") | [
"def",
"get_signature",
"(",
"self",
",",
"field_name",
":",
"str",
")",
"->",
"SignatureDecorator",
":",
"return",
"self",
".",
"_decorators",
".",
"field",
"(",
"field_name",
")",
".",
"get",
"(",
"\"sig\"",
")"
] | [
138,
4
] | [
149,
60
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage.set_signature | (self, field_name: str, signature: SignatureDecorator) |
Add or replace the signature for a named field.
Args:
field_name: Field to set signature on
signature: Signature for the field
|
Add or replace the signature for a named field. | def set_signature(self, field_name: str, signature: SignatureDecorator):
"""
Add or replace the signature for a named field.
Args:
field_name: Field to set signature on
signature: Signature for the field
"""
self._decorators.field(field_name)["sig"] = signature | [
"def",
"set_signature",
"(",
"self",
",",
"field_name",
":",
"str",
",",
"signature",
":",
"SignatureDecorator",
")",
":",
"self",
".",
"_decorators",
".",
"field",
"(",
"field_name",
")",
"[",
"\"sig\"",
"]",
"=",
"signature"
] | [
151,
4
] | [
160,
61
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage.sign_field | (
self, field_name: str, signer_verkey: str, wallet: BaseWallet, timestamp=None
) |
Create and store a signature for a named field.
Args:
field_name: Field to sign
signer_verkey: Verkey of signer
wallet: Wallet to use for signature
timestamp: Optional timestamp for signature
Returns:
A SignatureDecorator for newly created signature
Raises:
ValueError: If field_name doesn't exist on this message
|
Create and store a signature for a named field. | async def sign_field(
self, field_name: str, signer_verkey: str, wallet: BaseWallet, timestamp=None
) -> SignatureDecorator:
"""
Create and store a signature for a named field.
Args:
field_name: Field to sign
signer_verkey: Verkey of signer
wallet: Wallet to use for signature
timestamp: Optional timestamp for signature
Returns:
A SignatureDecorator for newly created signature
Raises:
ValueError: If field_name doesn't exist on this message
"""
value = getattr(self, field_name, None)
if value is None:
raise BaseModelError(
"{} field has no value for signature: {}".format(
self.__class__.__name__, field_name
)
)
sig = await SignatureDecorator.create(value, signer_verkey, wallet, timestamp)
self.set_signature(field_name, sig)
return sig | [
"async",
"def",
"sign_field",
"(",
"self",
",",
"field_name",
":",
"str",
",",
"signer_verkey",
":",
"str",
",",
"wallet",
":",
"BaseWallet",
",",
"timestamp",
"=",
"None",
")",
"->",
"SignatureDecorator",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"field_name",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"BaseModelError",
"(",
"\"{} field has no value for signature: {}\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"field_name",
")",
")",
"sig",
"=",
"await",
"SignatureDecorator",
".",
"create",
"(",
"value",
",",
"signer_verkey",
",",
"wallet",
",",
"timestamp",
")",
"self",
".",
"set_signature",
"(",
"field_name",
",",
"sig",
")",
"return",
"sig"
] | [
162,
4
] | [
190,
18
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage.verify_signed_field | (
self, field_name: str, wallet: BaseWallet, signer_verkey: str = None
) |
Verify a specific field signature.
Args:
field_name: The field name to verify
wallet: Wallet to use for the verification
signer_verkey: Verkey of signer to use
Returns:
The verkey of the signer
Raises:
ValueError: If field_name does not exist on this message
ValueError: If the verification fails
ValueError: If the verkey of the signature does not match the
provided verkey
|
Verify a specific field signature. | async def verify_signed_field(
self, field_name: str, wallet: BaseWallet, signer_verkey: str = None
) -> str:
"""
Verify a specific field signature.
Args:
field_name: The field name to verify
wallet: Wallet to use for the verification
signer_verkey: Verkey of signer to use
Returns:
The verkey of the signer
Raises:
ValueError: If field_name does not exist on this message
ValueError: If the verification fails
ValueError: If the verkey of the signature does not match the
provided verkey
"""
sig = self.get_signature(field_name)
if not sig:
raise BaseModelError("Missing field signature: {}".format(field_name))
if not await sig.verify(wallet):
raise BaseModelError(
"Field signature verification failed: {}".format(field_name)
)
if signer_verkey is not None and sig.signer != signer_verkey:
raise BaseModelError(
"Signer verkey of signature does not match: {}".format(field_name)
)
return sig.signer | [
"async",
"def",
"verify_signed_field",
"(",
"self",
",",
"field_name",
":",
"str",
",",
"wallet",
":",
"BaseWallet",
",",
"signer_verkey",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"sig",
"=",
"self",
".",
"get_signature",
"(",
"field_name",
")",
"if",
"not",
"sig",
":",
"raise",
"BaseModelError",
"(",
"\"Missing field signature: {}\"",
".",
"format",
"(",
"field_name",
")",
")",
"if",
"not",
"await",
"sig",
".",
"verify",
"(",
"wallet",
")",
":",
"raise",
"BaseModelError",
"(",
"\"Field signature verification failed: {}\"",
".",
"format",
"(",
"field_name",
")",
")",
"if",
"signer_verkey",
"is",
"not",
"None",
"and",
"sig",
".",
"signer",
"!=",
"signer_verkey",
":",
"raise",
"BaseModelError",
"(",
"\"Signer verkey of signature does not match: {}\"",
".",
"format",
"(",
"field_name",
")",
")",
"return",
"sig",
".",
"signer"
] | [
192,
4
] | [
224,
25
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage.verify_signatures | (self, wallet: BaseWallet) |
Verify all associated field signatures.
Args:
wallet: Wallet to use in verification
Returns:
True if all signatures verify, else false
|
Verify all associated field signatures. | async def verify_signatures(self, wallet: BaseWallet) -> bool:
"""
Verify all associated field signatures.
Args:
wallet: Wallet to use in verification
Returns:
True if all signatures verify, else false
"""
for field in self._decorators.fields.values():
if "sig" in field and not await field["sig"].verify(wallet):
return False
return True | [
"async",
"def",
"verify_signatures",
"(",
"self",
",",
"wallet",
":",
"BaseWallet",
")",
"->",
"bool",
":",
"for",
"field",
"in",
"self",
".",
"_decorators",
".",
"fields",
".",
"values",
"(",
")",
":",
"if",
"\"sig\"",
"in",
"field",
"and",
"not",
"await",
"field",
"[",
"\"sig\"",
"]",
".",
"verify",
"(",
"wallet",
")",
":",
"return",
"False",
"return",
"True"
] | [
226,
4
] | [
240,
19
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage._thread | (self) |
Accessor for the message's thread decorator.
Returns:
The ThreadDecorator for this message
|
Accessor for the message's thread decorator. | def _thread(self) -> ThreadDecorator:
"""
Accessor for the message's thread decorator.
Returns:
The ThreadDecorator for this message
"""
return self._decorators.get("thread") | [
"def",
"_thread",
"(",
"self",
")",
"->",
"ThreadDecorator",
":",
"return",
"self",
".",
"_decorators",
".",
"get",
"(",
"\"thread\"",
")"
] | [
243,
4
] | [
251,
45
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage._thread | (self, val: Union[ThreadDecorator, dict]) |
Setter for the message's thread decorator.
Args:
val: ThreadDecorator or dict to set as the thread
|
Setter for the message's thread decorator. | def _thread(self, val: Union[ThreadDecorator, dict]):
"""
Setter for the message's thread decorator.
Args:
val: ThreadDecorator or dict to set as the thread
"""
self._decorators["thread"] = val | [
"def",
"_thread",
"(",
"self",
",",
"val",
":",
"Union",
"[",
"ThreadDecorator",
",",
"dict",
"]",
")",
":",
"self",
".",
"_decorators",
"[",
"\"thread\"",
"]",
"=",
"val"
] | [
254,
4
] | [
261,
40
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage._thread_id | (self) | Accessor for the ID associated with this message. | Accessor for the ID associated with this message. | def _thread_id(self) -> str:
"""Accessor for the ID associated with this message."""
if self._thread and self._thread.thid:
return self._thread.thid
return self._message_id | [
"def",
"_thread_id",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_thread",
"and",
"self",
".",
"_thread",
".",
"thid",
":",
"return",
"self",
".",
"_thread",
".",
"thid",
"return",
"self",
".",
"_message_id"
] | [
264,
4
] | [
268,
31
] | python | en | ['en', 'en', 'en'] | True |
AgentMessage.assign_thread_from | (self, msg: "AgentMessage") |
Copy thread information from a previous message.
Args:
msg: The received message containing optional thread information
|
Copy thread information from a previous message. | def assign_thread_from(self, msg: "AgentMessage"):
"""
Copy thread information from a previous message.
Args:
msg: The received message containing optional thread information
"""
if msg:
thread = msg._thread
thid = thread and thread.thid or msg._message_id
pthid = thread and thread.pthid
self.assign_thread_id(thid, pthid) | [
"def",
"assign_thread_from",
"(",
"self",
",",
"msg",
":",
"\"AgentMessage\"",
")",
":",
"if",
"msg",
":",
"thread",
"=",
"msg",
".",
"_thread",
"thid",
"=",
"thread",
"and",
"thread",
".",
"thid",
"or",
"msg",
".",
"_message_id",
"pthid",
"=",
"thread",
"and",
"thread",
".",
"pthid",
"self",
".",
"assign_thread_id",
"(",
"thid",
",",
"pthid",
")"
] | [
270,
4
] | [
281,
46
] | python | en | ['en', 'error', 'th'] | False |
AgentMessage.assign_thread_id | (self, thid: str, pthid: str = None) |
Assign a specific thread ID.
Args:
thid: The thread identifier
pthid: The parent thread identifier
|
Assign a specific thread ID. | def assign_thread_id(self, thid: str, pthid: str = None):
"""
Assign a specific thread ID.
Args:
thid: The thread identifier
pthid: The parent thread identifier
"""
self._thread = ThreadDecorator(thid=thid, pthid=pthid) | [
"def",
"assign_thread_id",
"(",
"self",
",",
"thid",
":",
"str",
",",
"pthid",
":",
"str",
"=",
"None",
")",
":",
"self",
".",
"_thread",
"=",
"ThreadDecorator",
"(",
"thid",
"=",
"thid",
",",
"pthid",
"=",
"pthid",
")"
] | [
283,
4
] | [
291,
62
] | python | en | ['en', 'error', 'th'] | False |
AgentMessageSchema.__init__ | (self, *args, **kwargs) |
Initialize an instance of AgentMessageSchema.
Raises:
TypeError: If Meta.model_class has not been set
|
Initialize an instance of AgentMessageSchema. | def __init__(self, *args, **kwargs):
"""
Initialize an instance of AgentMessageSchema.
Raises:
TypeError: If Meta.model_class has not been set
"""
super(AgentMessageSchema, self).__init__(*args, **kwargs)
if not self.Meta.model_class:
raise TypeError(
"Can't instantiate abstract class {} with no model_class".format(
self.__class__.__name__
)
)
self._decorators = DecoratorSet()
self._decorators_dict = None
self._signatures = {} | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"AgentMessageSchema",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"self",
".",
"Meta",
".",
"model_class",
":",
"raise",
"TypeError",
"(",
"\"Can't instantiate abstract class {} with no model_class\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"self",
".",
"_decorators",
"=",
"DecoratorSet",
"(",
")",
"self",
".",
"_decorators_dict",
"=",
"None",
"self",
".",
"_signatures",
"=",
"{",
"}"
] | [
318,
4
] | [
335,
29
] | python | en | ['en', 'error', 'th'] | False |
AgentMessageSchema.extract_decorators | (self, data, **kwargs) |
Pre-load hook to extract the decorators and check the signed fields.
Args:
data: Incoming data to parse
Returns:
Parsed and modified data
Raises:
ValidationError: If a field signature does not correlate
to a field in the message
ValidationError: If the message defines both a field signature
and a value for the same field
ValidationError: If there is a missing field signature
|
Pre-load hook to extract the decorators and check the signed fields. | def extract_decorators(self, data, **kwargs):
"""
Pre-load hook to extract the decorators and check the signed fields.
Args:
data: Incoming data to parse
Returns:
Parsed and modified data
Raises:
ValidationError: If a field signature does not correlate
to a field in the message
ValidationError: If the message defines both a field signature
and a value for the same field
ValidationError: If there is a missing field signature
"""
processed = self._decorators.extract_decorators(data, self.__class__)
expect_fields = resolve_meta_property(self, "signed_fields") or ()
found_signatures = {}
for field_name, field in self._decorators.fields.items():
if "sig" in field:
if field_name not in expect_fields:
raise ValidationError(
f"Encountered unexpected field signature: {field_name}"
)
if field_name in processed:
raise ValidationError(
f"Message defines both field signature and value: {field_name}"
)
found_signatures[field_name] = field["sig"]
processed[field_name], _ = field["sig"].decode() # _ = timestamp
for field_name in expect_fields:
if field_name not in found_signatures:
raise ValidationError(f"Expected field signature: {field_name}")
return processed | [
"def",
"extract_decorators",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"processed",
"=",
"self",
".",
"_decorators",
".",
"extract_decorators",
"(",
"data",
",",
"self",
".",
"__class__",
")",
"expect_fields",
"=",
"resolve_meta_property",
"(",
"self",
",",
"\"signed_fields\"",
")",
"or",
"(",
")",
"found_signatures",
"=",
"{",
"}",
"for",
"field_name",
",",
"field",
"in",
"self",
".",
"_decorators",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"\"sig\"",
"in",
"field",
":",
"if",
"field_name",
"not",
"in",
"expect_fields",
":",
"raise",
"ValidationError",
"(",
"f\"Encountered unexpected field signature: {field_name}\"",
")",
"if",
"field_name",
"in",
"processed",
":",
"raise",
"ValidationError",
"(",
"f\"Message defines both field signature and value: {field_name}\"",
")",
"found_signatures",
"[",
"field_name",
"]",
"=",
"field",
"[",
"\"sig\"",
"]",
"processed",
"[",
"field_name",
"]",
",",
"_",
"=",
"field",
"[",
"\"sig\"",
"]",
".",
"decode",
"(",
")",
"# _ = timestamp",
"for",
"field_name",
"in",
"expect_fields",
":",
"if",
"field_name",
"not",
"in",
"found_signatures",
":",
"raise",
"ValidationError",
"(",
"f\"Expected field signature: {field_name}\"",
")",
"return",
"processed"
] | [
338,
4
] | [
375,
24
] | python | en | ['en', 'error', 'th'] | False |
AgentMessageSchema.populate_decorators | (self, obj, **kwargs) |
Post-load hook to populate decorators on the message.
Args:
obj: The AgentMessage object
Returns:
The AgentMessage object with populated decorators
|
Post-load hook to populate decorators on the message. | def populate_decorators(self, obj, **kwargs):
"""
Post-load hook to populate decorators on the message.
Args:
obj: The AgentMessage object
Returns:
The AgentMessage object with populated decorators
"""
obj._decorators = self._decorators
return obj | [
"def",
"populate_decorators",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
".",
"_decorators",
"=",
"self",
".",
"_decorators",
"return",
"obj"
] | [
378,
4
] | [
390,
18
] | python | en | ['en', 'error', 'th'] | False |
AgentMessageSchema.check_dump_decorators | (self, obj, **kwargs) |
Pre-dump hook to validate and load the message decorators.
Args:
obj: The AgentMessage object
Raises:
BaseModelError: If a decorator does not validate
|
Pre-dump hook to validate and load the message decorators. | def check_dump_decorators(self, obj, **kwargs):
"""
Pre-dump hook to validate and load the message decorators.
Args:
obj: The AgentMessage object
Raises:
BaseModelError: If a decorator does not validate
"""
decorators = obj._decorators.copy()
signatures = OrderedDict()
for name, field in decorators.fields.items():
if "sig" in field:
signatures[name] = field["sig"].serialize()
del field["sig"]
self._decorators_dict = decorators.to_dict()
self._signatures = signatures
# check existence of signatures
expect_fields = resolve_meta_property(self, "signed_fields") or ()
for field_name in expect_fields:
if field_name not in self._signatures:
raise BaseModelError(
"Missing signature for field: {}".format(field_name)
)
return obj | [
"def",
"check_dump_decorators",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"decorators",
"=",
"obj",
".",
"_decorators",
".",
"copy",
"(",
")",
"signatures",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
",",
"field",
"in",
"decorators",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"\"sig\"",
"in",
"field",
":",
"signatures",
"[",
"name",
"]",
"=",
"field",
"[",
"\"sig\"",
"]",
".",
"serialize",
"(",
")",
"del",
"field",
"[",
"\"sig\"",
"]",
"self",
".",
"_decorators_dict",
"=",
"decorators",
".",
"to_dict",
"(",
")",
"self",
".",
"_signatures",
"=",
"signatures",
"# check existence of signatures",
"expect_fields",
"=",
"resolve_meta_property",
"(",
"self",
",",
"\"signed_fields\"",
")",
"or",
"(",
")",
"for",
"field_name",
"in",
"expect_fields",
":",
"if",
"field_name",
"not",
"in",
"self",
".",
"_signatures",
":",
"raise",
"BaseModelError",
"(",
"\"Missing signature for field: {}\"",
".",
"format",
"(",
"field_name",
")",
")",
"return",
"obj"
] | [
393,
4
] | [
421,
18
] | python | en | ['en', 'error', 'th'] | False |
AgentMessageSchema.dump_decorators | (self, data, **kwargs) |
Post-dump hook to write the decorators to the serialized output.
Args:
obj: The serialized data
Returns:
The modified data
|
Post-dump hook to write the decorators to the serialized output. | def dump_decorators(self, data, **kwargs):
"""
Post-dump hook to write the decorators to the serialized output.
Args:
obj: The serialized data
Returns:
The modified data
"""
result = OrderedDict()
for key in ("@type", "@id"):
if key in data:
result[key] = data.pop(key)
result.update(self._decorators_dict)
result.update(data)
return result | [
"def",
"dump_decorators",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
"in",
"(",
"\"@type\"",
",",
"\"@id\"",
")",
":",
"if",
"key",
"in",
"data",
":",
"result",
"[",
"key",
"]",
"=",
"data",
".",
"pop",
"(",
"key",
")",
"result",
".",
"update",
"(",
"self",
".",
"_decorators_dict",
")",
"result",
".",
"update",
"(",
"data",
")",
"return",
"result"
] | [
424,
4
] | [
441,
21
] | python | en | ['en', 'error', 'th'] | False |
AgentMessageSchema.replace_signatures | (self, data, **kwargs) |
Post-dump hook to write the signatures to the serialized output.
Args:
obj: The serialized data
Returns:
The modified data
|
Post-dump hook to write the signatures to the serialized output. | def replace_signatures(self, data, **kwargs):
"""
Post-dump hook to write the signatures to the serialized output.
Args:
obj: The serialized data
Returns:
The modified data
"""
for field_name, sig in self._signatures.items():
del data[field_name]
data["{}~sig".format(field_name)] = sig
return data | [
"def",
"replace_signatures",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"field_name",
",",
"sig",
"in",
"self",
".",
"_signatures",
".",
"items",
"(",
")",
":",
"del",
"data",
"[",
"field_name",
"]",
"data",
"[",
"\"{}~sig\"",
".",
"format",
"(",
"field_name",
")",
"]",
"=",
"sig",
"return",
"data"
] | [
444,
4
] | [
458,
19
] | python | en | ['en', 'error', 'th'] | False |
BaseSettings.get_value | (self, *var_names, default=None) | Fetch a setting.
Args:
var_names: A list of variable name alternatives
default: The default value to return if none are defined
Returns:
The setting value, if defined, otherwise the default value
| Fetch a setting. | def get_value(self, *var_names, default=None):
"""Fetch a setting.
Args:
var_names: A list of variable name alternatives
default: The default value to return if none are defined
Returns:
The setting value, if defined, otherwise the default value
""" | [
"def",
"get_value",
"(",
"self",
",",
"*",
"var_names",
",",
"default",
"=",
"None",
")",
":"
] | [
20,
4
] | [
30,
11
] | python | en | ['en', 'cy', 'en'] | True |
BaseSettings.get_bool | (self, *var_names, default=None) | Fetch a setting as a boolean value.
Args:
var_names: A list of variable name alternatives
default: The default value to return if none are defined
| Fetch a setting as a boolean value. | def get_bool(self, *var_names, default=None) -> bool:
"""Fetch a setting as a boolean value.
Args:
var_names: A list of variable name alternatives
default: The default value to return if none are defined
"""
value = self.get_value(*var_names, default)
if value is not None:
value = bool(value and value not in ("false", "False", "0"))
return value | [
"def",
"get_bool",
"(",
"self",
",",
"*",
"var_names",
",",
"default",
"=",
"None",
")",
"->",
"bool",
":",
"value",
"=",
"self",
".",
"get_value",
"(",
"*",
"var_names",
",",
"default",
")",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"bool",
"(",
"value",
"and",
"value",
"not",
"in",
"(",
"\"false\"",
",",
"\"False\"",
",",
"\"0\"",
")",
")",
"return",
"value"
] | [
32,
4
] | [
42,
20
] | python | en | ['en', 'gd', 'en'] | True |
BaseSettings.get_int | (self, *var_names, default=None) | Fetch a setting as an integer value.
Args:
var_names: A list of variable name alternatives
default: The default value to return if none are defined
| Fetch a setting as an integer value. | def get_int(self, *var_names, default=None) -> int:
"""Fetch a setting as an integer value.
Args:
var_names: A list of variable name alternatives
default: The default value to return if none are defined
"""
value = self.get_value(*var_names, default)
if value is not None:
value = int(value)
return value | [
"def",
"get_int",
"(",
"self",
",",
"*",
"var_names",
",",
"default",
"=",
"None",
")",
"->",
"int",
":",
"value",
"=",
"self",
".",
"get_value",
"(",
"*",
"var_names",
",",
"default",
")",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"int",
"(",
"value",
")",
"return",
"value"
] | [
44,
4
] | [
54,
20
] | python | en | ['en', 'en', 'en'] | True |
BaseSettings.get_str | (self, *var_names, default=None) | Fetch a setting as a string value.
Args:
var_names: A list of variable name alternatives
default: The default value to return if none are defined
| Fetch a setting as a string value. | def get_str(self, *var_names, default=None) -> str:
"""Fetch a setting as a string value.
Args:
var_names: A list of variable name alternatives
default: The default value to return if none are defined
"""
value = self.get_value(*var_names, default=default)
if value is not None:
value = str(value)
return value | [
"def",
"get_str",
"(",
"self",
",",
"*",
"var_names",
",",
"default",
"=",
"None",
")",
"->",
"str",
":",
"value",
"=",
"self",
".",
"get_value",
"(",
"*",
"var_names",
",",
"default",
"=",
"default",
")",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"str",
"(",
"value",
")",
"return",
"value"
] | [
56,
4
] | [
66,
20
] | python | en | ['en', 'en', 'en'] | True |
BaseSettings.__iter__ | (self) | Iterate settings keys. | Iterate settings keys. | def __iter__(self):
"""Iterate settings keys.""" | [
"def",
"__iter__",
"(",
"self",
")",
":"
] | [
69,
4
] | [
70,
36
] | python | en | ['en', 'ms', 'en'] | True |
BaseSettings.__getitem__ | (self, index) | Fetch as an array index. | Fetch as an array index. | def __getitem__(self, index):
"""Fetch as an array index."""
if not isinstance(index, str):
raise TypeError("Index must be a string")
missing = object()
result = self.get_value(index, default=missing)
if result is missing:
raise KeyError("Undefined index: {}".format(index))
return self.get_value(index) | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"isinstance",
"(",
"index",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Index must be a string\"",
")",
"missing",
"=",
"object",
"(",
")",
"result",
"=",
"self",
".",
"get_value",
"(",
"index",
",",
"default",
"=",
"missing",
")",
"if",
"result",
"is",
"missing",
":",
"raise",
"KeyError",
"(",
"\"Undefined index: {}\"",
".",
"format",
"(",
"index",
")",
")",
"return",
"self",
".",
"get_value",
"(",
"index",
")"
] | [
72,
4
] | [
80,
36
] | python | en | ['en', 'hu', 'en'] | True |
BaseSettings.__len__ | (self) | Fetch the length of the mapping. | Fetch the length of the mapping. | def __len__(self):
"""Fetch the length of the mapping.""" | [
"def",
"__len__",
"(",
"self",
")",
":"
] | [
83,
4
] | [
84,
46
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.