repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequencelengths 20
707
| docstring
stringlengths 3
17.3k
| docstring_tokens
sequencelengths 3
222
| sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value | idx
int64 0
252k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
OpenTreeOfLife/peyotl | peyotl/nexson_syntax/__init__.py | _inplace_sort_by_id | def _inplace_sort_by_id(unsorted_list):
"""Takes a list of dicts each of which has an '@id' key,
sorts the elements in the list by the value of the @id key.
Assumes that @id is unique or the dicts have a meaningul < operator
"""
if not isinstance(unsorted_list, list):
return
sorted_list = [(i.get('@id'), i) for i in unsorted_list]
sorted_list.sort()
del unsorted_list[:]
unsorted_list.extend([i[1] for i in sorted_list]) | python | def _inplace_sort_by_id(unsorted_list):
"""Takes a list of dicts each of which has an '@id' key,
sorts the elements in the list by the value of the @id key.
Assumes that @id is unique or the dicts have a meaningul < operator
"""
if not isinstance(unsorted_list, list):
return
sorted_list = [(i.get('@id'), i) for i in unsorted_list]
sorted_list.sort()
del unsorted_list[:]
unsorted_list.extend([i[1] for i in sorted_list]) | [
"def",
"_inplace_sort_by_id",
"(",
"unsorted_list",
")",
":",
"if",
"not",
"isinstance",
"(",
"unsorted_list",
",",
"list",
")",
":",
"return",
"sorted_list",
"=",
"[",
"(",
"i",
".",
"get",
"(",
"'@id'",
")",
",",
"i",
")",
"for",
"i",
"in",
"unsorted_list",
"]",
"sorted_list",
".",
"sort",
"(",
")",
"del",
"unsorted_list",
"[",
":",
"]",
"unsorted_list",
".",
"extend",
"(",
"[",
"i",
"[",
"1",
"]",
"for",
"i",
"in",
"sorted_list",
"]",
")"
] | Takes a list of dicts each of which has an '@id' key,
sorts the elements in the list by the value of the @id key.
Assumes that @id is unique or the dicts have a meaningul < operator | [
"Takes",
"a",
"list",
"of",
"dicts",
"each",
"of",
"which",
"has",
"an"
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_syntax/__init__.py#L736-L746 | train | 500 |
OpenTreeOfLife/peyotl | peyotl/nexson_syntax/__init__.py | cull_nonmatching_trees | def cull_nonmatching_trees(nexson, tree_id, curr_version=None):
"""Modifies `nexson` and returns it in version 1.2.1
with any tree that does not match the ID removed.
Note that this does not search through the NexSON for
every node, edge, tree that was deleted. So the resulting
NexSON may have broken references !
"""
if curr_version is None:
curr_version = detect_nexson_version(nexson)
if not _is_by_id_hbf(curr_version):
nexson = convert_nexson_format(nexson, BY_ID_HONEY_BADGERFISH)
nexml_el = get_nexml_el(nexson)
tree_groups = nexml_el['treesById']
tree_groups_to_del = []
for tgi, tree_group in tree_groups.items():
tbi = tree_group['treeById']
if tree_id in tbi:
trees_to_del = [i for i in tbi.keys() if i != tree_id]
for tid in trees_to_del:
tree_group['^ot:treeElementOrder'].remove(tid)
del tbi[tid]
else:
tree_groups_to_del.append(tgi)
for tgid in tree_groups_to_del:
nexml_el['^ot:treesElementOrder'].remove(tgid)
del tree_groups[tgid]
return nexson | python | def cull_nonmatching_trees(nexson, tree_id, curr_version=None):
"""Modifies `nexson` and returns it in version 1.2.1
with any tree that does not match the ID removed.
Note that this does not search through the NexSON for
every node, edge, tree that was deleted. So the resulting
NexSON may have broken references !
"""
if curr_version is None:
curr_version = detect_nexson_version(nexson)
if not _is_by_id_hbf(curr_version):
nexson = convert_nexson_format(nexson, BY_ID_HONEY_BADGERFISH)
nexml_el = get_nexml_el(nexson)
tree_groups = nexml_el['treesById']
tree_groups_to_del = []
for tgi, tree_group in tree_groups.items():
tbi = tree_group['treeById']
if tree_id in tbi:
trees_to_del = [i for i in tbi.keys() if i != tree_id]
for tid in trees_to_del:
tree_group['^ot:treeElementOrder'].remove(tid)
del tbi[tid]
else:
tree_groups_to_del.append(tgi)
for tgid in tree_groups_to_del:
nexml_el['^ot:treesElementOrder'].remove(tgid)
del tree_groups[tgid]
return nexson | [
"def",
"cull_nonmatching_trees",
"(",
"nexson",
",",
"tree_id",
",",
"curr_version",
"=",
"None",
")",
":",
"if",
"curr_version",
"is",
"None",
":",
"curr_version",
"=",
"detect_nexson_version",
"(",
"nexson",
")",
"if",
"not",
"_is_by_id_hbf",
"(",
"curr_version",
")",
":",
"nexson",
"=",
"convert_nexson_format",
"(",
"nexson",
",",
"BY_ID_HONEY_BADGERFISH",
")",
"nexml_el",
"=",
"get_nexml_el",
"(",
"nexson",
")",
"tree_groups",
"=",
"nexml_el",
"[",
"'treesById'",
"]",
"tree_groups_to_del",
"=",
"[",
"]",
"for",
"tgi",
",",
"tree_group",
"in",
"tree_groups",
".",
"items",
"(",
")",
":",
"tbi",
"=",
"tree_group",
"[",
"'treeById'",
"]",
"if",
"tree_id",
"in",
"tbi",
":",
"trees_to_del",
"=",
"[",
"i",
"for",
"i",
"in",
"tbi",
".",
"keys",
"(",
")",
"if",
"i",
"!=",
"tree_id",
"]",
"for",
"tid",
"in",
"trees_to_del",
":",
"tree_group",
"[",
"'^ot:treeElementOrder'",
"]",
".",
"remove",
"(",
"tid",
")",
"del",
"tbi",
"[",
"tid",
"]",
"else",
":",
"tree_groups_to_del",
".",
"append",
"(",
"tgi",
")",
"for",
"tgid",
"in",
"tree_groups_to_del",
":",
"nexml_el",
"[",
"'^ot:treesElementOrder'",
"]",
".",
"remove",
"(",
"tgid",
")",
"del",
"tree_groups",
"[",
"tgid",
"]",
"return",
"nexson"
] | Modifies `nexson` and returns it in version 1.2.1
with any tree that does not match the ID removed.
Note that this does not search through the NexSON for
every node, edge, tree that was deleted. So the resulting
NexSON may have broken references ! | [
"Modifies",
"nexson",
"and",
"returns",
"it",
"in",
"version",
"1",
".",
"2",
".",
"1",
"with",
"any",
"tree",
"that",
"does",
"not",
"match",
"the",
"ID",
"removed",
"."
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_syntax/__init__.py#L1156-L1184 | train | 501 |
OpenTreeOfLife/peyotl | peyotl/nexson_syntax/__init__.py | PhyloSchema.phylesystem_api_url | def phylesystem_api_url(self, base_url, study_id):
"""Returns URL and param dict for a GET call to phylesystem_api
"""
p = self._phylesystem_api_params()
e = self._phylesystem_api_ext()
if self.content == 'study':
return '{d}/study/{i}{e}'.format(d=base_url, i=study_id, e=e), p
elif self.content == 'tree':
if self.content_id is None:
return '{d}/study/{i}/tree{e}'.format(d=base_url, i=study_id, e=e), p
return '{d}/study/{i}/tree/{t}{e}'.format(d=base_url, i=study_id, t=self.content_id, e=e), p
elif self.content == 'subtree':
assert self.content_id is not None
t, n = self.content_id
p['subtree_id'] = n
return '{d}/study/{i}/subtree/{t}{e}'.format(d=base_url, i=study_id, t=t, e=e), p
elif self.content == 'meta':
return '{d}/study/{i}/meta{e}'.format(d=base_url, i=study_id, e=e), p
elif self.content == 'otus':
if self.content_id is None:
return '{d}/study/{i}/otus{e}'.format(d=base_url, i=study_id, e=e), p
return '{d}/study/{i}/otus/{t}{e}'.format(d=base_url, i=study_id, t=self.content_id, e=e), p
elif self.content == 'otu':
if self.content_id is None:
return '{d}/study/{i}/otu{e}'.format(d=base_url, i=study_id, e=e), p
return '{d}/study/{i}/otu/{t}{e}'.format(d=base_url, i=study_id, t=self.content_id, e=e), p
elif self.content == 'otumap':
return '{d}/otumap/{i}{e}'.format(d=base_url, i=study_id, e=e), p
else:
assert False | python | def phylesystem_api_url(self, base_url, study_id):
"""Returns URL and param dict for a GET call to phylesystem_api
"""
p = self._phylesystem_api_params()
e = self._phylesystem_api_ext()
if self.content == 'study':
return '{d}/study/{i}{e}'.format(d=base_url, i=study_id, e=e), p
elif self.content == 'tree':
if self.content_id is None:
return '{d}/study/{i}/tree{e}'.format(d=base_url, i=study_id, e=e), p
return '{d}/study/{i}/tree/{t}{e}'.format(d=base_url, i=study_id, t=self.content_id, e=e), p
elif self.content == 'subtree':
assert self.content_id is not None
t, n = self.content_id
p['subtree_id'] = n
return '{d}/study/{i}/subtree/{t}{e}'.format(d=base_url, i=study_id, t=t, e=e), p
elif self.content == 'meta':
return '{d}/study/{i}/meta{e}'.format(d=base_url, i=study_id, e=e), p
elif self.content == 'otus':
if self.content_id is None:
return '{d}/study/{i}/otus{e}'.format(d=base_url, i=study_id, e=e), p
return '{d}/study/{i}/otus/{t}{e}'.format(d=base_url, i=study_id, t=self.content_id, e=e), p
elif self.content == 'otu':
if self.content_id is None:
return '{d}/study/{i}/otu{e}'.format(d=base_url, i=study_id, e=e), p
return '{d}/study/{i}/otu/{t}{e}'.format(d=base_url, i=study_id, t=self.content_id, e=e), p
elif self.content == 'otumap':
return '{d}/otumap/{i}{e}'.format(d=base_url, i=study_id, e=e), p
else:
assert False | [
"def",
"phylesystem_api_url",
"(",
"self",
",",
"base_url",
",",
"study_id",
")",
":",
"p",
"=",
"self",
".",
"_phylesystem_api_params",
"(",
")",
"e",
"=",
"self",
".",
"_phylesystem_api_ext",
"(",
")",
"if",
"self",
".",
"content",
"==",
"'study'",
":",
"return",
"'{d}/study/{i}{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"elif",
"self",
".",
"content",
"==",
"'tree'",
":",
"if",
"self",
".",
"content_id",
"is",
"None",
":",
"return",
"'{d}/study/{i}/tree{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"return",
"'{d}/study/{i}/tree/{t}{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"t",
"=",
"self",
".",
"content_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"elif",
"self",
".",
"content",
"==",
"'subtree'",
":",
"assert",
"self",
".",
"content_id",
"is",
"not",
"None",
"t",
",",
"n",
"=",
"self",
".",
"content_id",
"p",
"[",
"'subtree_id'",
"]",
"=",
"n",
"return",
"'{d}/study/{i}/subtree/{t}{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"t",
"=",
"t",
",",
"e",
"=",
"e",
")",
",",
"p",
"elif",
"self",
".",
"content",
"==",
"'meta'",
":",
"return",
"'{d}/study/{i}/meta{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"elif",
"self",
".",
"content",
"==",
"'otus'",
":",
"if",
"self",
".",
"content_id",
"is",
"None",
":",
"return",
"'{d}/study/{i}/otus{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"return",
"'{d}/study/{i}/otus/{t}{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"t",
"=",
"self",
".",
"content_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"elif",
"self",
".",
"content",
"==",
"'otu'",
":",
"if",
"self",
".",
"content_id",
"is",
"None",
":",
"return",
"'{d}/study/{i}/otu{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"return",
"'{d}/study/{i}/otu/{t}{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"t",
"=",
"self",
".",
"content_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"elif",
"self",
".",
"content",
"==",
"'otumap'",
":",
"return",
"'{d}/otumap/{i}{e}'",
".",
"format",
"(",
"d",
"=",
"base_url",
",",
"i",
"=",
"study_id",
",",
"e",
"=",
"e",
")",
",",
"p",
"else",
":",
"assert",
"False"
] | Returns URL and param dict for a GET call to phylesystem_api | [
"Returns",
"URL",
"and",
"param",
"dict",
"for",
"a",
"GET",
"call",
"to",
"phylesystem_api"
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_syntax/__init__.py#L400-L429 | train | 502 |
hsolbrig/pyjsg | pyjsg/jsglib/jsg_array.py | JSGArray._is_valid | def _is_valid(self, log: Optional[Logger] = None) -> bool:
""" Determine whether the current contents are valid """
return self._validate(self, log)[0] | python | def _is_valid(self, log: Optional[Logger] = None) -> bool:
""" Determine whether the current contents are valid """
return self._validate(self, log)[0] | [
"def",
"_is_valid",
"(",
"self",
",",
"log",
":",
"Optional",
"[",
"Logger",
"]",
"=",
"None",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_validate",
"(",
"self",
",",
"log",
")",
"[",
"0",
"]"
] | Determine whether the current contents are valid | [
"Determine",
"whether",
"the",
"current",
"contents",
"are",
"valid"
] | 9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7 | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/jsglib/jsg_array.py#L33-L35 | train | 503 |
hsolbrig/pyjsg | pyjsg/jsglib/jsg_array.py | JSGArray._validate | def _validate(self, val: list, log: Optional[Logger] = None) -> Tuple[bool, List[str]]:
""" Determine whether val is a valid instance of this array
:returns: Success indicator and error list """
errors = []
if not isinstance(val, list):
errors.append(f"{self._variable_name}: {repr(val)} is not an array")
else:
for i in range(0, len(val)):
v = val[i]
if not conforms(v, self._type, self._context.NAMESPACE):
errors.append(f"{self._variable_name} element {i}: {v} is not a {self._type.__name__}")
if len(val) < self._min:
errors.append(
f"{self._variable_name}: at least {self._min} value{'s' if self._min > 1 else ''} required - "
f"element has {len(val) if len(val) else 'none'}")
if self._max is not None and len(val) > self._max:
errors.append(
f"{self._variable_name}: no more than {self._max} values permitted - element has {len(val)}")
if log:
for error in errors:
log.log(error)
return not bool(errors), errors | python | def _validate(self, val: list, log: Optional[Logger] = None) -> Tuple[bool, List[str]]:
""" Determine whether val is a valid instance of this array
:returns: Success indicator and error list """
errors = []
if not isinstance(val, list):
errors.append(f"{self._variable_name}: {repr(val)} is not an array")
else:
for i in range(0, len(val)):
v = val[i]
if not conforms(v, self._type, self._context.NAMESPACE):
errors.append(f"{self._variable_name} element {i}: {v} is not a {self._type.__name__}")
if len(val) < self._min:
errors.append(
f"{self._variable_name}: at least {self._min} value{'s' if self._min > 1 else ''} required - "
f"element has {len(val) if len(val) else 'none'}")
if self._max is not None and len(val) > self._max:
errors.append(
f"{self._variable_name}: no more than {self._max} values permitted - element has {len(val)}")
if log:
for error in errors:
log.log(error)
return not bool(errors), errors | [
"def",
"_validate",
"(",
"self",
",",
"val",
":",
"list",
",",
"log",
":",
"Optional",
"[",
"Logger",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"bool",
",",
"List",
"[",
"str",
"]",
"]",
":",
"errors",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"errors",
".",
"append",
"(",
"f\"{self._variable_name}: {repr(val)} is not an array\"",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"val",
")",
")",
":",
"v",
"=",
"val",
"[",
"i",
"]",
"if",
"not",
"conforms",
"(",
"v",
",",
"self",
".",
"_type",
",",
"self",
".",
"_context",
".",
"NAMESPACE",
")",
":",
"errors",
".",
"append",
"(",
"f\"{self._variable_name} element {i}: {v} is not a {self._type.__name__}\"",
")",
"if",
"len",
"(",
"val",
")",
"<",
"self",
".",
"_min",
":",
"errors",
".",
"append",
"(",
"f\"{self._variable_name}: at least {self._min} value{'s' if self._min > 1 else ''} required - \"",
"f\"element has {len(val) if len(val) else 'none'}\"",
")",
"if",
"self",
".",
"_max",
"is",
"not",
"None",
"and",
"len",
"(",
"val",
")",
">",
"self",
".",
"_max",
":",
"errors",
".",
"append",
"(",
"f\"{self._variable_name}: no more than {self._max} values permitted - element has {len(val)}\"",
")",
"if",
"log",
":",
"for",
"error",
"in",
"errors",
":",
"log",
".",
"log",
"(",
"error",
")",
"return",
"not",
"bool",
"(",
"errors",
")",
",",
"errors"
] | Determine whether val is a valid instance of this array
:returns: Success indicator and error list | [
"Determine",
"whether",
"val",
"is",
"a",
"valid",
"instance",
"of",
"this",
"array"
] | 9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7 | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/jsglib/jsg_array.py#L37-L61 | train | 504 |
OpenTreeOfLife/peyotl | peyotl/nexson_proxy.py | tree_iter_nexson_proxy | def tree_iter_nexson_proxy(nexson_proxy):
"""Iterates over NexsonTreeProxy objects in order determined by the nexson blob"""
nexml_el = nexson_proxy._nexml_el
tg_order = nexml_el['^ot:treesElementOrder']
tgd = nexml_el['treesById']
for tg_id in tg_order:
tg = tgd[tg_id]
tree_order = tg['^ot:treeElementOrder']
tbid = tg['treeById']
otus = tg['@otus']
for k in tree_order:
v = tbid[k]
yield nexson_proxy._create_tree_proxy(tree_id=k, tree=v, otus=otus) | python | def tree_iter_nexson_proxy(nexson_proxy):
"""Iterates over NexsonTreeProxy objects in order determined by the nexson blob"""
nexml_el = nexson_proxy._nexml_el
tg_order = nexml_el['^ot:treesElementOrder']
tgd = nexml_el['treesById']
for tg_id in tg_order:
tg = tgd[tg_id]
tree_order = tg['^ot:treeElementOrder']
tbid = tg['treeById']
otus = tg['@otus']
for k in tree_order:
v = tbid[k]
yield nexson_proxy._create_tree_proxy(tree_id=k, tree=v, otus=otus) | [
"def",
"tree_iter_nexson_proxy",
"(",
"nexson_proxy",
")",
":",
"nexml_el",
"=",
"nexson_proxy",
".",
"_nexml_el",
"tg_order",
"=",
"nexml_el",
"[",
"'^ot:treesElementOrder'",
"]",
"tgd",
"=",
"nexml_el",
"[",
"'treesById'",
"]",
"for",
"tg_id",
"in",
"tg_order",
":",
"tg",
"=",
"tgd",
"[",
"tg_id",
"]",
"tree_order",
"=",
"tg",
"[",
"'^ot:treeElementOrder'",
"]",
"tbid",
"=",
"tg",
"[",
"'treeById'",
"]",
"otus",
"=",
"tg",
"[",
"'@otus'",
"]",
"for",
"k",
"in",
"tree_order",
":",
"v",
"=",
"tbid",
"[",
"k",
"]",
"yield",
"nexson_proxy",
".",
"_create_tree_proxy",
"(",
"tree_id",
"=",
"k",
",",
"tree",
"=",
"v",
",",
"otus",
"=",
"otus",
")"
] | Iterates over NexsonTreeProxy objects in order determined by the nexson blob | [
"Iterates",
"over",
"NexsonTreeProxy",
"objects",
"in",
"order",
"determined",
"by",
"the",
"nexson",
"blob"
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_proxy.py#L52-L64 | train | 505 |
flyte/apcaccess | apcaccess/__main__.py | main | def main():
"""Get status from APC NIS and print output on stdout."""
# No need to use "proper" names on such simple code.
# pylint: disable=invalid-name
p = argparse.ArgumentParser()
p.add_argument("--host", default="localhost")
p.add_argument("--port", type=int, default=3551)
p.add_argument("--strip-units", action="store_true", default=False)
args = p.parse_args()
status.print_status(
status.get(args.host, args.port),
strip_units=args.strip_units
) | python | def main():
"""Get status from APC NIS and print output on stdout."""
# No need to use "proper" names on such simple code.
# pylint: disable=invalid-name
p = argparse.ArgumentParser()
p.add_argument("--host", default="localhost")
p.add_argument("--port", type=int, default=3551)
p.add_argument("--strip-units", action="store_true", default=False)
args = p.parse_args()
status.print_status(
status.get(args.host, args.port),
strip_units=args.strip_units
) | [
"def",
"main",
"(",
")",
":",
"# No need to use \"proper\" names on such simple code.",
"# pylint: disable=invalid-name",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"p",
".",
"add_argument",
"(",
"\"--host\"",
",",
"default",
"=",
"\"localhost\"",
")",
"p",
".",
"add_argument",
"(",
"\"--port\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"3551",
")",
"p",
".",
"add_argument",
"(",
"\"--strip-units\"",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",
"False",
")",
"args",
"=",
"p",
".",
"parse_args",
"(",
")",
"status",
".",
"print_status",
"(",
"status",
".",
"get",
"(",
"args",
".",
"host",
",",
"args",
".",
"port",
")",
",",
"strip_units",
"=",
"args",
".",
"strip_units",
")"
] | Get status from APC NIS and print output on stdout. | [
"Get",
"status",
"from",
"APC",
"NIS",
"and",
"print",
"output",
"on",
"stdout",
"."
] | 0c8a5d5e4ba1c07110e411b4ffea4ddccef4829a | https://github.com/flyte/apcaccess/blob/0c8a5d5e4ba1c07110e411b4ffea4ddccef4829a/apcaccess/__main__.py#L12-L24 | train | 506 |
palantir/typedjsonrpc | typedjsonrpc/server.py | Server.wsgi_app | def wsgi_app(self, environ, start_response):
"""A basic WSGI app"""
@_LOCAL_MANAGER.middleware
def _wrapped_app(environ, start_response):
request = Request(environ)
setattr(_local, _CURRENT_REQUEST_KEY, request)
response = self._dispatch_request(request)
return response(environ, start_response)
return _wrapped_app(environ, start_response) | python | def wsgi_app(self, environ, start_response):
"""A basic WSGI app"""
@_LOCAL_MANAGER.middleware
def _wrapped_app(environ, start_response):
request = Request(environ)
setattr(_local, _CURRENT_REQUEST_KEY, request)
response = self._dispatch_request(request)
return response(environ, start_response)
return _wrapped_app(environ, start_response) | [
"def",
"wsgi_app",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"@",
"_LOCAL_MANAGER",
".",
"middleware",
"def",
"_wrapped_app",
"(",
"environ",
",",
"start_response",
")",
":",
"request",
"=",
"Request",
"(",
"environ",
")",
"setattr",
"(",
"_local",
",",
"_CURRENT_REQUEST_KEY",
",",
"request",
")",
"response",
"=",
"self",
".",
"_dispatch_request",
"(",
"request",
")",
"return",
"response",
"(",
"environ",
",",
"start_response",
")",
"return",
"_wrapped_app",
"(",
"environ",
",",
"start_response",
")"
] | A basic WSGI app | [
"A",
"basic",
"WSGI",
"app"
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/server.py#L101-L109 | train | 507 |
palantir/typedjsonrpc | typedjsonrpc/server.py | Server.run | def run(self, host, port, **options):
"""For debugging purposes, you can run this as a standalone server.
.. WARNING:: **Security vulnerability**
This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use
this in production, you should run :class:`Server` as a standard WSGI app with
`uWSGI <https://uwsgi-docs.readthedocs.org/en/latest/>`_ or another similar WSGI server.
.. versionadded:: 0.1.0
"""
self.registry.debug = True
debugged = DebuggedJsonRpcApplication(self, evalex=True)
run_simple(host, port, debugged, use_reloader=True, **options) | python | def run(self, host, port, **options):
"""For debugging purposes, you can run this as a standalone server.
.. WARNING:: **Security vulnerability**
This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use
this in production, you should run :class:`Server` as a standard WSGI app with
`uWSGI <https://uwsgi-docs.readthedocs.org/en/latest/>`_ or another similar WSGI server.
.. versionadded:: 0.1.0
"""
self.registry.debug = True
debugged = DebuggedJsonRpcApplication(self, evalex=True)
run_simple(host, port, debugged, use_reloader=True, **options) | [
"def",
"run",
"(",
"self",
",",
"host",
",",
"port",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"registry",
".",
"debug",
"=",
"True",
"debugged",
"=",
"DebuggedJsonRpcApplication",
"(",
"self",
",",
"evalex",
"=",
"True",
")",
"run_simple",
"(",
"host",
",",
"port",
",",
"debugged",
",",
"use_reloader",
"=",
"True",
",",
"*",
"*",
"options",
")"
] | For debugging purposes, you can run this as a standalone server.
.. WARNING:: **Security vulnerability**
This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use
this in production, you should run :class:`Server` as a standard WSGI app with
`uWSGI <https://uwsgi-docs.readthedocs.org/en/latest/>`_ or another similar WSGI server.
.. versionadded:: 0.1.0 | [
"For",
"debugging",
"purposes",
"you",
"can",
"run",
"this",
"as",
"a",
"standalone",
"server",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/server.py#L114-L127 | train | 508 |
palantir/typedjsonrpc | typedjsonrpc/server.py | Server._try_trigger_before_first_request_funcs | def _try_trigger_before_first_request_funcs(self): # pylint: disable=C0103
"""Runs each function from ``self.before_first_request_funcs`` once and only once."""
if self._after_first_request_handled:
return
else:
with self._before_first_request_lock:
if self._after_first_request_handled:
return
for func in self._before_first_request_funcs:
func()
self._after_first_request_handled = True | python | def _try_trigger_before_first_request_funcs(self): # pylint: disable=C0103
"""Runs each function from ``self.before_first_request_funcs`` once and only once."""
if self._after_first_request_handled:
return
else:
with self._before_first_request_lock:
if self._after_first_request_handled:
return
for func in self._before_first_request_funcs:
func()
self._after_first_request_handled = True | [
"def",
"_try_trigger_before_first_request_funcs",
"(",
"self",
")",
":",
"# pylint: disable=C0103",
"if",
"self",
".",
"_after_first_request_handled",
":",
"return",
"else",
":",
"with",
"self",
".",
"_before_first_request_lock",
":",
"if",
"self",
".",
"_after_first_request_handled",
":",
"return",
"for",
"func",
"in",
"self",
".",
"_before_first_request_funcs",
":",
"func",
"(",
")",
"self",
".",
"_after_first_request_handled",
"=",
"True"
] | Runs each function from ``self.before_first_request_funcs`` once and only once. | [
"Runs",
"each",
"function",
"from",
"self",
".",
"before_first_request_funcs",
"once",
"and",
"only",
"once",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/server.py#L129-L139 | train | 509 |
palantir/typedjsonrpc | typedjsonrpc/server.py | DebuggedJsonRpcApplication.debug_application | def debug_application(self, environ, start_response):
"""Run the application and preserve the traceback frames.
:param environ: The environment which is passed into the wsgi application
:type environ: dict[str, object]
:param start_response: The start_response function of the wsgi application
:type start_response: (str, list[(str, str)]) -> None
:rtype: generator[str]
.. versionadded:: 0.1.0
"""
adapter = self._debug_map.bind_to_environ(environ)
if adapter.test():
_, args = adapter.match()
return self.handle_debug(environ, start_response, args["traceback_id"])
else:
return super(DebuggedJsonRpcApplication, self).debug_application(environ,
start_response) | python | def debug_application(self, environ, start_response):
"""Run the application and preserve the traceback frames.
:param environ: The environment which is passed into the wsgi application
:type environ: dict[str, object]
:param start_response: The start_response function of the wsgi application
:type start_response: (str, list[(str, str)]) -> None
:rtype: generator[str]
.. versionadded:: 0.1.0
"""
adapter = self._debug_map.bind_to_environ(environ)
if adapter.test():
_, args = adapter.match()
return self.handle_debug(environ, start_response, args["traceback_id"])
else:
return super(DebuggedJsonRpcApplication, self).debug_application(environ,
start_response) | [
"def",
"debug_application",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"adapter",
"=",
"self",
".",
"_debug_map",
".",
"bind_to_environ",
"(",
"environ",
")",
"if",
"adapter",
".",
"test",
"(",
")",
":",
"_",
",",
"args",
"=",
"adapter",
".",
"match",
"(",
")",
"return",
"self",
".",
"handle_debug",
"(",
"environ",
",",
"start_response",
",",
"args",
"[",
"\"traceback_id\"",
"]",
")",
"else",
":",
"return",
"super",
"(",
"DebuggedJsonRpcApplication",
",",
"self",
")",
".",
"debug_application",
"(",
"environ",
",",
"start_response",
")"
] | Run the application and preserve the traceback frames.
:param environ: The environment which is passed into the wsgi application
:type environ: dict[str, object]
:param start_response: The start_response function of the wsgi application
:type start_response: (str, list[(str, str)]) -> None
:rtype: generator[str]
.. versionadded:: 0.1.0 | [
"Run",
"the",
"application",
"and",
"preserve",
"the",
"traceback",
"frames",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/server.py#L177-L194 | train | 510 |
palantir/typedjsonrpc | typedjsonrpc/server.py | DebuggedJsonRpcApplication.handle_debug | def handle_debug(self, environ, start_response, traceback_id):
"""Handles the debug endpoint for inspecting previous errors.
:param environ: The environment which is passed into the wsgi application
:type environ: dict[str, object]
:param start_response: The start_response function of the wsgi application
:type start_response: (str, list[(str, str)]) -> NoneType
:param traceback_id: The id of the traceback to inspect
:type traceback_id: int
.. versionadded:: 0.1.0
"""
if traceback_id not in self.app.registry.tracebacks:
abort(404)
self._copy_over_traceback(traceback_id)
traceback = self.tracebacks[traceback_id]
rendered = traceback.render_full(evalex=self.evalex, secret=self.secret)
response = Response(rendered.encode('utf-8', 'replace'),
headers=[('Content-Type', 'text/html; charset=utf-8'),
('X-XSS-Protection', '0')])
return response(environ, start_response) | python | def handle_debug(self, environ, start_response, traceback_id):
"""Handles the debug endpoint for inspecting previous errors.
:param environ: The environment which is passed into the wsgi application
:type environ: dict[str, object]
:param start_response: The start_response function of the wsgi application
:type start_response: (str, list[(str, str)]) -> NoneType
:param traceback_id: The id of the traceback to inspect
:type traceback_id: int
.. versionadded:: 0.1.0
"""
if traceback_id not in self.app.registry.tracebacks:
abort(404)
self._copy_over_traceback(traceback_id)
traceback = self.tracebacks[traceback_id]
rendered = traceback.render_full(evalex=self.evalex, secret=self.secret)
response = Response(rendered.encode('utf-8', 'replace'),
headers=[('Content-Type', 'text/html; charset=utf-8'),
('X-XSS-Protection', '0')])
return response(environ, start_response) | [
"def",
"handle_debug",
"(",
"self",
",",
"environ",
",",
"start_response",
",",
"traceback_id",
")",
":",
"if",
"traceback_id",
"not",
"in",
"self",
".",
"app",
".",
"registry",
".",
"tracebacks",
":",
"abort",
"(",
"404",
")",
"self",
".",
"_copy_over_traceback",
"(",
"traceback_id",
")",
"traceback",
"=",
"self",
".",
"tracebacks",
"[",
"traceback_id",
"]",
"rendered",
"=",
"traceback",
".",
"render_full",
"(",
"evalex",
"=",
"self",
".",
"evalex",
",",
"secret",
"=",
"self",
".",
"secret",
")",
"response",
"=",
"Response",
"(",
"rendered",
".",
"encode",
"(",
"'utf-8'",
",",
"'replace'",
")",
",",
"headers",
"=",
"[",
"(",
"'Content-Type'",
",",
"'text/html; charset=utf-8'",
")",
",",
"(",
"'X-XSS-Protection'",
",",
"'0'",
")",
"]",
")",
"return",
"response",
"(",
"environ",
",",
"start_response",
")"
] | Handles the debug endpoint for inspecting previous errors.
:param environ: The environment which is passed into the wsgi application
:type environ: dict[str, object]
:param start_response: The start_response function of the wsgi application
:type start_response: (str, list[(str, str)]) -> NoneType
:param traceback_id: The id of the traceback to inspect
:type traceback_id: int
.. versionadded:: 0.1.0 | [
"Handles",
"the",
"debug",
"endpoint",
"for",
"inspecting",
"previous",
"errors",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/server.py#L196-L216 | train | 511 |
inveniosoftware/invenio-communities | invenio_communities/ext.py | InvenioCommunities.register_signals | def register_signals(self, app):
"""Register the signals."""
before_record_index.connect(inject_provisional_community)
if app.config['COMMUNITIES_OAI_ENABLED']:
listen(Community, 'after_insert', create_oaipmh_set)
listen(Community, 'after_delete', destroy_oaipmh_set)
inclusion_request_created.connect(new_request) | python | def register_signals(self, app):
"""Register the signals."""
before_record_index.connect(inject_provisional_community)
if app.config['COMMUNITIES_OAI_ENABLED']:
listen(Community, 'after_insert', create_oaipmh_set)
listen(Community, 'after_delete', destroy_oaipmh_set)
inclusion_request_created.connect(new_request) | [
"def",
"register_signals",
"(",
"self",
",",
"app",
")",
":",
"before_record_index",
".",
"connect",
"(",
"inject_provisional_community",
")",
"if",
"app",
".",
"config",
"[",
"'COMMUNITIES_OAI_ENABLED'",
"]",
":",
"listen",
"(",
"Community",
",",
"'after_insert'",
",",
"create_oaipmh_set",
")",
"listen",
"(",
"Community",
",",
"'after_delete'",
",",
"destroy_oaipmh_set",
")",
"inclusion_request_created",
".",
"connect",
"(",
"new_request",
")"
] | Register the signals. | [
"Register",
"the",
"signals",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/ext.py#L59-L65 | train | 512 |
hsolbrig/pyjsg | pyjsg/validate_json.py | genargs | def genargs() -> ArgumentParser:
"""
Create a command line parser
:return: parser
"""
parser = ArgumentParser()
parser.add_argument("spec", help="JSG specification - can be file name, URI or string")
parser.add_argument("-o", "--outfile", help="Output python file - if omitted, python is not saved")
parser.add_argument("-p", "--print", help="Print python file to stdout")
parser.add_argument("-id", "--inputdir", help="Input directory with JSON files")
parser.add_argument("-i", "--json", help="URL, file name or json text", nargs='*')
return parser | python | def genargs() -> ArgumentParser:
"""
Create a command line parser
:return: parser
"""
parser = ArgumentParser()
parser.add_argument("spec", help="JSG specification - can be file name, URI or string")
parser.add_argument("-o", "--outfile", help="Output python file - if omitted, python is not saved")
parser.add_argument("-p", "--print", help="Print python file to stdout")
parser.add_argument("-id", "--inputdir", help="Input directory with JSON files")
parser.add_argument("-i", "--json", help="URL, file name or json text", nargs='*')
return parser | [
"def",
"genargs",
"(",
")",
"->",
"ArgumentParser",
":",
"parser",
"=",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"spec\"",
",",
"help",
"=",
"\"JSG specification - can be file name, URI or string\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-o\"",
",",
"\"--outfile\"",
",",
"help",
"=",
"\"Output python file - if omitted, python is not saved\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-p\"",
",",
"\"--print\"",
",",
"help",
"=",
"\"Print python file to stdout\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-id\"",
",",
"\"--inputdir\"",
",",
"help",
"=",
"\"Input directory with JSON files\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-i\"",
",",
"\"--json\"",
",",
"help",
"=",
"\"URL, file name or json text\"",
",",
"nargs",
"=",
"'*'",
")",
"return",
"parser"
] | Create a command line parser
:return: parser | [
"Create",
"a",
"command",
"line",
"parser"
] | 9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7 | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/validate_json.py#L88-L100 | train | 513 |
hsolbrig/pyjsg | pyjsg/validate_json.py | JSGPython._to_string | def _to_string(inp: str) -> str:
""" Convert a URL or file name to a string """
if '://' in inp:
req = requests.get(inp)
if not req.ok:
raise ValueError(f"Unable to read {inp}")
return req.text
else:
with open(inp) as infile:
return infile.read() | python | def _to_string(inp: str) -> str:
""" Convert a URL or file name to a string """
if '://' in inp:
req = requests.get(inp)
if not req.ok:
raise ValueError(f"Unable to read {inp}")
return req.text
else:
with open(inp) as infile:
return infile.read() | [
"def",
"_to_string",
"(",
"inp",
":",
"str",
")",
"->",
"str",
":",
"if",
"'://'",
"in",
"inp",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"inp",
")",
"if",
"not",
"req",
".",
"ok",
":",
"raise",
"ValueError",
"(",
"f\"Unable to read {inp}\"",
")",
"return",
"req",
".",
"text",
"else",
":",
"with",
"open",
"(",
"inp",
")",
"as",
"infile",
":",
"return",
"infile",
".",
"read",
"(",
")"
] | Convert a URL or file name to a string | [
"Convert",
"a",
"URL",
"or",
"file",
"name",
"to",
"a",
"string"
] | 9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7 | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/validate_json.py#L57-L66 | train | 514 |
hsolbrig/pyjsg | pyjsg/validate_json.py | JSGPython.conforms | def conforms(self, json: str, name: str = "", verbose: bool=False) -> ValidationResult:
""" Determine whether json conforms with the JSG specification
:param json: JSON string, URI to JSON or file name with JSON
:param name: Test name for ValidationResult -- printed in dx if present
:param verbose: True means print the response
:return: pass/fail + fail reason
"""
json = self._to_string(json) if not self.is_json(json) else json
try:
self.json_obj = loads(json, self.module)
except ValueError as v:
return ValidationResult(False, str(v), name, None)
logfile = StringIO()
logger = Logger(cast(TextIO, logfile)) # cast because of bug in ide
if not is_valid(self.json_obj, logger):
return ValidationResult(False, logfile.getvalue().strip('\n'), name, None)
return ValidationResult(True, "", name, type(self.json_obj).__name__) | python | def conforms(self, json: str, name: str = "", verbose: bool=False) -> ValidationResult:
""" Determine whether json conforms with the JSG specification
:param json: JSON string, URI to JSON or file name with JSON
:param name: Test name for ValidationResult -- printed in dx if present
:param verbose: True means print the response
:return: pass/fail + fail reason
"""
json = self._to_string(json) if not self.is_json(json) else json
try:
self.json_obj = loads(json, self.module)
except ValueError as v:
return ValidationResult(False, str(v), name, None)
logfile = StringIO()
logger = Logger(cast(TextIO, logfile)) # cast because of bug in ide
if not is_valid(self.json_obj, logger):
return ValidationResult(False, logfile.getvalue().strip('\n'), name, None)
return ValidationResult(True, "", name, type(self.json_obj).__name__) | [
"def",
"conforms",
"(",
"self",
",",
"json",
":",
"str",
",",
"name",
":",
"str",
"=",
"\"\"",
",",
"verbose",
":",
"bool",
"=",
"False",
")",
"->",
"ValidationResult",
":",
"json",
"=",
"self",
".",
"_to_string",
"(",
"json",
")",
"if",
"not",
"self",
".",
"is_json",
"(",
"json",
")",
"else",
"json",
"try",
":",
"self",
".",
"json_obj",
"=",
"loads",
"(",
"json",
",",
"self",
".",
"module",
")",
"except",
"ValueError",
"as",
"v",
":",
"return",
"ValidationResult",
"(",
"False",
",",
"str",
"(",
"v",
")",
",",
"name",
",",
"None",
")",
"logfile",
"=",
"StringIO",
"(",
")",
"logger",
"=",
"Logger",
"(",
"cast",
"(",
"TextIO",
",",
"logfile",
")",
")",
"# cast because of bug in ide",
"if",
"not",
"is_valid",
"(",
"self",
".",
"json_obj",
",",
"logger",
")",
":",
"return",
"ValidationResult",
"(",
"False",
",",
"logfile",
".",
"getvalue",
"(",
")",
".",
"strip",
"(",
"'\\n'",
")",
",",
"name",
",",
"None",
")",
"return",
"ValidationResult",
"(",
"True",
",",
"\"\"",
",",
"name",
",",
"type",
"(",
"self",
".",
"json_obj",
")",
".",
"__name__",
")"
] | Determine whether json conforms with the JSG specification
:param json: JSON string, URI to JSON or file name with JSON
:param name: Test name for ValidationResult -- printed in dx if present
:param verbose: True means print the response
:return: pass/fail + fail reason | [
"Determine",
"whether",
"json",
"conforms",
"with",
"the",
"JSG",
"specification"
] | 9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7 | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/validate_json.py#L68-L85 | train | 515 |
PSPC-SPAC-buyandsell/von_agent | von_agent/agent/issuer.py | Issuer._sync_revoc | async def _sync_revoc(self, rr_id: str, rr_size: int = None) -> None:
"""
Create revoc registry if need be for input revocation registry identifier;
open and cache tails file reader.
:param rr_id: revocation registry identifier
:param rr_size: if new revocation registry necessary, its size (default as per _create_rev_reg())
"""
LOGGER.debug('Issuer._sync_revoc >>> rr_id: %s, rr_size: %s', rr_id, rr_size)
(cd_id, tag) = rev_reg_id2cred_def_id__tag(rr_id)
try:
await self.get_cred_def(cd_id)
except AbsentCredDef:
LOGGER.debug(
'Issuer._sync_revoc: <!< tails tree %s may be for another ledger; no cred def found on %s',
self._dir_tails,
cd_id)
raise AbsentCredDef('Tails tree {} may be for another ledger; no cred def found on {}'.format(
self._dir_tails,
cd_id))
with REVO_CACHE.lock:
revo_cache_entry = REVO_CACHE.get(rr_id, None)
tails = None if revo_cache_entry is None else revo_cache_entry.tails
if tails is None: # it's a new revocation registry, or not yet set in cache
try:
tails = await Tails(self._dir_tails, cd_id, tag).open()
except AbsentTails:
await self._create_rev_reg(rr_id, rr_size) # it's a new revocation registry
tails = await Tails(self._dir_tails, cd_id, tag).open() # symlink should exist now
if revo_cache_entry is None:
REVO_CACHE[rr_id] = RevoCacheEntry(None, tails)
else:
REVO_CACHE[rr_id].tails = tails
LOGGER.debug('Issuer._sync_revoc <<<') | python | async def _sync_revoc(self, rr_id: str, rr_size: int = None) -> None:
"""
Create revoc registry if need be for input revocation registry identifier;
open and cache tails file reader.
:param rr_id: revocation registry identifier
:param rr_size: if new revocation registry necessary, its size (default as per _create_rev_reg())
"""
LOGGER.debug('Issuer._sync_revoc >>> rr_id: %s, rr_size: %s', rr_id, rr_size)
(cd_id, tag) = rev_reg_id2cred_def_id__tag(rr_id)
try:
await self.get_cred_def(cd_id)
except AbsentCredDef:
LOGGER.debug(
'Issuer._sync_revoc: <!< tails tree %s may be for another ledger; no cred def found on %s',
self._dir_tails,
cd_id)
raise AbsentCredDef('Tails tree {} may be for another ledger; no cred def found on {}'.format(
self._dir_tails,
cd_id))
with REVO_CACHE.lock:
revo_cache_entry = REVO_CACHE.get(rr_id, None)
tails = None if revo_cache_entry is None else revo_cache_entry.tails
if tails is None: # it's a new revocation registry, or not yet set in cache
try:
tails = await Tails(self._dir_tails, cd_id, tag).open()
except AbsentTails:
await self._create_rev_reg(rr_id, rr_size) # it's a new revocation registry
tails = await Tails(self._dir_tails, cd_id, tag).open() # symlink should exist now
if revo_cache_entry is None:
REVO_CACHE[rr_id] = RevoCacheEntry(None, tails)
else:
REVO_CACHE[rr_id].tails = tails
LOGGER.debug('Issuer._sync_revoc <<<') | [
"async",
"def",
"_sync_revoc",
"(",
"self",
",",
"rr_id",
":",
"str",
",",
"rr_size",
":",
"int",
"=",
"None",
")",
"->",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'Issuer._sync_revoc >>> rr_id: %s, rr_size: %s'",
",",
"rr_id",
",",
"rr_size",
")",
"(",
"cd_id",
",",
"tag",
")",
"=",
"rev_reg_id2cred_def_id__tag",
"(",
"rr_id",
")",
"try",
":",
"await",
"self",
".",
"get_cred_def",
"(",
"cd_id",
")",
"except",
"AbsentCredDef",
":",
"LOGGER",
".",
"debug",
"(",
"'Issuer._sync_revoc: <!< tails tree %s may be for another ledger; no cred def found on %s'",
",",
"self",
".",
"_dir_tails",
",",
"cd_id",
")",
"raise",
"AbsentCredDef",
"(",
"'Tails tree {} may be for another ledger; no cred def found on {}'",
".",
"format",
"(",
"self",
".",
"_dir_tails",
",",
"cd_id",
")",
")",
"with",
"REVO_CACHE",
".",
"lock",
":",
"revo_cache_entry",
"=",
"REVO_CACHE",
".",
"get",
"(",
"rr_id",
",",
"None",
")",
"tails",
"=",
"None",
"if",
"revo_cache_entry",
"is",
"None",
"else",
"revo_cache_entry",
".",
"tails",
"if",
"tails",
"is",
"None",
":",
"# it's a new revocation registry, or not yet set in cache",
"try",
":",
"tails",
"=",
"await",
"Tails",
"(",
"self",
".",
"_dir_tails",
",",
"cd_id",
",",
"tag",
")",
".",
"open",
"(",
")",
"except",
"AbsentTails",
":",
"await",
"self",
".",
"_create_rev_reg",
"(",
"rr_id",
",",
"rr_size",
")",
"# it's a new revocation registry",
"tails",
"=",
"await",
"Tails",
"(",
"self",
".",
"_dir_tails",
",",
"cd_id",
",",
"tag",
")",
".",
"open",
"(",
")",
"# symlink should exist now",
"if",
"revo_cache_entry",
"is",
"None",
":",
"REVO_CACHE",
"[",
"rr_id",
"]",
"=",
"RevoCacheEntry",
"(",
"None",
",",
"tails",
")",
"else",
":",
"REVO_CACHE",
"[",
"rr_id",
"]",
".",
"tails",
"=",
"tails",
"LOGGER",
".",
"debug",
"(",
"'Issuer._sync_revoc <<<'",
")"
] | Create revoc registry if need be for input revocation registry identifier;
open and cache tails file reader.
:param rr_id: revocation registry identifier
:param rr_size: if new revocation registry necessary, its size (default as per _create_rev_reg()) | [
"Create",
"revoc",
"registry",
"if",
"need",
"be",
"for",
"input",
"revocation",
"registry",
"identifier",
";",
"open",
"and",
"cache",
"tails",
"file",
"reader",
"."
] | 0b1c17cca3bd178b6e6974af84dbac1dfce5cf45 | https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/agent/issuer.py#L139-L178 | train | 516 |
CybOXProject/mixbox | mixbox/binding_utils.py | quote_xml | def quote_xml(text):
"""Format a value for display as an XML text node.
Returns:
Unicode string (str on Python 3, unicode on Python 2)
"""
text = _coerce_unicode(text)
# If it's a CDATA block, return the text as is.
if text.startswith(CDATA_START):
return text
# If it's not a CDATA block, escape the XML and return the character
# encoded string.
return saxutils.escape(text) | python | def quote_xml(text):
"""Format a value for display as an XML text node.
Returns:
Unicode string (str on Python 3, unicode on Python 2)
"""
text = _coerce_unicode(text)
# If it's a CDATA block, return the text as is.
if text.startswith(CDATA_START):
return text
# If it's not a CDATA block, escape the XML and return the character
# encoded string.
return saxutils.escape(text) | [
"def",
"quote_xml",
"(",
"text",
")",
":",
"text",
"=",
"_coerce_unicode",
"(",
"text",
")",
"# If it's a CDATA block, return the text as is.",
"if",
"text",
".",
"startswith",
"(",
"CDATA_START",
")",
":",
"return",
"text",
"# If it's not a CDATA block, escape the XML and return the character",
"# encoded string.",
"return",
"saxutils",
".",
"escape",
"(",
"text",
")"
] | Format a value for display as an XML text node.
Returns:
Unicode string (str on Python 3, unicode on Python 2) | [
"Format",
"a",
"value",
"for",
"display",
"as",
"an",
"XML",
"text",
"node",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/binding_utils.py#L299-L313 | train | 517 |
CybOXProject/mixbox | mixbox/namespaces.py | _NamespaceInfo.__construct_from_components | def __construct_from_components(self, ns_uri, prefix=None, schema_location=None):
"""Initialize this instance from a namespace URI, and optional
prefix and schema location URI."""
assert ns_uri # other fields are optional
self.uri = ns_uri
self.schema_location = schema_location or None
self.prefixes = OrderedSet()
if prefix:
self.prefixes.add(prefix)
self.preferred_prefix = prefix or None | python | def __construct_from_components(self, ns_uri, prefix=None, schema_location=None):
"""Initialize this instance from a namespace URI, and optional
prefix and schema location URI."""
assert ns_uri # other fields are optional
self.uri = ns_uri
self.schema_location = schema_location or None
self.prefixes = OrderedSet()
if prefix:
self.prefixes.add(prefix)
self.preferred_prefix = prefix or None | [
"def",
"__construct_from_components",
"(",
"self",
",",
"ns_uri",
",",
"prefix",
"=",
"None",
",",
"schema_location",
"=",
"None",
")",
":",
"assert",
"ns_uri",
"# other fields are optional",
"self",
".",
"uri",
"=",
"ns_uri",
"self",
".",
"schema_location",
"=",
"schema_location",
"or",
"None",
"self",
".",
"prefixes",
"=",
"OrderedSet",
"(",
")",
"if",
"prefix",
":",
"self",
".",
"prefixes",
".",
"add",
"(",
"prefix",
")",
"self",
".",
"preferred_prefix",
"=",
"prefix",
"or",
"None"
] | Initialize this instance from a namespace URI, and optional
prefix and schema location URI. | [
"Initialize",
"this",
"instance",
"from",
"a",
"namespace",
"URI",
"and",
"optional",
"prefix",
"and",
"schema",
"location",
"URI",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L145-L157 | train | 518 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.namespace_for_prefix | def namespace_for_prefix(self, prefix):
"""Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
"""
try:
ni = self.__lookup_prefix(prefix)
except PrefixNotFoundError:
return None
else:
return ni.uri | python | def namespace_for_prefix(self, prefix):
"""Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
"""
try:
ni = self.__lookup_prefix(prefix)
except PrefixNotFoundError:
return None
else:
return ni.uri | [
"def",
"namespace_for_prefix",
"(",
"self",
",",
"prefix",
")",
":",
"try",
":",
"ni",
"=",
"self",
".",
"__lookup_prefix",
"(",
"prefix",
")",
"except",
"PrefixNotFoundError",
":",
"return",
"None",
"else",
":",
"return",
"ni",
".",
"uri"
] | Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set. | [
"Get",
"the",
"namespace",
"the",
"given",
"prefix",
"maps",
"to",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L271-L286 | train | 519 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.set_preferred_prefix_for_namespace | def set_preferred_prefix_for_namespace(self, ns_uri, prefix, add_if_not_exist=False):
"""Sets the preferred prefix for ns_uri. If add_if_not_exist is True,
the prefix is added if it's not already registered. Otherwise,
setting an unknown prefix as preferred is an error. The default
is False. Setting to None always works, and indicates a preference
to use the namespace as a default. The given namespace must already
be in this set.
Args:
ns_uri (str): the namespace URI whose prefix is to be set
prefix (str): the preferred prefix to set
add_if_not_exist (bool): Whether to add the prefix if it is not
already set as a prefix of ``ns_uri``.
Raises:
NamespaceNotFoundError: If namespace ``ns_uri`` isn't in this set.
DuplicatePrefixError: If ``prefix`` already maps to a different
namespace.
"""
ni = self.__lookup_uri(ns_uri)
if not prefix:
ni.preferred_prefix = None
elif prefix in ni.prefixes:
ni.preferred_prefix = prefix
elif add_if_not_exist:
self.add_prefix(ns_uri, prefix, set_as_preferred=True)
else:
raise PrefixNotFoundError(prefix) | python | def set_preferred_prefix_for_namespace(self, ns_uri, prefix, add_if_not_exist=False):
"""Sets the preferred prefix for ns_uri. If add_if_not_exist is True,
the prefix is added if it's not already registered. Otherwise,
setting an unknown prefix as preferred is an error. The default
is False. Setting to None always works, and indicates a preference
to use the namespace as a default. The given namespace must already
be in this set.
Args:
ns_uri (str): the namespace URI whose prefix is to be set
prefix (str): the preferred prefix to set
add_if_not_exist (bool): Whether to add the prefix if it is not
already set as a prefix of ``ns_uri``.
Raises:
NamespaceNotFoundError: If namespace ``ns_uri`` isn't in this set.
DuplicatePrefixError: If ``prefix`` already maps to a different
namespace.
"""
ni = self.__lookup_uri(ns_uri)
if not prefix:
ni.preferred_prefix = None
elif prefix in ni.prefixes:
ni.preferred_prefix = prefix
elif add_if_not_exist:
self.add_prefix(ns_uri, prefix, set_as_preferred=True)
else:
raise PrefixNotFoundError(prefix) | [
"def",
"set_preferred_prefix_for_namespace",
"(",
"self",
",",
"ns_uri",
",",
"prefix",
",",
"add_if_not_exist",
"=",
"False",
")",
":",
"ni",
"=",
"self",
".",
"__lookup_uri",
"(",
"ns_uri",
")",
"if",
"not",
"prefix",
":",
"ni",
".",
"preferred_prefix",
"=",
"None",
"elif",
"prefix",
"in",
"ni",
".",
"prefixes",
":",
"ni",
".",
"preferred_prefix",
"=",
"prefix",
"elif",
"add_if_not_exist",
":",
"self",
".",
"add_prefix",
"(",
"ns_uri",
",",
"prefix",
",",
"set_as_preferred",
"=",
"True",
")",
"else",
":",
"raise",
"PrefixNotFoundError",
"(",
"prefix",
")"
] | Sets the preferred prefix for ns_uri. If add_if_not_exist is True,
the prefix is added if it's not already registered. Otherwise,
setting an unknown prefix as preferred is an error. The default
is False. Setting to None always works, and indicates a preference
to use the namespace as a default. The given namespace must already
be in this set.
Args:
ns_uri (str): the namespace URI whose prefix is to be set
prefix (str): the preferred prefix to set
add_if_not_exist (bool): Whether to add the prefix if it is not
already set as a prefix of ``ns_uri``.
Raises:
NamespaceNotFoundError: If namespace ``ns_uri`` isn't in this set.
DuplicatePrefixError: If ``prefix`` already maps to a different
namespace. | [
"Sets",
"the",
"preferred",
"prefix",
"for",
"ns_uri",
".",
"If",
"add_if_not_exist",
"is",
"True",
"the",
"prefix",
"is",
"added",
"if",
"it",
"s",
"not",
"already",
"registered",
".",
"Otherwise",
"setting",
"an",
"unknown",
"prefix",
"as",
"preferred",
"is",
"an",
"error",
".",
"The",
"default",
"is",
"False",
".",
"Setting",
"to",
"None",
"always",
"works",
"and",
"indicates",
"a",
"preference",
"to",
"use",
"the",
"namespace",
"as",
"a",
"default",
".",
"The",
"given",
"namespace",
"must",
"already",
"be",
"in",
"this",
"set",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L294-L322 | train | 520 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.__merge_schema_locations | def __merge_schema_locations(self, ni, incoming_schemaloc):
"""Merge incoming_schemaloc into the given `_NamespaceInfo`, ni. If we
don't have one yet and the incoming value is non-None, update ours
with theirs. This modifies ni.
"""
if ni.schema_location == incoming_schemaloc: # TODO (bworrell): empty strings?
return
elif not ni.schema_location:
ni.schema_location = incoming_schemaloc or None
elif not incoming_schemaloc:
return
else:
raise ConflictingSchemaLocationError(ni.uri, ni.schema_location, incoming_schemaloc) | python | def __merge_schema_locations(self, ni, incoming_schemaloc):
"""Merge incoming_schemaloc into the given `_NamespaceInfo`, ni. If we
don't have one yet and the incoming value is non-None, update ours
with theirs. This modifies ni.
"""
if ni.schema_location == incoming_schemaloc: # TODO (bworrell): empty strings?
return
elif not ni.schema_location:
ni.schema_location = incoming_schemaloc or None
elif not incoming_schemaloc:
return
else:
raise ConflictingSchemaLocationError(ni.uri, ni.schema_location, incoming_schemaloc) | [
"def",
"__merge_schema_locations",
"(",
"self",
",",
"ni",
",",
"incoming_schemaloc",
")",
":",
"if",
"ni",
".",
"schema_location",
"==",
"incoming_schemaloc",
":",
"# TODO (bworrell): empty strings?",
"return",
"elif",
"not",
"ni",
".",
"schema_location",
":",
"ni",
".",
"schema_location",
"=",
"incoming_schemaloc",
"or",
"None",
"elif",
"not",
"incoming_schemaloc",
":",
"return",
"else",
":",
"raise",
"ConflictingSchemaLocationError",
"(",
"ni",
".",
"uri",
",",
"ni",
".",
"schema_location",
",",
"incoming_schemaloc",
")"
] | Merge incoming_schemaloc into the given `_NamespaceInfo`, ni. If we
don't have one yet and the incoming value is non-None, update ours
with theirs. This modifies ni. | [
"Merge",
"incoming_schemaloc",
"into",
"the",
"given",
"_NamespaceInfo",
"ni",
".",
"If",
"we",
"don",
"t",
"have",
"one",
"yet",
"and",
"the",
"incoming",
"value",
"is",
"non",
"-",
"None",
"update",
"ours",
"with",
"theirs",
".",
"This",
"modifies",
"ni",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L324-L336 | train | 521 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.add_namespace_uri | def add_namespace_uri(self, ns_uri, prefix=None, schema_location=None):
"""Adds a new namespace to this set, optionally with a prefix and
schema location URI.
If the namespace already exists, the given prefix and schema location
are merged with the existing entry:
* If non-None, ``prefix`` is added to the set. The preferred
prefix is not modified.
* If a schema location is not already associated with the
namespace, it is set to ``schema_location`` (if given).
If the namespace doesn't already exist in this set (so a new one is
being created) and a prefix is given, that prefix becomes preferred.
If not given, a preference as a default namespace is used.
Args:
ns_uri (str): The URI of the new namespace
prefix (str): The desired prefix for the new namespace (optional)
schema_location (str): The desired schema location for the new
namespace (optional).
Raises:
DuplicatePrefixError: If a prefix is given which already maps to a
different namespace
ConflictingSchemaLocationError: If a schema location is given and
the namespace already exists in this set with a different
schema location.
"""
assert ns_uri
if ns_uri in self.__ns_uri_map:
# We have a _NamespaceInfo object for this URI already. So this
# is a merge operation.
#
# We modify a copy of the real _NamespaceInfo so that we are
# exception-safe: if something goes wrong, we don't end up with a
# half-changed NamespaceSet.
ni = self.__lookup_uri(ns_uri)
new_ni = copy.deepcopy(ni)
# Reconcile prefixes
if prefix:
self.__check_prefix_conflict(ni, prefix)
new_ni.prefixes.add(prefix)
self.__merge_schema_locations(new_ni, schema_location)
# At this point, we have a legit new_ni object. Now we update
# the set, ensuring our invariants. This should replace
# all instances of the old ni in this set.
for p in new_ni.prefixes:
self.__prefix_map[p] = new_ni
self.__ns_uri_map[new_ni.uri] = new_ni
else:
# A brand new namespace. The incoming prefix should not exist at
# all in the prefix map.
if prefix:
self.__check_prefix_conflict(ns_uri, prefix)
ni = _NamespaceInfo(ns_uri, prefix, schema_location)
self.__add_namespaceinfo(ni) | python | def add_namespace_uri(self, ns_uri, prefix=None, schema_location=None):
"""Adds a new namespace to this set, optionally with a prefix and
schema location URI.
If the namespace already exists, the given prefix and schema location
are merged with the existing entry:
* If non-None, ``prefix`` is added to the set. The preferred
prefix is not modified.
* If a schema location is not already associated with the
namespace, it is set to ``schema_location`` (if given).
If the namespace doesn't already exist in this set (so a new one is
being created) and a prefix is given, that prefix becomes preferred.
If not given, a preference as a default namespace is used.
Args:
ns_uri (str): The URI of the new namespace
prefix (str): The desired prefix for the new namespace (optional)
schema_location (str): The desired schema location for the new
namespace (optional).
Raises:
DuplicatePrefixError: If a prefix is given which already maps to a
different namespace
ConflictingSchemaLocationError: If a schema location is given and
the namespace already exists in this set with a different
schema location.
"""
assert ns_uri
if ns_uri in self.__ns_uri_map:
# We have a _NamespaceInfo object for this URI already. So this
# is a merge operation.
#
# We modify a copy of the real _NamespaceInfo so that we are
# exception-safe: if something goes wrong, we don't end up with a
# half-changed NamespaceSet.
ni = self.__lookup_uri(ns_uri)
new_ni = copy.deepcopy(ni)
# Reconcile prefixes
if prefix:
self.__check_prefix_conflict(ni, prefix)
new_ni.prefixes.add(prefix)
self.__merge_schema_locations(new_ni, schema_location)
# At this point, we have a legit new_ni object. Now we update
# the set, ensuring our invariants. This should replace
# all instances of the old ni in this set.
for p in new_ni.prefixes:
self.__prefix_map[p] = new_ni
self.__ns_uri_map[new_ni.uri] = new_ni
else:
# A brand new namespace. The incoming prefix should not exist at
# all in the prefix map.
if prefix:
self.__check_prefix_conflict(ns_uri, prefix)
ni = _NamespaceInfo(ns_uri, prefix, schema_location)
self.__add_namespaceinfo(ni) | [
"def",
"add_namespace_uri",
"(",
"self",
",",
"ns_uri",
",",
"prefix",
"=",
"None",
",",
"schema_location",
"=",
"None",
")",
":",
"assert",
"ns_uri",
"if",
"ns_uri",
"in",
"self",
".",
"__ns_uri_map",
":",
"# We have a _NamespaceInfo object for this URI already. So this",
"# is a merge operation.",
"#",
"# We modify a copy of the real _NamespaceInfo so that we are",
"# exception-safe: if something goes wrong, we don't end up with a",
"# half-changed NamespaceSet.",
"ni",
"=",
"self",
".",
"__lookup_uri",
"(",
"ns_uri",
")",
"new_ni",
"=",
"copy",
".",
"deepcopy",
"(",
"ni",
")",
"# Reconcile prefixes",
"if",
"prefix",
":",
"self",
".",
"__check_prefix_conflict",
"(",
"ni",
",",
"prefix",
")",
"new_ni",
".",
"prefixes",
".",
"add",
"(",
"prefix",
")",
"self",
".",
"__merge_schema_locations",
"(",
"new_ni",
",",
"schema_location",
")",
"# At this point, we have a legit new_ni object. Now we update",
"# the set, ensuring our invariants. This should replace",
"# all instances of the old ni in this set.",
"for",
"p",
"in",
"new_ni",
".",
"prefixes",
":",
"self",
".",
"__prefix_map",
"[",
"p",
"]",
"=",
"new_ni",
"self",
".",
"__ns_uri_map",
"[",
"new_ni",
".",
"uri",
"]",
"=",
"new_ni",
"else",
":",
"# A brand new namespace. The incoming prefix should not exist at",
"# all in the prefix map.",
"if",
"prefix",
":",
"self",
".",
"__check_prefix_conflict",
"(",
"ns_uri",
",",
"prefix",
")",
"ni",
"=",
"_NamespaceInfo",
"(",
"ns_uri",
",",
"prefix",
",",
"schema_location",
")",
"self",
".",
"__add_namespaceinfo",
"(",
"ni",
")"
] | Adds a new namespace to this set, optionally with a prefix and
schema location URI.
If the namespace already exists, the given prefix and schema location
are merged with the existing entry:
* If non-None, ``prefix`` is added to the set. The preferred
prefix is not modified.
* If a schema location is not already associated with the
namespace, it is set to ``schema_location`` (if given).
If the namespace doesn't already exist in this set (so a new one is
being created) and a prefix is given, that prefix becomes preferred.
If not given, a preference as a default namespace is used.
Args:
ns_uri (str): The URI of the new namespace
prefix (str): The desired prefix for the new namespace (optional)
schema_location (str): The desired schema location for the new
namespace (optional).
Raises:
DuplicatePrefixError: If a prefix is given which already maps to a
different namespace
ConflictingSchemaLocationError: If a schema location is given and
the namespace already exists in this set with a different
schema location. | [
"Adds",
"a",
"new",
"namespace",
"to",
"this",
"set",
"optionally",
"with",
"a",
"prefix",
"and",
"schema",
"location",
"URI",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L344-L405 | train | 522 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.remove_namespace | def remove_namespace(self, ns_uri):
"""Removes the indicated namespace from this set."""
if not self.contains_namespace(ns_uri):
return
ni = self.__ns_uri_map.pop(ns_uri)
for prefix in ni.prefixes:
del self.__prefix_map[prefix] | python | def remove_namespace(self, ns_uri):
"""Removes the indicated namespace from this set."""
if not self.contains_namespace(ns_uri):
return
ni = self.__ns_uri_map.pop(ns_uri)
for prefix in ni.prefixes:
del self.__prefix_map[prefix] | [
"def",
"remove_namespace",
"(",
"self",
",",
"ns_uri",
")",
":",
"if",
"not",
"self",
".",
"contains_namespace",
"(",
"ns_uri",
")",
":",
"return",
"ni",
"=",
"self",
".",
"__ns_uri_map",
".",
"pop",
"(",
"ns_uri",
")",
"for",
"prefix",
"in",
"ni",
".",
"prefixes",
":",
"del",
"self",
".",
"__prefix_map",
"[",
"prefix",
"]"
] | Removes the indicated namespace from this set. | [
"Removes",
"the",
"indicated",
"namespace",
"from",
"this",
"set",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L407-L414 | train | 523 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.add_prefix | def add_prefix(self, ns_uri, prefix, set_as_preferred=False):
"""Adds prefix for the given namespace URI. The namespace must already
exist in this set. If set_as_preferred is True, also set this
namespace as the preferred one.
``prefix`` must be non-None; a default preference can't be set this way.
See :meth:`set_preferred_prefix_for_namespace` for that.
Args:
ns_uri (str): The namespace URI to add the prefix to
prefix (str): The prefix to add (not None)
set_as_preferred (bool): Whether to set the new prefix as preferred
Raises:
NamespaceNotFoundError: If namespace ``ns_uri`` isn't in this set
"""
assert prefix
ni = self.__lookup_uri(ns_uri)
self.__check_prefix_conflict(ni, prefix)
ni.prefixes.add(prefix)
self.__prefix_map[prefix] = ni
if set_as_preferred:
ni.preferred_prefix = prefix | python | def add_prefix(self, ns_uri, prefix, set_as_preferred=False):
"""Adds prefix for the given namespace URI. The namespace must already
exist in this set. If set_as_preferred is True, also set this
namespace as the preferred one.
``prefix`` must be non-None; a default preference can't be set this way.
See :meth:`set_preferred_prefix_for_namespace` for that.
Args:
ns_uri (str): The namespace URI to add the prefix to
prefix (str): The prefix to add (not None)
set_as_preferred (bool): Whether to set the new prefix as preferred
Raises:
NamespaceNotFoundError: If namespace ``ns_uri`` isn't in this set
"""
assert prefix
ni = self.__lookup_uri(ns_uri)
self.__check_prefix_conflict(ni, prefix)
ni.prefixes.add(prefix)
self.__prefix_map[prefix] = ni
if set_as_preferred:
ni.preferred_prefix = prefix | [
"def",
"add_prefix",
"(",
"self",
",",
"ns_uri",
",",
"prefix",
",",
"set_as_preferred",
"=",
"False",
")",
":",
"assert",
"prefix",
"ni",
"=",
"self",
".",
"__lookup_uri",
"(",
"ns_uri",
")",
"self",
".",
"__check_prefix_conflict",
"(",
"ni",
",",
"prefix",
")",
"ni",
".",
"prefixes",
".",
"add",
"(",
"prefix",
")",
"self",
".",
"__prefix_map",
"[",
"prefix",
"]",
"=",
"ni",
"if",
"set_as_preferred",
":",
"ni",
".",
"preferred_prefix",
"=",
"prefix"
] | Adds prefix for the given namespace URI. The namespace must already
exist in this set. If set_as_preferred is True, also set this
namespace as the preferred one.
``prefix`` must be non-None; a default preference can't be set this way.
See :meth:`set_preferred_prefix_for_namespace` for that.
Args:
ns_uri (str): The namespace URI to add the prefix to
prefix (str): The prefix to add (not None)
set_as_preferred (bool): Whether to set the new prefix as preferred
Raises:
NamespaceNotFoundError: If namespace ``ns_uri`` isn't in this set | [
"Adds",
"prefix",
"for",
"the",
"given",
"namespace",
"URI",
".",
"The",
"namespace",
"must",
"already",
"exist",
"in",
"this",
"set",
".",
"If",
"set_as_preferred",
"is",
"True",
"also",
"set",
"this",
"namespace",
"as",
"the",
"preferred",
"one",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L416-L441 | train | 524 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.prefix_iter | def prefix_iter(self, ns_uri):
"""Gets an iterator over the prefixes for the given namespace."""
ni = self.__lookup_uri(ns_uri)
return iter(ni.prefixes) | python | def prefix_iter(self, ns_uri):
"""Gets an iterator over the prefixes for the given namespace."""
ni = self.__lookup_uri(ns_uri)
return iter(ni.prefixes) | [
"def",
"prefix_iter",
"(",
"self",
",",
"ns_uri",
")",
":",
"ni",
"=",
"self",
".",
"__lookup_uri",
"(",
"ns_uri",
")",
"return",
"iter",
"(",
"ni",
".",
"prefixes",
")"
] | Gets an iterator over the prefixes for the given namespace. | [
"Gets",
"an",
"iterator",
"over",
"the",
"prefixes",
"for",
"the",
"given",
"namespace",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L448-L451 | train | 525 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.remove_prefix | def remove_prefix(self, prefix):
"""Removes prefix from this set. This is a no-op if the prefix
doesn't exist in it.
"""
if prefix not in self.__prefix_map:
return
ni = self.__lookup_prefix(prefix)
ni.prefixes.discard(prefix)
del self.__prefix_map[prefix]
# If we removed the preferred prefix, find a new one.
if ni.preferred_prefix == prefix:
ni.preferred_prefix = next(iter(ni.prefixes), None) | python | def remove_prefix(self, prefix):
"""Removes prefix from this set. This is a no-op if the prefix
doesn't exist in it.
"""
if prefix not in self.__prefix_map:
return
ni = self.__lookup_prefix(prefix)
ni.prefixes.discard(prefix)
del self.__prefix_map[prefix]
# If we removed the preferred prefix, find a new one.
if ni.preferred_prefix == prefix:
ni.preferred_prefix = next(iter(ni.prefixes), None) | [
"def",
"remove_prefix",
"(",
"self",
",",
"prefix",
")",
":",
"if",
"prefix",
"not",
"in",
"self",
".",
"__prefix_map",
":",
"return",
"ni",
"=",
"self",
".",
"__lookup_prefix",
"(",
"prefix",
")",
"ni",
".",
"prefixes",
".",
"discard",
"(",
"prefix",
")",
"del",
"self",
".",
"__prefix_map",
"[",
"prefix",
"]",
"# If we removed the preferred prefix, find a new one.",
"if",
"ni",
".",
"preferred_prefix",
"==",
"prefix",
":",
"ni",
".",
"preferred_prefix",
"=",
"next",
"(",
"iter",
"(",
"ni",
".",
"prefixes",
")",
",",
"None",
")"
] | Removes prefix from this set. This is a no-op if the prefix
doesn't exist in it. | [
"Removes",
"prefix",
"from",
"this",
"set",
".",
"This",
"is",
"a",
"no",
"-",
"op",
"if",
"the",
"prefix",
"doesn",
"t",
"exist",
"in",
"it",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L453-L466 | train | 526 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.set_schema_location | def set_schema_location(self, ns_uri, schema_location, replace=False):
"""Sets the schema location of the given namespace.
If ``replace`` is ``True``, then any existing schema location is
replaced. Otherwise, if the schema location is already set to a
different value, an exception is raised. If the schema location is set
to None, it is effectively erased from this set (this is not considered
"replacement".)
Args:
ns_uri (str): The namespace whose schema location is to be set
schema_location (str): The schema location URI to set, or None
replace (bool): Whether to replace any existing schema location
Raises:
NamespaceNotFoundError: If the given namespace isn't in this set.
ConflictingSchemaLocationError: If replace is False,
schema_location is not None, and the namespace already has a
different schema location in this set.
"""
ni = self.__lookup_uri(ns_uri)
if ni.schema_location == schema_location:
return
elif replace or ni.schema_location is None:
ni.schema_location = schema_location
elif schema_location is None:
ni.schema_location = None # Not considered "replacement".
else:
raise ConflictingSchemaLocationError(ns_uri, ni.schema_location, schema_location) | python | def set_schema_location(self, ns_uri, schema_location, replace=False):
"""Sets the schema location of the given namespace.
If ``replace`` is ``True``, then any existing schema location is
replaced. Otherwise, if the schema location is already set to a
different value, an exception is raised. If the schema location is set
to None, it is effectively erased from this set (this is not considered
"replacement".)
Args:
ns_uri (str): The namespace whose schema location is to be set
schema_location (str): The schema location URI to set, or None
replace (bool): Whether to replace any existing schema location
Raises:
NamespaceNotFoundError: If the given namespace isn't in this set.
ConflictingSchemaLocationError: If replace is False,
schema_location is not None, and the namespace already has a
different schema location in this set.
"""
ni = self.__lookup_uri(ns_uri)
if ni.schema_location == schema_location:
return
elif replace or ni.schema_location is None:
ni.schema_location = schema_location
elif schema_location is None:
ni.schema_location = None # Not considered "replacement".
else:
raise ConflictingSchemaLocationError(ns_uri, ni.schema_location, schema_location) | [
"def",
"set_schema_location",
"(",
"self",
",",
"ns_uri",
",",
"schema_location",
",",
"replace",
"=",
"False",
")",
":",
"ni",
"=",
"self",
".",
"__lookup_uri",
"(",
"ns_uri",
")",
"if",
"ni",
".",
"schema_location",
"==",
"schema_location",
":",
"return",
"elif",
"replace",
"or",
"ni",
".",
"schema_location",
"is",
"None",
":",
"ni",
".",
"schema_location",
"=",
"schema_location",
"elif",
"schema_location",
"is",
"None",
":",
"ni",
".",
"schema_location",
"=",
"None",
"# Not considered \"replacement\".",
"else",
":",
"raise",
"ConflictingSchemaLocationError",
"(",
"ns_uri",
",",
"ni",
".",
"schema_location",
",",
"schema_location",
")"
] | Sets the schema location of the given namespace.
If ``replace`` is ``True``, then any existing schema location is
replaced. Otherwise, if the schema location is already set to a
different value, an exception is raised. If the schema location is set
to None, it is effectively erased from this set (this is not considered
"replacement".)
Args:
ns_uri (str): The namespace whose schema location is to be set
schema_location (str): The schema location URI to set, or None
replace (bool): Whether to replace any existing schema location
Raises:
NamespaceNotFoundError: If the given namespace isn't in this set.
ConflictingSchemaLocationError: If replace is False,
schema_location is not None, and the namespace already has a
different schema location in this set. | [
"Sets",
"the",
"schema",
"location",
"of",
"the",
"given",
"namespace",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L483-L512 | train | 527 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.get_schemaloc_string | def get_schemaloc_string(self, ns_uris=None, sort=False, delim="\n"):
"""Constructs and returns a schemalocation attribute. If no
namespaces in this set have any schema locations defined, returns
an empty string.
Args:
ns_uris (iterable): The namespaces to include in the constructed
attribute value. If None, all are included.
sort (bool): Whether the sort the namespace URIs.
delim (str): The delimiter to use between namespace/schemaloc
*pairs*.
Returns:
str: A schemalocation attribute in the format:
``xsi:schemaLocation="nsuri schemaloc<delim>nsuri2 schemaloc2<delim>..."``
"""
if not ns_uris:
ns_uris = six.iterkeys(self.__ns_uri_map)
if sort:
ns_uris = sorted(ns_uris)
schemalocs = []
for ns_uri in ns_uris:
ni = self.__lookup_uri(ns_uri)
if ni.schema_location:
schemalocs.append("{0.uri} {0.schema_location}".format(ni))
if not schemalocs:
return ""
return 'xsi:schemaLocation="{0}"'.format(delim.join(schemalocs)) | python | def get_schemaloc_string(self, ns_uris=None, sort=False, delim="\n"):
"""Constructs and returns a schemalocation attribute. If no
namespaces in this set have any schema locations defined, returns
an empty string.
Args:
ns_uris (iterable): The namespaces to include in the constructed
attribute value. If None, all are included.
sort (bool): Whether the sort the namespace URIs.
delim (str): The delimiter to use between namespace/schemaloc
*pairs*.
Returns:
str: A schemalocation attribute in the format:
``xsi:schemaLocation="nsuri schemaloc<delim>nsuri2 schemaloc2<delim>..."``
"""
if not ns_uris:
ns_uris = six.iterkeys(self.__ns_uri_map)
if sort:
ns_uris = sorted(ns_uris)
schemalocs = []
for ns_uri in ns_uris:
ni = self.__lookup_uri(ns_uri)
if ni.schema_location:
schemalocs.append("{0.uri} {0.schema_location}".format(ni))
if not schemalocs:
return ""
return 'xsi:schemaLocation="{0}"'.format(delim.join(schemalocs)) | [
"def",
"get_schemaloc_string",
"(",
"self",
",",
"ns_uris",
"=",
"None",
",",
"sort",
"=",
"False",
",",
"delim",
"=",
"\"\\n\"",
")",
":",
"if",
"not",
"ns_uris",
":",
"ns_uris",
"=",
"six",
".",
"iterkeys",
"(",
"self",
".",
"__ns_uri_map",
")",
"if",
"sort",
":",
"ns_uris",
"=",
"sorted",
"(",
"ns_uris",
")",
"schemalocs",
"=",
"[",
"]",
"for",
"ns_uri",
"in",
"ns_uris",
":",
"ni",
"=",
"self",
".",
"__lookup_uri",
"(",
"ns_uri",
")",
"if",
"ni",
".",
"schema_location",
":",
"schemalocs",
".",
"append",
"(",
"\"{0.uri} {0.schema_location}\"",
".",
"format",
"(",
"ni",
")",
")",
"if",
"not",
"schemalocs",
":",
"return",
"\"\"",
"return",
"'xsi:schemaLocation=\"{0}\"'",
".",
"format",
"(",
"delim",
".",
"join",
"(",
"schemalocs",
")",
")"
] | Constructs and returns a schemalocation attribute. If no
namespaces in this set have any schema locations defined, returns
an empty string.
Args:
ns_uris (iterable): The namespaces to include in the constructed
attribute value. If None, all are included.
sort (bool): Whether the sort the namespace URIs.
delim (str): The delimiter to use between namespace/schemaloc
*pairs*.
Returns:
str: A schemalocation attribute in the format:
``xsi:schemaLocation="nsuri schemaloc<delim>nsuri2 schemaloc2<delim>..."`` | [
"Constructs",
"and",
"returns",
"a",
"schemalocation",
"attribute",
".",
"If",
"no",
"namespaces",
"in",
"this",
"set",
"have",
"any",
"schema",
"locations",
"defined",
"returns",
"an",
"empty",
"string",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L593-L627 | train | 528 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.get_uri_prefix_map | def get_uri_prefix_map(self):
"""Constructs and returns a map from namespace URI to prefix,
representing all namespaces in this set. The prefix chosen for each
namespace is its preferred prefix if it's not None. If the preferred
prefix is None, one is chosen from the set of registered
prefixes. In the latter situation, if no prefixes are registered,
an exception is raised.
"""
mapping = {}
for ni in six.itervalues(self.__ns_uri_map):
if ni.preferred_prefix:
mapping[ni.uri] = ni.preferred_prefix
elif len(ni.prefixes) > 0:
mapping[ni.uri] = next(iter(ni.prefixes))
else:
# The reason I don't let any namespace map to None here is that
# I don't think generateDS supports it. It requires prefixes
# for all namespaces.
raise NoPrefixesError(ni.uri)
return mapping | python | def get_uri_prefix_map(self):
"""Constructs and returns a map from namespace URI to prefix,
representing all namespaces in this set. The prefix chosen for each
namespace is its preferred prefix if it's not None. If the preferred
prefix is None, one is chosen from the set of registered
prefixes. In the latter situation, if no prefixes are registered,
an exception is raised.
"""
mapping = {}
for ni in six.itervalues(self.__ns_uri_map):
if ni.preferred_prefix:
mapping[ni.uri] = ni.preferred_prefix
elif len(ni.prefixes) > 0:
mapping[ni.uri] = next(iter(ni.prefixes))
else:
# The reason I don't let any namespace map to None here is that
# I don't think generateDS supports it. It requires prefixes
# for all namespaces.
raise NoPrefixesError(ni.uri)
return mapping | [
"def",
"get_uri_prefix_map",
"(",
"self",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"ni",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"__ns_uri_map",
")",
":",
"if",
"ni",
".",
"preferred_prefix",
":",
"mapping",
"[",
"ni",
".",
"uri",
"]",
"=",
"ni",
".",
"preferred_prefix",
"elif",
"len",
"(",
"ni",
".",
"prefixes",
")",
">",
"0",
":",
"mapping",
"[",
"ni",
".",
"uri",
"]",
"=",
"next",
"(",
"iter",
"(",
"ni",
".",
"prefixes",
")",
")",
"else",
":",
"# The reason I don't let any namespace map to None here is that",
"# I don't think generateDS supports it. It requires prefixes",
"# for all namespaces.",
"raise",
"NoPrefixesError",
"(",
"ni",
".",
"uri",
")",
"return",
"mapping"
] | Constructs and returns a map from namespace URI to prefix,
representing all namespaces in this set. The prefix chosen for each
namespace is its preferred prefix if it's not None. If the preferred
prefix is None, one is chosen from the set of registered
prefixes. In the latter situation, if no prefixes are registered,
an exception is raised. | [
"Constructs",
"and",
"returns",
"a",
"map",
"from",
"namespace",
"URI",
"to",
"prefix",
"representing",
"all",
"namespaces",
"in",
"this",
"set",
".",
"The",
"prefix",
"chosen",
"for",
"each",
"namespace",
"is",
"its",
"preferred",
"prefix",
"if",
"it",
"s",
"not",
"None",
".",
"If",
"the",
"preferred",
"prefix",
"is",
"None",
"one",
"is",
"chosen",
"from",
"the",
"set",
"of",
"registered",
"prefixes",
".",
"In",
"the",
"latter",
"situation",
"if",
"no",
"prefixes",
"are",
"registered",
"an",
"exception",
"is",
"raised",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L629-L650 | train | 529 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.get_uri_schemaloc_map | def get_uri_schemaloc_map(self):
"""Constructs and returns a map from namespace URI to schema location
URI. Namespaces without schema locations are excluded."""
mapping = {}
for ni in six.itervalues(self.__ns_uri_map):
if ni.schema_location:
mapping[ni.uri] = ni.schema_location
return mapping | python | def get_uri_schemaloc_map(self):
"""Constructs and returns a map from namespace URI to schema location
URI. Namespaces without schema locations are excluded."""
mapping = {}
for ni in six.itervalues(self.__ns_uri_map):
if ni.schema_location:
mapping[ni.uri] = ni.schema_location
return mapping | [
"def",
"get_uri_schemaloc_map",
"(",
"self",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"ni",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"__ns_uri_map",
")",
":",
"if",
"ni",
".",
"schema_location",
":",
"mapping",
"[",
"ni",
".",
"uri",
"]",
"=",
"ni",
".",
"schema_location",
"return",
"mapping"
] | Constructs and returns a map from namespace URI to schema location
URI. Namespaces without schema locations are excluded. | [
"Constructs",
"and",
"returns",
"a",
"map",
"from",
"namespace",
"URI",
"to",
"schema",
"location",
"URI",
".",
"Namespaces",
"without",
"schema",
"locations",
"are",
"excluded",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L673-L682 | train | 530 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.subset | def subset(self, ns_uris):
"""Return a subset of this NamespaceSet containing only data for the
given namespaces.
Args:
ns_uris (iterable): An iterable of namespace URIs which select the
namespaces for the subset.
Returns:
The subset
Raises:
NamespaceNotFoundError: If any namespace URIs in `ns_uris` don't
match any namespaces in this set.
"""
sub_ns = NamespaceSet()
for ns_uri in ns_uris:
ni = self.__lookup_uri(ns_uri)
new_ni = copy.deepcopy(ni)
# We should be able to reach into details of our own
# implementation on another obj, right?? This makes the subset
# operation faster. We can set up the innards directly from a
# cloned _NamespaceInfo.
sub_ns._NamespaceSet__add_namespaceinfo(new_ni)
return sub_ns | python | def subset(self, ns_uris):
"""Return a subset of this NamespaceSet containing only data for the
given namespaces.
Args:
ns_uris (iterable): An iterable of namespace URIs which select the
namespaces for the subset.
Returns:
The subset
Raises:
NamespaceNotFoundError: If any namespace URIs in `ns_uris` don't
match any namespaces in this set.
"""
sub_ns = NamespaceSet()
for ns_uri in ns_uris:
ni = self.__lookup_uri(ns_uri)
new_ni = copy.deepcopy(ni)
# We should be able to reach into details of our own
# implementation on another obj, right?? This makes the subset
# operation faster. We can set up the innards directly from a
# cloned _NamespaceInfo.
sub_ns._NamespaceSet__add_namespaceinfo(new_ni)
return sub_ns | [
"def",
"subset",
"(",
"self",
",",
"ns_uris",
")",
":",
"sub_ns",
"=",
"NamespaceSet",
"(",
")",
"for",
"ns_uri",
"in",
"ns_uris",
":",
"ni",
"=",
"self",
".",
"__lookup_uri",
"(",
"ns_uri",
")",
"new_ni",
"=",
"copy",
".",
"deepcopy",
"(",
"ni",
")",
"# We should be able to reach into details of our own",
"# implementation on another obj, right?? This makes the subset",
"# operation faster. We can set up the innards directly from a",
"# cloned _NamespaceInfo.",
"sub_ns",
".",
"_NamespaceSet__add_namespaceinfo",
"(",
"new_ni",
")",
"return",
"sub_ns"
] | Return a subset of this NamespaceSet containing only data for the
given namespaces.
Args:
ns_uris (iterable): An iterable of namespace URIs which select the
namespaces for the subset.
Returns:
The subset
Raises:
NamespaceNotFoundError: If any namespace URIs in `ns_uris` don't
match any namespaces in this set. | [
"Return",
"a",
"subset",
"of",
"this",
"NamespaceSet",
"containing",
"only",
"data",
"for",
"the",
"given",
"namespaces",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L690-L717 | train | 531 |
CybOXProject/mixbox | mixbox/namespaces.py | NamespaceSet.import_from | def import_from(self, other_ns, replace=False):
"""Imports namespaces into this set, from other_ns.
Args:
other_ns (NamespaceSet): The set to import from
replace (bool): If a namespace exists in both sets, do we replace
our data with other_ns's data? We could get fancy and define
some merge strategies, but for now, this is very simple. It's
either do nothing, or wholesale replacement. There is no
merging.
Raises:
DuplicatePrefixError: If the other NamespaceSet is mapping any
prefixes incompatibly with respect to this set.
"""
for other_ns_uri in other_ns.namespace_uris:
ni = self.__ns_uri_map.get(other_ns_uri)
if ni is None:
other_ni = other_ns._NamespaceSet__ns_uri_map[other_ns_uri]
# Gotta make sure that the other set isn't mapping its prefixes
# incompatibly with respect to this set.
for other_prefix in other_ni.prefixes:
self.__check_prefix_conflict(other_ns_uri, other_prefix)
cloned_ni = copy.deepcopy(other_ni)
self.__add_namespaceinfo(cloned_ni)
elif replace:
other_ni = other_ns._NamespaceSet__ns_uri_map[other_ns_uri]
for other_prefix in other_ni.prefixes:
self.__check_prefix_conflict(ni, other_prefix)
cloned_ni = copy.deepcopy(other_ni)
self.remove_namespace(other_ns_uri)
self.__add_namespaceinfo(cloned_ni)
else:
continue | python | def import_from(self, other_ns, replace=False):
"""Imports namespaces into this set, from other_ns.
Args:
other_ns (NamespaceSet): The set to import from
replace (bool): If a namespace exists in both sets, do we replace
our data with other_ns's data? We could get fancy and define
some merge strategies, but for now, this is very simple. It's
either do nothing, or wholesale replacement. There is no
merging.
Raises:
DuplicatePrefixError: If the other NamespaceSet is mapping any
prefixes incompatibly with respect to this set.
"""
for other_ns_uri in other_ns.namespace_uris:
ni = self.__ns_uri_map.get(other_ns_uri)
if ni is None:
other_ni = other_ns._NamespaceSet__ns_uri_map[other_ns_uri]
# Gotta make sure that the other set isn't mapping its prefixes
# incompatibly with respect to this set.
for other_prefix in other_ni.prefixes:
self.__check_prefix_conflict(other_ns_uri, other_prefix)
cloned_ni = copy.deepcopy(other_ni)
self.__add_namespaceinfo(cloned_ni)
elif replace:
other_ni = other_ns._NamespaceSet__ns_uri_map[other_ns_uri]
for other_prefix in other_ni.prefixes:
self.__check_prefix_conflict(ni, other_prefix)
cloned_ni = copy.deepcopy(other_ni)
self.remove_namespace(other_ns_uri)
self.__add_namespaceinfo(cloned_ni)
else:
continue | [
"def",
"import_from",
"(",
"self",
",",
"other_ns",
",",
"replace",
"=",
"False",
")",
":",
"for",
"other_ns_uri",
"in",
"other_ns",
".",
"namespace_uris",
":",
"ni",
"=",
"self",
".",
"__ns_uri_map",
".",
"get",
"(",
"other_ns_uri",
")",
"if",
"ni",
"is",
"None",
":",
"other_ni",
"=",
"other_ns",
".",
"_NamespaceSet__ns_uri_map",
"[",
"other_ns_uri",
"]",
"# Gotta make sure that the other set isn't mapping its prefixes",
"# incompatibly with respect to this set.",
"for",
"other_prefix",
"in",
"other_ni",
".",
"prefixes",
":",
"self",
".",
"__check_prefix_conflict",
"(",
"other_ns_uri",
",",
"other_prefix",
")",
"cloned_ni",
"=",
"copy",
".",
"deepcopy",
"(",
"other_ni",
")",
"self",
".",
"__add_namespaceinfo",
"(",
"cloned_ni",
")",
"elif",
"replace",
":",
"other_ni",
"=",
"other_ns",
".",
"_NamespaceSet__ns_uri_map",
"[",
"other_ns_uri",
"]",
"for",
"other_prefix",
"in",
"other_ni",
".",
"prefixes",
":",
"self",
".",
"__check_prefix_conflict",
"(",
"ni",
",",
"other_prefix",
")",
"cloned_ni",
"=",
"copy",
".",
"deepcopy",
"(",
"other_ni",
")",
"self",
".",
"remove_namespace",
"(",
"other_ns_uri",
")",
"self",
".",
"__add_namespaceinfo",
"(",
"cloned_ni",
")",
"else",
":",
"continue"
] | Imports namespaces into this set, from other_ns.
Args:
other_ns (NamespaceSet): The set to import from
replace (bool): If a namespace exists in both sets, do we replace
our data with other_ns's data? We could get fancy and define
some merge strategies, but for now, this is very simple. It's
either do nothing, or wholesale replacement. There is no
merging.
Raises:
DuplicatePrefixError: If the other NamespaceSet is mapping any
prefixes incompatibly with respect to this set. | [
"Imports",
"namespaces",
"into",
"this",
"set",
"from",
"other_ns",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L719-L756 | train | 532 |
CybOXProject/mixbox | mixbox/parser.py | EntityParser._get_version | def _get_version(self, root):
"""Return the version of the root element passed in.
Args:
root (etree.Element)
Returns:
distutils.StrictVersion
Raises:
UnknownVersionError
"""
# Note: STIX and MAEC use a "version" attribute. To support CybOX, a
# subclass will need to combine "cybox_major_version",
# "cybox_minor_version", and "cybox_update_version".
version = self.get_version(root)
if version:
return StrictVersion(version)
raise UnknownVersionError(
"Unable to determine the version of the input document. No "
"version information found on the root element."
) | python | def _get_version(self, root):
"""Return the version of the root element passed in.
Args:
root (etree.Element)
Returns:
distutils.StrictVersion
Raises:
UnknownVersionError
"""
# Note: STIX and MAEC use a "version" attribute. To support CybOX, a
# subclass will need to combine "cybox_major_version",
# "cybox_minor_version", and "cybox_update_version".
version = self.get_version(root)
if version:
return StrictVersion(version)
raise UnknownVersionError(
"Unable to determine the version of the input document. No "
"version information found on the root element."
) | [
"def",
"_get_version",
"(",
"self",
",",
"root",
")",
":",
"# Note: STIX and MAEC use a \"version\" attribute. To support CybOX, a",
"# subclass will need to combine \"cybox_major_version\",",
"# \"cybox_minor_version\", and \"cybox_update_version\".",
"version",
"=",
"self",
".",
"get_version",
"(",
"root",
")",
"if",
"version",
":",
"return",
"StrictVersion",
"(",
"version",
")",
"raise",
"UnknownVersionError",
"(",
"\"Unable to determine the version of the input document. No \"",
"\"version information found on the root element.\"",
")"
] | Return the version of the root element passed in.
Args:
root (etree.Element)
Returns:
distutils.StrictVersion
Raises:
UnknownVersionError | [
"Return",
"the",
"version",
"of",
"the",
"root",
"element",
"passed",
"in",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/parser.py#L55-L77 | train | 533 |
CybOXProject/mixbox | mixbox/parser.py | EntityParser._check_version | def _check_version(self, root):
"""Ensure the root element is a supported version.
Args:
root (etree.Element)
Raises:
UnsupportedVersionError
"""
version = self._get_version(root)
supported = [StrictVersion(x) for x in
self.supported_versions(root.tag)]
if version in supported:
return
error = "Document version ({0}) not in supported versions ({1})"
raise UnsupportedVersionError(
message=error.format(version, supported),
expected=supported,
found=version
) | python | def _check_version(self, root):
"""Ensure the root element is a supported version.
Args:
root (etree.Element)
Raises:
UnsupportedVersionError
"""
version = self._get_version(root)
supported = [StrictVersion(x) for x in
self.supported_versions(root.tag)]
if version in supported:
return
error = "Document version ({0}) not in supported versions ({1})"
raise UnsupportedVersionError(
message=error.format(version, supported),
expected=supported,
found=version
) | [
"def",
"_check_version",
"(",
"self",
",",
"root",
")",
":",
"version",
"=",
"self",
".",
"_get_version",
"(",
"root",
")",
"supported",
"=",
"[",
"StrictVersion",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"supported_versions",
"(",
"root",
".",
"tag",
")",
"]",
"if",
"version",
"in",
"supported",
":",
"return",
"error",
"=",
"\"Document version ({0}) not in supported versions ({1})\"",
"raise",
"UnsupportedVersionError",
"(",
"message",
"=",
"error",
".",
"format",
"(",
"version",
",",
"supported",
")",
",",
"expected",
"=",
"supported",
",",
"found",
"=",
"version",
")"
] | Ensure the root element is a supported version.
Args:
root (etree.Element)
Raises:
UnsupportedVersionError | [
"Ensure",
"the",
"root",
"element",
"is",
"a",
"supported",
"version",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/parser.py#L79-L100 | train | 534 |
CybOXProject/mixbox | mixbox/parser.py | EntityParser._check_root_tag | def _check_root_tag(self, root):
"""Check that the XML element tree has a supported root element.
Args:
root (etree.Element)
Raises:
UnsupportedRootElementError
"""
supported = self.supported_tags()
if root.tag in supported:
return
error = "Document root element ({0}) not one of ({1})"
raise UnsupportedRootElementError(
message=error.format(root.tag, supported),
expected=supported,
found=root.tag,
) | python | def _check_root_tag(self, root):
"""Check that the XML element tree has a supported root element.
Args:
root (etree.Element)
Raises:
UnsupportedRootElementError
"""
supported = self.supported_tags()
if root.tag in supported:
return
error = "Document root element ({0}) not one of ({1})"
raise UnsupportedRootElementError(
message=error.format(root.tag, supported),
expected=supported,
found=root.tag,
) | [
"def",
"_check_root_tag",
"(",
"self",
",",
"root",
")",
":",
"supported",
"=",
"self",
".",
"supported_tags",
"(",
")",
"if",
"root",
".",
"tag",
"in",
"supported",
":",
"return",
"error",
"=",
"\"Document root element ({0}) not one of ({1})\"",
"raise",
"UnsupportedRootElementError",
"(",
"message",
"=",
"error",
".",
"format",
"(",
"root",
".",
"tag",
",",
"supported",
")",
",",
"expected",
"=",
"supported",
",",
"found",
"=",
"root",
".",
"tag",
",",
")"
] | Check that the XML element tree has a supported root element.
Args:
root (etree.Element)
Raises:
UnsupportedRootElementError | [
"Check",
"that",
"the",
"XML",
"element",
"tree",
"has",
"a",
"supported",
"root",
"element",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/parser.py#L102-L120 | train | 535 |
CybOXProject/mixbox | mixbox/parser.py | EntityParser.parse_xml_to_obj | def parse_xml_to_obj(self, xml_file, check_version=True, check_root=True,
encoding=None):
"""Creates a STIX binding object from the supplied xml file.
Args:
xml_file: A filename/path or a file-like object representing a STIX
instance document
check_version: Inspect the version before parsing.
check_root: Inspect the root element before parsing.
encoding: The character encoding of the input `xml_file`.
Raises:
.UnknownVersionError: If `check_version` is ``True`` and `xml_file`
does not contain STIX version information.
.UnsupportedVersionError: If `check_version` is ``False`` and
`xml_file` contains an unsupported STIX version.
.UnsupportedRootElement: If `check_root` is ``True`` and `xml_file`
contains an invalid root element.
"""
root = get_etree_root(xml_file, encoding=encoding)
if check_root:
self._check_root_tag(root)
if check_version:
self._check_version(root)
entity_class = self.get_entity_class(root.tag)
entity_obj = entity_class._binding_class.factory()
entity_obj.build(root)
return entity_obj | python | def parse_xml_to_obj(self, xml_file, check_version=True, check_root=True,
encoding=None):
"""Creates a STIX binding object from the supplied xml file.
Args:
xml_file: A filename/path or a file-like object representing a STIX
instance document
check_version: Inspect the version before parsing.
check_root: Inspect the root element before parsing.
encoding: The character encoding of the input `xml_file`.
Raises:
.UnknownVersionError: If `check_version` is ``True`` and `xml_file`
does not contain STIX version information.
.UnsupportedVersionError: If `check_version` is ``False`` and
`xml_file` contains an unsupported STIX version.
.UnsupportedRootElement: If `check_root` is ``True`` and `xml_file`
contains an invalid root element.
"""
root = get_etree_root(xml_file, encoding=encoding)
if check_root:
self._check_root_tag(root)
if check_version:
self._check_version(root)
entity_class = self.get_entity_class(root.tag)
entity_obj = entity_class._binding_class.factory()
entity_obj.build(root)
return entity_obj | [
"def",
"parse_xml_to_obj",
"(",
"self",
",",
"xml_file",
",",
"check_version",
"=",
"True",
",",
"check_root",
"=",
"True",
",",
"encoding",
"=",
"None",
")",
":",
"root",
"=",
"get_etree_root",
"(",
"xml_file",
",",
"encoding",
"=",
"encoding",
")",
"if",
"check_root",
":",
"self",
".",
"_check_root_tag",
"(",
"root",
")",
"if",
"check_version",
":",
"self",
".",
"_check_version",
"(",
"root",
")",
"entity_class",
"=",
"self",
".",
"get_entity_class",
"(",
"root",
".",
"tag",
")",
"entity_obj",
"=",
"entity_class",
".",
"_binding_class",
".",
"factory",
"(",
")",
"entity_obj",
".",
"build",
"(",
"root",
")",
"return",
"entity_obj"
] | Creates a STIX binding object from the supplied xml file.
Args:
xml_file: A filename/path or a file-like object representing a STIX
instance document
check_version: Inspect the version before parsing.
check_root: Inspect the root element before parsing.
encoding: The character encoding of the input `xml_file`.
Raises:
.UnknownVersionError: If `check_version` is ``True`` and `xml_file`
does not contain STIX version information.
.UnsupportedVersionError: If `check_version` is ``False`` and
`xml_file` contains an unsupported STIX version.
.UnsupportedRootElement: If `check_root` is ``True`` and `xml_file`
contains an invalid root element. | [
"Creates",
"a",
"STIX",
"binding",
"object",
"from",
"the",
"supplied",
"xml",
"file",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/parser.py#L122-L154 | train | 536 |
CybOXProject/mixbox | mixbox/parser.py | EntityParser.parse_xml | def parse_xml(self, xml_file, check_version=True, check_root=True,
encoding=None):
"""Creates a python-stix STIXPackage object from the supplied xml_file.
Args:
xml_file: A filename/path or a file-like object representing a STIX
instance document
check_version: Inspect the version before parsing.
check_root: Inspect the root element before parsing.
encoding: The character encoding of the input `xml_file`. If
``None``, an attempt will be made to determine the input
character encoding.
Raises:
.UnknownVersionError: If `check_version` is ``True`` and `xml_file`
does not contain STIX version information.
.UnsupportedVersionError: If `check_version` is ``False`` and
`xml_file` contains an unsupported STIX version.
.UnsupportedRootElement: If `check_root` is ``True`` and `xml_file`
contains an invalid root element.
"""
xml_etree = get_etree(xml_file, encoding=encoding)
entity_obj = self.parse_xml_to_obj(
xml_file=xml_etree,
check_version=check_version,
check_root=check_root
)
xml_root_node = xml_etree.getroot()
entity = self.get_entity_class(xml_root_node.tag).from_obj(entity_obj)
# Save the parsed nsmap and schemalocations onto the parsed Entity
entity.__input_namespaces__ = dict(iteritems(xml_root_node.nsmap))
with ignored(KeyError):
pairs = get_schemaloc_pairs(xml_root_node)
entity.__input_schemalocations__ = dict(pairs)
return entity | python | def parse_xml(self, xml_file, check_version=True, check_root=True,
encoding=None):
"""Creates a python-stix STIXPackage object from the supplied xml_file.
Args:
xml_file: A filename/path or a file-like object representing a STIX
instance document
check_version: Inspect the version before parsing.
check_root: Inspect the root element before parsing.
encoding: The character encoding of the input `xml_file`. If
``None``, an attempt will be made to determine the input
character encoding.
Raises:
.UnknownVersionError: If `check_version` is ``True`` and `xml_file`
does not contain STIX version information.
.UnsupportedVersionError: If `check_version` is ``False`` and
`xml_file` contains an unsupported STIX version.
.UnsupportedRootElement: If `check_root` is ``True`` and `xml_file`
contains an invalid root element.
"""
xml_etree = get_etree(xml_file, encoding=encoding)
entity_obj = self.parse_xml_to_obj(
xml_file=xml_etree,
check_version=check_version,
check_root=check_root
)
xml_root_node = xml_etree.getroot()
entity = self.get_entity_class(xml_root_node.tag).from_obj(entity_obj)
# Save the parsed nsmap and schemalocations onto the parsed Entity
entity.__input_namespaces__ = dict(iteritems(xml_root_node.nsmap))
with ignored(KeyError):
pairs = get_schemaloc_pairs(xml_root_node)
entity.__input_schemalocations__ = dict(pairs)
return entity | [
"def",
"parse_xml",
"(",
"self",
",",
"xml_file",
",",
"check_version",
"=",
"True",
",",
"check_root",
"=",
"True",
",",
"encoding",
"=",
"None",
")",
":",
"xml_etree",
"=",
"get_etree",
"(",
"xml_file",
",",
"encoding",
"=",
"encoding",
")",
"entity_obj",
"=",
"self",
".",
"parse_xml_to_obj",
"(",
"xml_file",
"=",
"xml_etree",
",",
"check_version",
"=",
"check_version",
",",
"check_root",
"=",
"check_root",
")",
"xml_root_node",
"=",
"xml_etree",
".",
"getroot",
"(",
")",
"entity",
"=",
"self",
".",
"get_entity_class",
"(",
"xml_root_node",
".",
"tag",
")",
".",
"from_obj",
"(",
"entity_obj",
")",
"# Save the parsed nsmap and schemalocations onto the parsed Entity",
"entity",
".",
"__input_namespaces__",
"=",
"dict",
"(",
"iteritems",
"(",
"xml_root_node",
".",
"nsmap",
")",
")",
"with",
"ignored",
"(",
"KeyError",
")",
":",
"pairs",
"=",
"get_schemaloc_pairs",
"(",
"xml_root_node",
")",
"entity",
".",
"__input_schemalocations__",
"=",
"dict",
"(",
"pairs",
")",
"return",
"entity"
] | Creates a python-stix STIXPackage object from the supplied xml_file.
Args:
xml_file: A filename/path or a file-like object representing a STIX
instance document
check_version: Inspect the version before parsing.
check_root: Inspect the root element before parsing.
encoding: The character encoding of the input `xml_file`. If
``None``, an attempt will be made to determine the input
character encoding.
Raises:
.UnknownVersionError: If `check_version` is ``True`` and `xml_file`
does not contain STIX version information.
.UnsupportedVersionError: If `check_version` is ``False`` and
`xml_file` contains an unsupported STIX version.
.UnsupportedRootElement: If `check_root` is ``True`` and `xml_file`
contains an invalid root element. | [
"Creates",
"a",
"python",
"-",
"stix",
"STIXPackage",
"object",
"from",
"the",
"supplied",
"xml_file",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/parser.py#L156-L195 | train | 537 |
inveniosoftware/invenio-communities | invenio_communities/serializers/schemas/community.py | CommunitySchemaV1.get_logo_url | def get_logo_url(self, obj):
"""Get the community logo URL."""
if current_app and obj.logo_url:
return u'{site_url}{path}'.format(
site_url=current_app.config.get('THEME_SITEURL'),
path=obj.logo_url,
) | python | def get_logo_url(self, obj):
"""Get the community logo URL."""
if current_app and obj.logo_url:
return u'{site_url}{path}'.format(
site_url=current_app.config.get('THEME_SITEURL'),
path=obj.logo_url,
) | [
"def",
"get_logo_url",
"(",
"self",
",",
"obj",
")",
":",
"if",
"current_app",
"and",
"obj",
".",
"logo_url",
":",
"return",
"u'{site_url}{path}'",
".",
"format",
"(",
"site_url",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'THEME_SITEURL'",
")",
",",
"path",
"=",
"obj",
".",
"logo_url",
",",
")"
] | Get the community logo URL. | [
"Get",
"the",
"community",
"logo",
"URL",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/serializers/schemas/community.py#L50-L56 | train | 538 |
inveniosoftware/invenio-communities | invenio_communities/serializers/schemas/community.py | CommunitySchemaV1.item_links_addition | def item_links_addition(self, data):
"""Add the links for each community."""
links_item_factory = self.context.get('links_item_factory',
default_links_item_factory)
data['links'] = links_item_factory(data)
return data | python | def item_links_addition(self, data):
"""Add the links for each community."""
links_item_factory = self.context.get('links_item_factory',
default_links_item_factory)
data['links'] = links_item_factory(data)
return data | [
"def",
"item_links_addition",
"(",
"self",
",",
"data",
")",
":",
"links_item_factory",
"=",
"self",
".",
"context",
".",
"get",
"(",
"'links_item_factory'",
",",
"default_links_item_factory",
")",
"data",
"[",
"'links'",
"]",
"=",
"links_item_factory",
"(",
"data",
")",
"return",
"data"
] | Add the links for each community. | [
"Add",
"the",
"links",
"for",
"each",
"community",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/serializers/schemas/community.py#L59-L64 | train | 539 |
inveniosoftware/invenio-communities | invenio_communities/serializers/schemas/community.py | CommunitySchemaV1.envelope | def envelope(self, data, many):
"""Wrap result in envelope."""
if not many:
return data
result = dict(
hits=dict(
hits=data,
total=self.context.get('total', len(data))
)
)
page = self.context.get('page')
if page:
links_pagination_factory = self.context.get(
'links_pagination_factory',
default_links_pagination_factory
)
urlkwargs = self.context.get('urlkwargs', {})
result['links'] = links_pagination_factory(page, urlkwargs)
return result | python | def envelope(self, data, many):
"""Wrap result in envelope."""
if not many:
return data
result = dict(
hits=dict(
hits=data,
total=self.context.get('total', len(data))
)
)
page = self.context.get('page')
if page:
links_pagination_factory = self.context.get(
'links_pagination_factory',
default_links_pagination_factory
)
urlkwargs = self.context.get('urlkwargs', {})
result['links'] = links_pagination_factory(page, urlkwargs)
return result | [
"def",
"envelope",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"if",
"not",
"many",
":",
"return",
"data",
"result",
"=",
"dict",
"(",
"hits",
"=",
"dict",
"(",
"hits",
"=",
"data",
",",
"total",
"=",
"self",
".",
"context",
".",
"get",
"(",
"'total'",
",",
"len",
"(",
"data",
")",
")",
")",
")",
"page",
"=",
"self",
".",
"context",
".",
"get",
"(",
"'page'",
")",
"if",
"page",
":",
"links_pagination_factory",
"=",
"self",
".",
"context",
".",
"get",
"(",
"'links_pagination_factory'",
",",
"default_links_pagination_factory",
")",
"urlkwargs",
"=",
"self",
".",
"context",
".",
"get",
"(",
"'urlkwargs'",
",",
"{",
"}",
")",
"result",
"[",
"'links'",
"]",
"=",
"links_pagination_factory",
"(",
"page",
",",
"urlkwargs",
")",
"return",
"result"
] | Wrap result in envelope. | [
"Wrap",
"result",
"in",
"envelope",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/serializers/schemas/community.py#L67-L90 | train | 540 |
CybOXProject/mixbox | mixbox/dates.py | parse_datetime | def parse_datetime(value):
"""Attempts to parse `value` into an instance of ``datetime.datetime``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string or datetime.datetime value.
"""
if not value:
return None
elif isinstance(value, datetime.datetime):
return value
return dateutil.parser.parse(value) | python | def parse_datetime(value):
"""Attempts to parse `value` into an instance of ``datetime.datetime``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string or datetime.datetime value.
"""
if not value:
return None
elif isinstance(value, datetime.datetime):
return value
return dateutil.parser.parse(value) | [
"def",
"parse_datetime",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
"return",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"value",
")"
] | Attempts to parse `value` into an instance of ``datetime.datetime``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string or datetime.datetime value. | [
"Attempts",
"to",
"parse",
"value",
"into",
"an",
"instance",
"of",
"datetime",
".",
"datetime",
".",
"If",
"value",
"is",
"None",
"this",
"function",
"will",
"return",
"None",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/dates.py#L13-L25 | train | 541 |
CybOXProject/mixbox | mixbox/dates.py | parse_date | def parse_date(value):
"""Attempts to parse `value` into an instance of ``datetime.date``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string, datetime.date, or
datetime.datetime value.
"""
if not value:
return None
if isinstance(value, datetime.date):
return value
return parse_datetime(value).date() | python | def parse_date(value):
"""Attempts to parse `value` into an instance of ``datetime.date``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string, datetime.date, or
datetime.datetime value.
"""
if not value:
return None
if isinstance(value, datetime.date):
return value
return parse_datetime(value).date() | [
"def",
"parse_date",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
":",
"return",
"value",
"return",
"parse_datetime",
"(",
"value",
")",
".",
"date",
"(",
")"
] | Attempts to parse `value` into an instance of ``datetime.date``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string, datetime.date, or
datetime.datetime value. | [
"Attempts",
"to",
"parse",
"value",
"into",
"an",
"instance",
"of",
"datetime",
".",
"date",
".",
"If",
"value",
"is",
"None",
"this",
"function",
"will",
"return",
"None",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/dates.py#L44-L59 | train | 542 |
SpotlightData/preprocessing | preprocessing/spellcheck.py | correct_word | def correct_word(word_string):
'''
Finds all valid one and two letter corrections for word_string, returning the word
with the highest relative probability as type str.
'''
if word_string is None:
return ""
elif isinstance(word_string, str):
return max(find_candidates(word_string), key=find_word_prob)
else:
raise InputError("string or none type variable not passed as argument to correct_word") | python | def correct_word(word_string):
'''
Finds all valid one and two letter corrections for word_string, returning the word
with the highest relative probability as type str.
'''
if word_string is None:
return ""
elif isinstance(word_string, str):
return max(find_candidates(word_string), key=find_word_prob)
else:
raise InputError("string or none type variable not passed as argument to correct_word") | [
"def",
"correct_word",
"(",
"word_string",
")",
":",
"if",
"word_string",
"is",
"None",
":",
"return",
"\"\"",
"elif",
"isinstance",
"(",
"word_string",
",",
"str",
")",
":",
"return",
"max",
"(",
"find_candidates",
"(",
"word_string",
")",
",",
"key",
"=",
"find_word_prob",
")",
"else",
":",
"raise",
"InputError",
"(",
"\"string or none type variable not passed as argument to correct_word\"",
")"
] | Finds all valid one and two letter corrections for word_string, returning the word
with the highest relative probability as type str. | [
"Finds",
"all",
"valid",
"one",
"and",
"two",
"letter",
"corrections",
"for",
"word_string",
"returning",
"the",
"word",
"with",
"the",
"highest",
"relative",
"probability",
"as",
"type",
"str",
"."
] | 180c6472bc2642afbd7a1ece08d0b0d14968a708 | https://github.com/SpotlightData/preprocessing/blob/180c6472bc2642afbd7a1ece08d0b0d14968a708/preprocessing/spellcheck.py#L18-L28 | train | 543 |
SpotlightData/preprocessing | preprocessing/spellcheck.py | find_candidates | def find_candidates(word_string):
'''
Finds all potential words word_string could have intended to mean. If a word is not incorrectly
spelled, it will return this word first, else if will look for one letter edits that are correct.
If there are no valid one letter edits, it will perform a two letter edit search.
If valid corrections are found, all are returned as a set instance. Should a valid word not be
found, the original word is returned as a set instance.
'''
if word_string is None:
return {}
elif isinstance(word_string, str):
return (validate_words([word_string]) or validate_words(list(find_one_letter_edits(word_string)))
or validate_words(list(find_two_letter_edits(word_string))) or set([word_string]))
else:
raise InputError("string or none type variable not passed as argument to find_candidates") | python | def find_candidates(word_string):
'''
Finds all potential words word_string could have intended to mean. If a word is not incorrectly
spelled, it will return this word first, else if will look for one letter edits that are correct.
If there are no valid one letter edits, it will perform a two letter edit search.
If valid corrections are found, all are returned as a set instance. Should a valid word not be
found, the original word is returned as a set instance.
'''
if word_string is None:
return {}
elif isinstance(word_string, str):
return (validate_words([word_string]) or validate_words(list(find_one_letter_edits(word_string)))
or validate_words(list(find_two_letter_edits(word_string))) or set([word_string]))
else:
raise InputError("string or none type variable not passed as argument to find_candidates") | [
"def",
"find_candidates",
"(",
"word_string",
")",
":",
"if",
"word_string",
"is",
"None",
":",
"return",
"{",
"}",
"elif",
"isinstance",
"(",
"word_string",
",",
"str",
")",
":",
"return",
"(",
"validate_words",
"(",
"[",
"word_string",
"]",
")",
"or",
"validate_words",
"(",
"list",
"(",
"find_one_letter_edits",
"(",
"word_string",
")",
")",
")",
"or",
"validate_words",
"(",
"list",
"(",
"find_two_letter_edits",
"(",
"word_string",
")",
")",
")",
"or",
"set",
"(",
"[",
"word_string",
"]",
")",
")",
"else",
":",
"raise",
"InputError",
"(",
"\"string or none type variable not passed as argument to find_candidates\"",
")"
] | Finds all potential words word_string could have intended to mean. If a word is not incorrectly
spelled, it will return this word first, else if will look for one letter edits that are correct.
If there are no valid one letter edits, it will perform a two letter edit search.
If valid corrections are found, all are returned as a set instance. Should a valid word not be
found, the original word is returned as a set instance. | [
"Finds",
"all",
"potential",
"words",
"word_string",
"could",
"have",
"intended",
"to",
"mean",
".",
"If",
"a",
"word",
"is",
"not",
"incorrectly",
"spelled",
"it",
"will",
"return",
"this",
"word",
"first",
"else",
"if",
"will",
"look",
"for",
"one",
"letter",
"edits",
"that",
"are",
"correct",
".",
"If",
"there",
"are",
"no",
"valid",
"one",
"letter",
"edits",
"it",
"will",
"perform",
"a",
"two",
"letter",
"edit",
"search",
"."
] | 180c6472bc2642afbd7a1ece08d0b0d14968a708 | https://github.com/SpotlightData/preprocessing/blob/180c6472bc2642afbd7a1ece08d0b0d14968a708/preprocessing/spellcheck.py#L30-L45 | train | 544 |
SpotlightData/preprocessing | preprocessing/spellcheck.py | find_word_prob | def find_word_prob(word_string, word_total=sum(WORD_DISTRIBUTION.values())):
'''
Finds the relative probability of the word appearing given context of a base corpus.
Returns this probability value as a float instance.
'''
if word_string is None:
return 0
elif isinstance(word_string, str):
return WORD_DISTRIBUTION[word_string] / word_total
else:
raise InputError("string or none type variable not passed as argument to find_word_prob") | python | def find_word_prob(word_string, word_total=sum(WORD_DISTRIBUTION.values())):
'''
Finds the relative probability of the word appearing given context of a base corpus.
Returns this probability value as a float instance.
'''
if word_string is None:
return 0
elif isinstance(word_string, str):
return WORD_DISTRIBUTION[word_string] / word_total
else:
raise InputError("string or none type variable not passed as argument to find_word_prob") | [
"def",
"find_word_prob",
"(",
"word_string",
",",
"word_total",
"=",
"sum",
"(",
"WORD_DISTRIBUTION",
".",
"values",
"(",
")",
")",
")",
":",
"if",
"word_string",
"is",
"None",
":",
"return",
"0",
"elif",
"isinstance",
"(",
"word_string",
",",
"str",
")",
":",
"return",
"WORD_DISTRIBUTION",
"[",
"word_string",
"]",
"/",
"word_total",
"else",
":",
"raise",
"InputError",
"(",
"\"string or none type variable not passed as argument to find_word_prob\"",
")"
] | Finds the relative probability of the word appearing given context of a base corpus.
Returns this probability value as a float instance. | [
"Finds",
"the",
"relative",
"probability",
"of",
"the",
"word",
"appearing",
"given",
"context",
"of",
"a",
"base",
"corpus",
".",
"Returns",
"this",
"probability",
"value",
"as",
"a",
"float",
"instance",
"."
] | 180c6472bc2642afbd7a1ece08d0b0d14968a708 | https://github.com/SpotlightData/preprocessing/blob/180c6472bc2642afbd7a1ece08d0b0d14968a708/preprocessing/spellcheck.py#L91-L101 | train | 545 |
SpotlightData/preprocessing | preprocessing/spellcheck.py | validate_words | def validate_words(word_list):
'''
Checks for each edited word in word_list if that word is a valid english word.abs
Returns all validated words as a set instance.
'''
if word_list is None:
return {}
elif isinstance(word_list, list):
if not word_list:
return {}
else:
return set(word for word in word_list if word in WORD_DISTRIBUTION)
else:
raise InputError("list variable not passed as argument to validate_words") | python | def validate_words(word_list):
'''
Checks for each edited word in word_list if that word is a valid english word.abs
Returns all validated words as a set instance.
'''
if word_list is None:
return {}
elif isinstance(word_list, list):
if not word_list:
return {}
else:
return set(word for word in word_list if word in WORD_DISTRIBUTION)
else:
raise InputError("list variable not passed as argument to validate_words") | [
"def",
"validate_words",
"(",
"word_list",
")",
":",
"if",
"word_list",
"is",
"None",
":",
"return",
"{",
"}",
"elif",
"isinstance",
"(",
"word_list",
",",
"list",
")",
":",
"if",
"not",
"word_list",
":",
"return",
"{",
"}",
"else",
":",
"return",
"set",
"(",
"word",
"for",
"word",
"in",
"word_list",
"if",
"word",
"in",
"WORD_DISTRIBUTION",
")",
"else",
":",
"raise",
"InputError",
"(",
"\"list variable not passed as argument to validate_words\"",
")"
] | Checks for each edited word in word_list if that word is a valid english word.abs
Returns all validated words as a set instance. | [
"Checks",
"for",
"each",
"edited",
"word",
"in",
"word_list",
"if",
"that",
"word",
"is",
"a",
"valid",
"english",
"word",
".",
"abs",
"Returns",
"all",
"validated",
"words",
"as",
"a",
"set",
"instance",
"."
] | 180c6472bc2642afbd7a1ece08d0b0d14968a708 | https://github.com/SpotlightData/preprocessing/blob/180c6472bc2642afbd7a1ece08d0b0d14968a708/preprocessing/spellcheck.py#L103-L116 | train | 546 |
emirozer/bowshock | bowshock/star.py | search_star | def search_star(star):
'''
It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun.
http://star-api.herokuapp.com/api/v1/stars/Sun
'''
base_url = "http://star-api.herokuapp.com/api/v1/stars/"
if not isinstance(star, str):
raise ValueError("The star arg you provided is not the type of str")
else:
base_url += star
return dispatch_http_get(base_url) | python | def search_star(star):
'''
It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun.
http://star-api.herokuapp.com/api/v1/stars/Sun
'''
base_url = "http://star-api.herokuapp.com/api/v1/stars/"
if not isinstance(star, str):
raise ValueError("The star arg you provided is not the type of str")
else:
base_url += star
return dispatch_http_get(base_url) | [
"def",
"search_star",
"(",
"star",
")",
":",
"base_url",
"=",
"\"http://star-api.herokuapp.com/api/v1/stars/\"",
"if",
"not",
"isinstance",
"(",
"star",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"The star arg you provided is not the type of str\"",
")",
"else",
":",
"base_url",
"+=",
"star",
"return",
"dispatch_http_get",
"(",
"base_url",
")"
] | It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun.
http://star-api.herokuapp.com/api/v1/stars/Sun | [
"It",
"is",
"also",
"possible",
"to",
"query",
"the",
"stars",
"by",
"label",
"here",
"is",
"an",
"example",
"of",
"querying",
"for",
"the",
"star",
"labeled",
"as",
"Sun",
"."
] | 9f5e053f1d54995b833b83616f37c67178c3e840 | https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/star.py#L16-L30 | train | 547 |
emirozer/bowshock | bowshock/star.py | search_exoplanet | def search_exoplanet(exoplanet):
'''
It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com
http://star-api.herokuapp.com/api/v1/exo_planets/11 Com
'''
base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/"
if not isinstance(exoplanet, str):
raise ValueError(
"The exoplanet arg you provided is not the type of str")
else:
base_url += exoplanet
return dispatch_http_get(base_url) | python | def search_exoplanet(exoplanet):
'''
It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com
http://star-api.herokuapp.com/api/v1/exo_planets/11 Com
'''
base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/"
if not isinstance(exoplanet, str):
raise ValueError(
"The exoplanet arg you provided is not the type of str")
else:
base_url += exoplanet
return dispatch_http_get(base_url) | [
"def",
"search_exoplanet",
"(",
"exoplanet",
")",
":",
"base_url",
"=",
"\"http://star-api.herokuapp.com/api/v1/exo_planets/\"",
"if",
"not",
"isinstance",
"(",
"exoplanet",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"The exoplanet arg you provided is not the type of str\"",
")",
"else",
":",
"base_url",
"+=",
"exoplanet",
"return",
"dispatch_http_get",
"(",
"base_url",
")"
] | It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com
http://star-api.herokuapp.com/api/v1/exo_planets/11 Com | [
"It",
"is",
"also",
"possible",
"to",
"query",
"the",
"exoplanets",
"by",
"label",
"here",
"is",
"an",
"example",
"of",
"querying",
"for",
"the",
"exoplanet",
"labeled",
"as",
"11",
"Com"
] | 9f5e053f1d54995b833b83616f37c67178c3e840 | https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/star.py#L43-L58 | train | 548 |
emirozer/bowshock | bowshock/star.py | search_local_galaxies | def search_local_galaxies(galaxy):
'''
It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10
http://star-api.herokuapp.com/api/v1/local_groups/IC 10
'''
base_url = "http://star-api.herokuapp.com/api/v1/local_groups/"
if not isinstance(galaxy, str):
raise ValueError("The galaxy arg you provided is not the type of str")
else:
base_url += galaxy
return dispatch_http_get(base_url) | python | def search_local_galaxies(galaxy):
'''
It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10
http://star-api.herokuapp.com/api/v1/local_groups/IC 10
'''
base_url = "http://star-api.herokuapp.com/api/v1/local_groups/"
if not isinstance(galaxy, str):
raise ValueError("The galaxy arg you provided is not the type of str")
else:
base_url += galaxy
return dispatch_http_get(base_url) | [
"def",
"search_local_galaxies",
"(",
"galaxy",
")",
":",
"base_url",
"=",
"\"http://star-api.herokuapp.com/api/v1/local_groups/\"",
"if",
"not",
"isinstance",
"(",
"galaxy",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"The galaxy arg you provided is not the type of str\"",
")",
"else",
":",
"base_url",
"+=",
"galaxy",
"return",
"dispatch_http_get",
"(",
"base_url",
")"
] | It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10
http://star-api.herokuapp.com/api/v1/local_groups/IC 10 | [
"It",
"is",
"also",
"possible",
"to",
"query",
"the",
"local",
"galaxies",
"by",
"label",
"here",
"is",
"an",
"example",
"of",
"querying",
"for",
"the",
"local",
"galaxy",
"labeled",
"IC",
"10"
] | 9f5e053f1d54995b833b83616f37c67178c3e840 | https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/star.py#L71-L85 | train | 549 |
emirozer/bowshock | bowshock/star.py | search_star_cluster | def search_star_cluster(cluster):
'''
It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59
http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59
'''
base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/"
if not isinstance(cluster, str):
raise ValueError("The cluster arg you provided is not the type of str")
else:
base_url += cluster
return dispatch_http_get(base_url) | python | def search_star_cluster(cluster):
'''
It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59
http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59
'''
base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/"
if not isinstance(cluster, str):
raise ValueError("The cluster arg you provided is not the type of str")
else:
base_url += cluster
return dispatch_http_get(base_url) | [
"def",
"search_star_cluster",
"(",
"cluster",
")",
":",
"base_url",
"=",
"\"http://star-api.herokuapp.com/api/v1/open_cluster/\"",
"if",
"not",
"isinstance",
"(",
"cluster",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"The cluster arg you provided is not the type of str\"",
")",
"else",
":",
"base_url",
"+=",
"cluster",
"return",
"dispatch_http_get",
"(",
"base_url",
")"
] | It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59
http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59 | [
"It",
"is",
"also",
"possible",
"to",
"query",
"the",
"star",
"clusters",
"by",
"label",
"here",
"is",
"an",
"example",
"of",
"querying",
"for",
"the",
"star",
"cluster",
"labeled",
"Berkeley",
"59"
] | 9f5e053f1d54995b833b83616f37c67178c3e840 | https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/star.py#L98-L112 | train | 550 |
hsolbrig/pyjsg | pyjsg/parser_impl/jsg_lexerruleblock_parser.py | JSGLexerRuleBlock.as_python | def as_python(self, name: str) -> str:
""" Return the python representation """
if self._ruleTokens:
pattern = "jsg.JSGPattern(r'{}'.format({}))".\
format(self._rulePattern, ', '.join(['{v}={v}.pattern'.format(v=v) for v in sorted(self._ruleTokens)]))
else:
pattern = "jsg.JSGPattern(r'{}')".format(self._rulePattern)
base_type = self._jsontype.signature_type() if self._jsontype else "jsg.JSGString"
return python_template.format(name=name, base_type=base_type, pattern=pattern) | python | def as_python(self, name: str) -> str:
""" Return the python representation """
if self._ruleTokens:
pattern = "jsg.JSGPattern(r'{}'.format({}))".\
format(self._rulePattern, ', '.join(['{v}={v}.pattern'.format(v=v) for v in sorted(self._ruleTokens)]))
else:
pattern = "jsg.JSGPattern(r'{}')".format(self._rulePattern)
base_type = self._jsontype.signature_type() if self._jsontype else "jsg.JSGString"
return python_template.format(name=name, base_type=base_type, pattern=pattern) | [
"def",
"as_python",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"str",
":",
"if",
"self",
".",
"_ruleTokens",
":",
"pattern",
"=",
"\"jsg.JSGPattern(r'{}'.format({}))\"",
".",
"format",
"(",
"self",
".",
"_rulePattern",
",",
"', '",
".",
"join",
"(",
"[",
"'{v}={v}.pattern'",
".",
"format",
"(",
"v",
"=",
"v",
")",
"for",
"v",
"in",
"sorted",
"(",
"self",
".",
"_ruleTokens",
")",
"]",
")",
")",
"else",
":",
"pattern",
"=",
"\"jsg.JSGPattern(r'{}')\"",
".",
"format",
"(",
"self",
".",
"_rulePattern",
")",
"base_type",
"=",
"self",
".",
"_jsontype",
".",
"signature_type",
"(",
")",
"if",
"self",
".",
"_jsontype",
"else",
"\"jsg.JSGString\"",
"return",
"python_template",
".",
"format",
"(",
"name",
"=",
"name",
",",
"base_type",
"=",
"base_type",
",",
"pattern",
"=",
"pattern",
")"
] | Return the python representation | [
"Return",
"the",
"python",
"representation"
] | 9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7 | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/parser_impl/jsg_lexerruleblock_parser.py#L59-L67 | train | 551 |
OpenTreeOfLife/peyotl | peyotl/utility/str_util.py | increment_slug | def increment_slug(s):
"""Generate next slug for a series.
Some docstore types will use slugs (see above) as document ids. To
support unique ids, we'll serialize them as follows:
TestUserA/my-test
TestUserA/my-test-2
TestUserA/my-test-3
...
"""
slug_parts = s.split('-')
# advance (or add) the serial counter on the end of this slug
# noinspection PyBroadException
try:
# if it's an integer, increment it
slug_parts[-1] = str(1 + int(slug_parts[-1]))
except:
# there's no counter! add one now
slug_parts.append('2')
return '-'.join(slug_parts) | python | def increment_slug(s):
"""Generate next slug for a series.
Some docstore types will use slugs (see above) as document ids. To
support unique ids, we'll serialize them as follows:
TestUserA/my-test
TestUserA/my-test-2
TestUserA/my-test-3
...
"""
slug_parts = s.split('-')
# advance (or add) the serial counter on the end of this slug
# noinspection PyBroadException
try:
# if it's an integer, increment it
slug_parts[-1] = str(1 + int(slug_parts[-1]))
except:
# there's no counter! add one now
slug_parts.append('2')
return '-'.join(slug_parts) | [
"def",
"increment_slug",
"(",
"s",
")",
":",
"slug_parts",
"=",
"s",
".",
"split",
"(",
"'-'",
")",
"# advance (or add) the serial counter on the end of this slug",
"# noinspection PyBroadException",
"try",
":",
"# if it's an integer, increment it",
"slug_parts",
"[",
"-",
"1",
"]",
"=",
"str",
"(",
"1",
"+",
"int",
"(",
"slug_parts",
"[",
"-",
"1",
"]",
")",
")",
"except",
":",
"# there's no counter! add one now",
"slug_parts",
".",
"append",
"(",
"'2'",
")",
"return",
"'-'",
".",
"join",
"(",
"slug_parts",
")"
] | Generate next slug for a series.
Some docstore types will use slugs (see above) as document ids. To
support unique ids, we'll serialize them as follows:
TestUserA/my-test
TestUserA/my-test-2
TestUserA/my-test-3
... | [
"Generate",
"next",
"slug",
"for",
"a",
"series",
"."
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/utility/str_util.py#L82-L101 | train | 552 |
OpenTreeOfLife/peyotl | peyotl/utility/str_util.py | underscored2camel_case | def underscored2camel_case(v):
"""converts ott_id to ottId."""
vlist = v.split('_')
c = []
for n, el in enumerate(vlist):
if el:
if n == 0:
c.append(el)
else:
c.extend([el[0].upper(), el[1:]])
return ''.join(c) | python | def underscored2camel_case(v):
"""converts ott_id to ottId."""
vlist = v.split('_')
c = []
for n, el in enumerate(vlist):
if el:
if n == 0:
c.append(el)
else:
c.extend([el[0].upper(), el[1:]])
return ''.join(c) | [
"def",
"underscored2camel_case",
"(",
"v",
")",
":",
"vlist",
"=",
"v",
".",
"split",
"(",
"'_'",
")",
"c",
"=",
"[",
"]",
"for",
"n",
",",
"el",
"in",
"enumerate",
"(",
"vlist",
")",
":",
"if",
"el",
":",
"if",
"n",
"==",
"0",
":",
"c",
".",
"append",
"(",
"el",
")",
"else",
":",
"c",
".",
"extend",
"(",
"[",
"el",
"[",
"0",
"]",
".",
"upper",
"(",
")",
",",
"el",
"[",
"1",
":",
"]",
"]",
")",
"return",
"''",
".",
"join",
"(",
"c",
")"
] | converts ott_id to ottId. | [
"converts",
"ott_id",
"to",
"ottId",
"."
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/utility/str_util.py#L104-L114 | train | 553 |
hsolbrig/pyjsg | pyjsg/jsglib/jsg_context.py | JSGContext.unvalidated_parm | def unvalidated_parm(self, parm: str) -> bool:
"""Return true if the pair name should be ignored
:param parm: string part of pair string:value
:return: True if it should be accepted
"""
return parm.startswith("_") or parm == self.TYPE or parm in self.IGNORE or \
(self.JSON_LD and parm.startswith('@')) | python | def unvalidated_parm(self, parm: str) -> bool:
"""Return true if the pair name should be ignored
:param parm: string part of pair string:value
:return: True if it should be accepted
"""
return parm.startswith("_") or parm == self.TYPE or parm in self.IGNORE or \
(self.JSON_LD and parm.startswith('@')) | [
"def",
"unvalidated_parm",
"(",
"self",
",",
"parm",
":",
"str",
")",
"->",
"bool",
":",
"return",
"parm",
".",
"startswith",
"(",
"\"_\"",
")",
"or",
"parm",
"==",
"self",
".",
"TYPE",
"or",
"parm",
"in",
"self",
".",
"IGNORE",
"or",
"(",
"self",
".",
"JSON_LD",
"and",
"parm",
".",
"startswith",
"(",
"'@'",
")",
")"
] | Return true if the pair name should be ignored
:param parm: string part of pair string:value
:return: True if it should be accepted | [
"Return",
"true",
"if",
"the",
"pair",
"name",
"should",
"be",
"ignored"
] | 9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7 | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/jsglib/jsg_context.py#L24-L31 | train | 554 |
palantir/typedjsonrpc | typedjsonrpc/registry.py | Registry.dispatch | def dispatch(self, request):
"""Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
.. versionadded:: 0.1.0
"""
def _wrapped():
messages = self._get_request_messages(request)
results = [self._dispatch_and_handle_errors(message) for message in messages]
non_notification_results = [x for x in results if x is not None]
if len(non_notification_results) == 0:
return None
elif len(messages) == 1:
return non_notification_results[0]
else:
return non_notification_results
result, _ = self._handle_exceptions(_wrapped)
if result is not None:
return self._encode_complete_result(result) | python | def dispatch(self, request):
"""Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
.. versionadded:: 0.1.0
"""
def _wrapped():
messages = self._get_request_messages(request)
results = [self._dispatch_and_handle_errors(message) for message in messages]
non_notification_results = [x for x in results if x is not None]
if len(non_notification_results) == 0:
return None
elif len(messages) == 1:
return non_notification_results[0]
else:
return non_notification_results
result, _ = self._handle_exceptions(_wrapped)
if result is not None:
return self._encode_complete_result(result) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
")",
":",
"def",
"_wrapped",
"(",
")",
":",
"messages",
"=",
"self",
".",
"_get_request_messages",
"(",
"request",
")",
"results",
"=",
"[",
"self",
".",
"_dispatch_and_handle_errors",
"(",
"message",
")",
"for",
"message",
"in",
"messages",
"]",
"non_notification_results",
"=",
"[",
"x",
"for",
"x",
"in",
"results",
"if",
"x",
"is",
"not",
"None",
"]",
"if",
"len",
"(",
"non_notification_results",
")",
"==",
"0",
":",
"return",
"None",
"elif",
"len",
"(",
"messages",
")",
"==",
"1",
":",
"return",
"non_notification_results",
"[",
"0",
"]",
"else",
":",
"return",
"non_notification_results",
"result",
",",
"_",
"=",
"self",
".",
"_handle_exceptions",
"(",
"_wrapped",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_encode_complete_result",
"(",
"result",
")"
] | Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
.. versionadded:: 0.1.0 | [
"Takes",
"a",
"request",
"and",
"dispatches",
"its",
"data",
"to",
"a",
"jsonrpc",
"method",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/registry.py#L95-L118 | train | 555 |
palantir/typedjsonrpc | typedjsonrpc/registry.py | Registry.register | def register(self, name, method, method_signature=None):
"""Registers a method with a given name and signature.
:param name: The name used to register the method
:type name: str
:param method: The method to register
:type method: function
:param method_signature: The method signature for the given function
:type method_signature: MethodSignature | None
.. versionadded:: 0.1.0
"""
if inspect.ismethod(method):
raise Exception("typedjsonrpc does not support making class methods into endpoints")
self._name_to_method_info[name] = MethodInfo(name, method, method_signature) | python | def register(self, name, method, method_signature=None):
"""Registers a method with a given name and signature.
:param name: The name used to register the method
:type name: str
:param method: The method to register
:type method: function
:param method_signature: The method signature for the given function
:type method_signature: MethodSignature | None
.. versionadded:: 0.1.0
"""
if inspect.ismethod(method):
raise Exception("typedjsonrpc does not support making class methods into endpoints")
self._name_to_method_info[name] = MethodInfo(name, method, method_signature) | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"method",
",",
"method_signature",
"=",
"None",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"method",
")",
":",
"raise",
"Exception",
"(",
"\"typedjsonrpc does not support making class methods into endpoints\"",
")",
"self",
".",
"_name_to_method_info",
"[",
"name",
"]",
"=",
"MethodInfo",
"(",
"name",
",",
"method",
",",
"method_signature",
")"
] | Registers a method with a given name and signature.
:param name: The name used to register the method
:type name: str
:param method: The method to register
:type method: function
:param method_signature: The method signature for the given function
:type method_signature: MethodSignature | None
.. versionadded:: 0.1.0 | [
"Registers",
"a",
"method",
"with",
"a",
"given",
"name",
"and",
"signature",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/registry.py#L218-L232 | train | 556 |
palantir/typedjsonrpc | typedjsonrpc/registry.py | Registry.method | def method(self, returns, **parameter_types):
"""Syntactic sugar for registering a method
Example:
>>> registry = Registry()
>>> @registry.method(returns=int, x=int, y=int)
... def add(x, y):
... return x + y
:param returns: The method's return type
:type returns: type
:param parameter_types: The types of the method's parameters
:type parameter_types: dict[str, type]
.. versionadded:: 0.1.0
"""
@wrapt.decorator
def type_check_wrapper(method, instance, args, kwargs):
"""Wraps a method so that it is type-checked.
:param method: The method to wrap
:type method: (T) -> U
:return: The result of calling the method with the given parameters
:rtype: U
"""
if instance is not None:
raise Exception("Instance shouldn't be set.")
parameter_names = inspect.getargspec(method).args # pylint: disable=deprecated-method
defaults = inspect.getargspec(method).defaults # pylint: disable=deprecated-method
parameters = self._collect_parameters(parameter_names, args, kwargs, defaults)
parameter_checker.check_types(parameters, parameter_types, self._strict_floats)
result = method(*args, **kwargs)
parameter_checker.check_return_type(result, returns, self._strict_floats)
return result
def register_method(method):
"""Registers a method with its fully qualified name.
:param method: The method to register
:type method: function
:return: The original method wrapped into a type-checker
:rtype: function
"""
parameter_names = inspect.getargspec(method).args # pylint: disable=deprecated-method
parameter_checker.check_type_declaration(parameter_names, parameter_types)
wrapped_method = type_check_wrapper(method, None, None, None)
fully_qualified_name = "{}.{}".format(method.__module__, method.__name__)
self.register(fully_qualified_name, wrapped_method,
MethodSignature.create(parameter_names, parameter_types, returns))
return wrapped_method
return register_method | python | def method(self, returns, **parameter_types):
"""Syntactic sugar for registering a method
Example:
>>> registry = Registry()
>>> @registry.method(returns=int, x=int, y=int)
... def add(x, y):
... return x + y
:param returns: The method's return type
:type returns: type
:param parameter_types: The types of the method's parameters
:type parameter_types: dict[str, type]
.. versionadded:: 0.1.0
"""
@wrapt.decorator
def type_check_wrapper(method, instance, args, kwargs):
"""Wraps a method so that it is type-checked.
:param method: The method to wrap
:type method: (T) -> U
:return: The result of calling the method with the given parameters
:rtype: U
"""
if instance is not None:
raise Exception("Instance shouldn't be set.")
parameter_names = inspect.getargspec(method).args # pylint: disable=deprecated-method
defaults = inspect.getargspec(method).defaults # pylint: disable=deprecated-method
parameters = self._collect_parameters(parameter_names, args, kwargs, defaults)
parameter_checker.check_types(parameters, parameter_types, self._strict_floats)
result = method(*args, **kwargs)
parameter_checker.check_return_type(result, returns, self._strict_floats)
return result
def register_method(method):
"""Registers a method with its fully qualified name.
:param method: The method to register
:type method: function
:return: The original method wrapped into a type-checker
:rtype: function
"""
parameter_names = inspect.getargspec(method).args # pylint: disable=deprecated-method
parameter_checker.check_type_declaration(parameter_names, parameter_types)
wrapped_method = type_check_wrapper(method, None, None, None)
fully_qualified_name = "{}.{}".format(method.__module__, method.__name__)
self.register(fully_qualified_name, wrapped_method,
MethodSignature.create(parameter_names, parameter_types, returns))
return wrapped_method
return register_method | [
"def",
"method",
"(",
"self",
",",
"returns",
",",
"*",
"*",
"parameter_types",
")",
":",
"@",
"wrapt",
".",
"decorator",
"def",
"type_check_wrapper",
"(",
"method",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"\"\"\"Wraps a method so that it is type-checked.\n\n :param method: The method to wrap\n :type method: (T) -> U\n :return: The result of calling the method with the given parameters\n :rtype: U\n \"\"\"",
"if",
"instance",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"Instance shouldn't be set.\"",
")",
"parameter_names",
"=",
"inspect",
".",
"getargspec",
"(",
"method",
")",
".",
"args",
"# pylint: disable=deprecated-method",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"method",
")",
".",
"defaults",
"# pylint: disable=deprecated-method",
"parameters",
"=",
"self",
".",
"_collect_parameters",
"(",
"parameter_names",
",",
"args",
",",
"kwargs",
",",
"defaults",
")",
"parameter_checker",
".",
"check_types",
"(",
"parameters",
",",
"parameter_types",
",",
"self",
".",
"_strict_floats",
")",
"result",
"=",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"parameter_checker",
".",
"check_return_type",
"(",
"result",
",",
"returns",
",",
"self",
".",
"_strict_floats",
")",
"return",
"result",
"def",
"register_method",
"(",
"method",
")",
":",
"\"\"\"Registers a method with its fully qualified name.\n\n :param method: The method to register\n :type method: function\n :return: The original method wrapped into a type-checker\n :rtype: function\n \"\"\"",
"parameter_names",
"=",
"inspect",
".",
"getargspec",
"(",
"method",
")",
".",
"args",
"# pylint: disable=deprecated-method",
"parameter_checker",
".",
"check_type_declaration",
"(",
"parameter_names",
",",
"parameter_types",
")",
"wrapped_method",
"=",
"type_check_wrapper",
"(",
"method",
",",
"None",
",",
"None",
",",
"None",
")",
"fully_qualified_name",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"method",
".",
"__module__",
",",
"method",
".",
"__name__",
")",
"self",
".",
"register",
"(",
"fully_qualified_name",
",",
"wrapped_method",
",",
"MethodSignature",
".",
"create",
"(",
"parameter_names",
",",
"parameter_types",
",",
"returns",
")",
")",
"return",
"wrapped_method",
"return",
"register_method"
] | Syntactic sugar for registering a method
Example:
>>> registry = Registry()
>>> @registry.method(returns=int, x=int, y=int)
... def add(x, y):
... return x + y
:param returns: The method's return type
:type returns: type
:param parameter_types: The types of the method's parameters
:type parameter_types: dict[str, type]
.. versionadded:: 0.1.0 | [
"Syntactic",
"sugar",
"for",
"registering",
"a",
"method"
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/registry.py#L234-L291 | train | 557 |
palantir/typedjsonrpc | typedjsonrpc/registry.py | Registry._collect_parameters | def _collect_parameters(parameter_names, args, kwargs, defaults):
"""Creates a dictionary mapping parameters names to their values in the method call.
:param parameter_names: The method's parameter names
:type parameter_names: list[string]
:param args: *args passed into the method
:type args: list[object]
:param kwargs: **kwargs passed into the method
:type kwargs: dict[string, object]
:param defaults: The method's default values
:type defaults: list[object]
:return: Dictionary mapping parameter names to values
:rtype: dict[string, object]
"""
parameters = {}
if defaults is not None:
zipped_defaults = zip(reversed(parameter_names), reversed(defaults))
for name, default in zipped_defaults:
parameters[name] = default
for name, value in zip(parameter_names, args):
parameters[name] = value
for name, value in kwargs.items():
parameters[name] = value
return parameters | python | def _collect_parameters(parameter_names, args, kwargs, defaults):
"""Creates a dictionary mapping parameters names to their values in the method call.
:param parameter_names: The method's parameter names
:type parameter_names: list[string]
:param args: *args passed into the method
:type args: list[object]
:param kwargs: **kwargs passed into the method
:type kwargs: dict[string, object]
:param defaults: The method's default values
:type defaults: list[object]
:return: Dictionary mapping parameter names to values
:rtype: dict[string, object]
"""
parameters = {}
if defaults is not None:
zipped_defaults = zip(reversed(parameter_names), reversed(defaults))
for name, default in zipped_defaults:
parameters[name] = default
for name, value in zip(parameter_names, args):
parameters[name] = value
for name, value in kwargs.items():
parameters[name] = value
return parameters | [
"def",
"_collect_parameters",
"(",
"parameter_names",
",",
"args",
",",
"kwargs",
",",
"defaults",
")",
":",
"parameters",
"=",
"{",
"}",
"if",
"defaults",
"is",
"not",
"None",
":",
"zipped_defaults",
"=",
"zip",
"(",
"reversed",
"(",
"parameter_names",
")",
",",
"reversed",
"(",
"defaults",
")",
")",
"for",
"name",
",",
"default",
"in",
"zipped_defaults",
":",
"parameters",
"[",
"name",
"]",
"=",
"default",
"for",
"name",
",",
"value",
"in",
"zip",
"(",
"parameter_names",
",",
"args",
")",
":",
"parameters",
"[",
"name",
"]",
"=",
"value",
"for",
"name",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"parameters",
"[",
"name",
"]",
"=",
"value",
"return",
"parameters"
] | Creates a dictionary mapping parameters names to their values in the method call.
:param parameter_names: The method's parameter names
:type parameter_names: list[string]
:param args: *args passed into the method
:type args: list[object]
:param kwargs: **kwargs passed into the method
:type kwargs: dict[string, object]
:param defaults: The method's default values
:type defaults: list[object]
:return: Dictionary mapping parameter names to values
:rtype: dict[string, object] | [
"Creates",
"a",
"dictionary",
"mapping",
"parameters",
"names",
"to",
"their",
"values",
"in",
"the",
"method",
"call",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/registry.py#L294-L317 | train | 558 |
palantir/typedjsonrpc | typedjsonrpc/registry.py | Registry._get_request_messages | def _get_request_messages(self, request):
"""Parses the request as a json message.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: The parsed json object
:rtype: dict[str, object]
"""
data = request.get_data(as_text=True)
try:
msg = self.json_decoder.decode(data)
except Exception:
raise ParseError("Could not parse request data '{}'".format(data))
if isinstance(msg, list):
return msg
else:
return [msg] | python | def _get_request_messages(self, request):
"""Parses the request as a json message.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: The parsed json object
:rtype: dict[str, object]
"""
data = request.get_data(as_text=True)
try:
msg = self.json_decoder.decode(data)
except Exception:
raise ParseError("Could not parse request data '{}'".format(data))
if isinstance(msg, list):
return msg
else:
return [msg] | [
"def",
"_get_request_messages",
"(",
"self",
",",
"request",
")",
":",
"data",
"=",
"request",
".",
"get_data",
"(",
"as_text",
"=",
"True",
")",
"try",
":",
"msg",
"=",
"self",
".",
"json_decoder",
".",
"decode",
"(",
"data",
")",
"except",
"Exception",
":",
"raise",
"ParseError",
"(",
"\"Could not parse request data '{}'\"",
".",
"format",
"(",
"data",
")",
")",
"if",
"isinstance",
"(",
"msg",
",",
"list",
")",
":",
"return",
"msg",
"else",
":",
"return",
"[",
"msg",
"]"
] | Parses the request as a json message.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: The parsed json object
:rtype: dict[str, object] | [
"Parses",
"the",
"request",
"as",
"a",
"json",
"message",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/registry.py#L332-L348 | train | 559 |
palantir/typedjsonrpc | typedjsonrpc/registry.py | Registry._check_request | def _check_request(self, msg):
"""Checks that the request json is well-formed.
:param msg: The request's json data
:type msg: dict[str, object]
"""
if "jsonrpc" not in msg:
raise InvalidRequestError("'\"jsonrpc\": \"2.0\"' must be included.")
if msg["jsonrpc"] != "2.0":
raise InvalidRequestError("'jsonrpc' must be exactly the string '2.0', but it was '{}'."
.format(msg["jsonrpc"]))
if "method" not in msg:
raise InvalidRequestError("No method specified.")
if "id" in msg:
if msg["id"] is None:
raise InvalidRequestError("typedjsonrpc does not allow id to be None.")
if isinstance(msg["id"], float):
raise InvalidRequestError("typedjsonrpc does not support float ids.")
if not isinstance(msg["id"], (six.string_types, six.integer_types)):
raise InvalidRequestError("id must be a string or integer; '{}' is of type {}."
.format(msg["id"], type(msg["id"])))
if msg["method"] not in self._name_to_method_info:
raise MethodNotFoundError("Could not find method '{}'.".format(msg["method"])) | python | def _check_request(self, msg):
"""Checks that the request json is well-formed.
:param msg: The request's json data
:type msg: dict[str, object]
"""
if "jsonrpc" not in msg:
raise InvalidRequestError("'\"jsonrpc\": \"2.0\"' must be included.")
if msg["jsonrpc"] != "2.0":
raise InvalidRequestError("'jsonrpc' must be exactly the string '2.0', but it was '{}'."
.format(msg["jsonrpc"]))
if "method" not in msg:
raise InvalidRequestError("No method specified.")
if "id" in msg:
if msg["id"] is None:
raise InvalidRequestError("typedjsonrpc does not allow id to be None.")
if isinstance(msg["id"], float):
raise InvalidRequestError("typedjsonrpc does not support float ids.")
if not isinstance(msg["id"], (six.string_types, six.integer_types)):
raise InvalidRequestError("id must be a string or integer; '{}' is of type {}."
.format(msg["id"], type(msg["id"])))
if msg["method"] not in self._name_to_method_info:
raise MethodNotFoundError("Could not find method '{}'.".format(msg["method"])) | [
"def",
"_check_request",
"(",
"self",
",",
"msg",
")",
":",
"if",
"\"jsonrpc\"",
"not",
"in",
"msg",
":",
"raise",
"InvalidRequestError",
"(",
"\"'\\\"jsonrpc\\\": \\\"2.0\\\"' must be included.\"",
")",
"if",
"msg",
"[",
"\"jsonrpc\"",
"]",
"!=",
"\"2.0\"",
":",
"raise",
"InvalidRequestError",
"(",
"\"'jsonrpc' must be exactly the string '2.0', but it was '{}'.\"",
".",
"format",
"(",
"msg",
"[",
"\"jsonrpc\"",
"]",
")",
")",
"if",
"\"method\"",
"not",
"in",
"msg",
":",
"raise",
"InvalidRequestError",
"(",
"\"No method specified.\"",
")",
"if",
"\"id\"",
"in",
"msg",
":",
"if",
"msg",
"[",
"\"id\"",
"]",
"is",
"None",
":",
"raise",
"InvalidRequestError",
"(",
"\"typedjsonrpc does not allow id to be None.\"",
")",
"if",
"isinstance",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"float",
")",
":",
"raise",
"InvalidRequestError",
"(",
"\"typedjsonrpc does not support float ids.\"",
")",
"if",
"not",
"isinstance",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"(",
"six",
".",
"string_types",
",",
"six",
".",
"integer_types",
")",
")",
":",
"raise",
"InvalidRequestError",
"(",
"\"id must be a string or integer; '{}' is of type {}.\"",
".",
"format",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"type",
"(",
"msg",
"[",
"\"id\"",
"]",
")",
")",
")",
"if",
"msg",
"[",
"\"method\"",
"]",
"not",
"in",
"self",
".",
"_name_to_method_info",
":",
"raise",
"MethodNotFoundError",
"(",
"\"Could not find method '{}'.\"",
".",
"format",
"(",
"msg",
"[",
"\"method\"",
"]",
")",
")"
] | Checks that the request json is well-formed.
:param msg: The request's json data
:type msg: dict[str, object] | [
"Checks",
"that",
"the",
"request",
"json",
"is",
"well",
"-",
"formed",
"."
] | 274218fcd236ff9643506caa629029c9ba25a0fb | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/registry.py#L350-L372 | train | 560 |
inveniosoftware/invenio-communities | invenio_communities/utils.py | render_template_to_string | def render_template_to_string(input, _from_string=False, **context):
"""Render a template from the template folder with the given context.
Code based on
`<https://github.com/mitsuhiko/flask/blob/master/flask/templating.py>`_
:param input: the string template, or name of the template to be
rendered, or an iterable with template names
the first one existing will be rendered
:param context: the variables that should be available in the
context of the template.
:return: a string
"""
if _from_string:
template = current_app.jinja_env.from_string(input)
else:
template = current_app.jinja_env.get_or_select_template(input)
return template.render(context) | python | def render_template_to_string(input, _from_string=False, **context):
"""Render a template from the template folder with the given context.
Code based on
`<https://github.com/mitsuhiko/flask/blob/master/flask/templating.py>`_
:param input: the string template, or name of the template to be
rendered, or an iterable with template names
the first one existing will be rendered
:param context: the variables that should be available in the
context of the template.
:return: a string
"""
if _from_string:
template = current_app.jinja_env.from_string(input)
else:
template = current_app.jinja_env.get_or_select_template(input)
return template.render(context) | [
"def",
"render_template_to_string",
"(",
"input",
",",
"_from_string",
"=",
"False",
",",
"*",
"*",
"context",
")",
":",
"if",
"_from_string",
":",
"template",
"=",
"current_app",
".",
"jinja_env",
".",
"from_string",
"(",
"input",
")",
"else",
":",
"template",
"=",
"current_app",
".",
"jinja_env",
".",
"get_or_select_template",
"(",
"input",
")",
"return",
"template",
".",
"render",
"(",
"context",
")"
] | Render a template from the template folder with the given context.
Code based on
`<https://github.com/mitsuhiko/flask/blob/master/flask/templating.py>`_
:param input: the string template, or name of the template to be
rendered, or an iterable with template names
the first one existing will be rendered
:param context: the variables that should be available in the
context of the template.
:return: a string | [
"Render",
"a",
"template",
"from",
"the",
"template",
"folder",
"with",
"the",
"given",
"context",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/utils.py#L79-L95 | train | 561 |
inveniosoftware/invenio-communities | invenio_communities/utils.py | save_and_validate_logo | def save_and_validate_logo(logo_stream, logo_filename, community_id):
"""Validate if communities logo is in limit size and save it."""
cfg = current_app.config
logos_bucket_id = cfg['COMMUNITIES_BUCKET_UUID']
logo_max_size = cfg['COMMUNITIES_LOGO_MAX_SIZE']
logos_bucket = Bucket.query.get(logos_bucket_id)
ext = os.path.splitext(logo_filename)[1]
ext = ext[1:] if ext.startswith('.') else ext
logo_stream.seek(SEEK_SET, SEEK_END) # Seek from beginning to end
logo_size = logo_stream.tell()
if logo_size > logo_max_size:
return None
if ext in cfg['COMMUNITIES_LOGO_EXTENSIONS']:
key = "{0}/logo.{1}".format(community_id, ext)
logo_stream.seek(0) # Rewind the stream to the beginning
ObjectVersion.create(logos_bucket, key, stream=logo_stream,
size=logo_size)
return ext
else:
return None | python | def save_and_validate_logo(logo_stream, logo_filename, community_id):
"""Validate if communities logo is in limit size and save it."""
cfg = current_app.config
logos_bucket_id = cfg['COMMUNITIES_BUCKET_UUID']
logo_max_size = cfg['COMMUNITIES_LOGO_MAX_SIZE']
logos_bucket = Bucket.query.get(logos_bucket_id)
ext = os.path.splitext(logo_filename)[1]
ext = ext[1:] if ext.startswith('.') else ext
logo_stream.seek(SEEK_SET, SEEK_END) # Seek from beginning to end
logo_size = logo_stream.tell()
if logo_size > logo_max_size:
return None
if ext in cfg['COMMUNITIES_LOGO_EXTENSIONS']:
key = "{0}/logo.{1}".format(community_id, ext)
logo_stream.seek(0) # Rewind the stream to the beginning
ObjectVersion.create(logos_bucket, key, stream=logo_stream,
size=logo_size)
return ext
else:
return None | [
"def",
"save_and_validate_logo",
"(",
"logo_stream",
",",
"logo_filename",
",",
"community_id",
")",
":",
"cfg",
"=",
"current_app",
".",
"config",
"logos_bucket_id",
"=",
"cfg",
"[",
"'COMMUNITIES_BUCKET_UUID'",
"]",
"logo_max_size",
"=",
"cfg",
"[",
"'COMMUNITIES_LOGO_MAX_SIZE'",
"]",
"logos_bucket",
"=",
"Bucket",
".",
"query",
".",
"get",
"(",
"logos_bucket_id",
")",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"logo_filename",
")",
"[",
"1",
"]",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"if",
"ext",
".",
"startswith",
"(",
"'.'",
")",
"else",
"ext",
"logo_stream",
".",
"seek",
"(",
"SEEK_SET",
",",
"SEEK_END",
")",
"# Seek from beginning to end",
"logo_size",
"=",
"logo_stream",
".",
"tell",
"(",
")",
"if",
"logo_size",
">",
"logo_max_size",
":",
"return",
"None",
"if",
"ext",
"in",
"cfg",
"[",
"'COMMUNITIES_LOGO_EXTENSIONS'",
"]",
":",
"key",
"=",
"\"{0}/logo.{1}\"",
".",
"format",
"(",
"community_id",
",",
"ext",
")",
"logo_stream",
".",
"seek",
"(",
"0",
")",
"# Rewind the stream to the beginning",
"ObjectVersion",
".",
"create",
"(",
"logos_bucket",
",",
"key",
",",
"stream",
"=",
"logo_stream",
",",
"size",
"=",
"logo_size",
")",
"return",
"ext",
"else",
":",
"return",
"None"
] | Validate if communities logo is in limit size and save it. | [
"Validate",
"if",
"communities",
"logo",
"is",
"in",
"limit",
"size",
"and",
"save",
"it",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/utils.py#L98-L120 | train | 562 |
inveniosoftware/invenio-communities | invenio_communities/utils.py | initialize_communities_bucket | def initialize_communities_bucket():
"""Initialize the communities file bucket.
:raises: `invenio_files_rest.errors.FilesException`
"""
bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID'])
if Bucket.query.get(bucket_id):
raise FilesException("Bucket with UUID {} already exists.".format(
bucket_id))
else:
storage_class = current_app.config['FILES_REST_DEFAULT_STORAGE_CLASS']
location = Location.get_default()
bucket = Bucket(id=bucket_id,
location=location,
default_storage_class=storage_class)
db.session.add(bucket)
db.session.commit() | python | def initialize_communities_bucket():
"""Initialize the communities file bucket.
:raises: `invenio_files_rest.errors.FilesException`
"""
bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID'])
if Bucket.query.get(bucket_id):
raise FilesException("Bucket with UUID {} already exists.".format(
bucket_id))
else:
storage_class = current_app.config['FILES_REST_DEFAULT_STORAGE_CLASS']
location = Location.get_default()
bucket = Bucket(id=bucket_id,
location=location,
default_storage_class=storage_class)
db.session.add(bucket)
db.session.commit() | [
"def",
"initialize_communities_bucket",
"(",
")",
":",
"bucket_id",
"=",
"UUID",
"(",
"current_app",
".",
"config",
"[",
"'COMMUNITIES_BUCKET_UUID'",
"]",
")",
"if",
"Bucket",
".",
"query",
".",
"get",
"(",
"bucket_id",
")",
":",
"raise",
"FilesException",
"(",
"\"Bucket with UUID {} already exists.\"",
".",
"format",
"(",
"bucket_id",
")",
")",
"else",
":",
"storage_class",
"=",
"current_app",
".",
"config",
"[",
"'FILES_REST_DEFAULT_STORAGE_CLASS'",
"]",
"location",
"=",
"Location",
".",
"get_default",
"(",
")",
"bucket",
"=",
"Bucket",
"(",
"id",
"=",
"bucket_id",
",",
"location",
"=",
"location",
",",
"default_storage_class",
"=",
"storage_class",
")",
"db",
".",
"session",
".",
"add",
"(",
"bucket",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] | Initialize the communities file bucket.
:raises: `invenio_files_rest.errors.FilesException` | [
"Initialize",
"the",
"communities",
"file",
"bucket",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/utils.py#L123-L140 | train | 563 |
inveniosoftware/invenio-communities | invenio_communities/utils.py | format_request_email_templ | def format_request_email_templ(increq, template, **ctx):
"""Format the email message element for inclusion request notification.
Formats the message according to the provided template file, using
some default fields from 'increq' object as default context.
Arbitrary context can be provided as keywords ('ctx'), and those will
not be overwritten by the fields from 'increq' object.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param template: relative path to jinja template.
:type template: str
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Formatted message.
:rtype: str
"""
# Add minimal information to the contex (without overwriting).
curate_link = '{site_url}/communities/{id}/curate/'.format(
site_url=current_app.config['THEME_SITEURL'],
id=increq.community.id)
min_ctx = dict(
record=Record.get_record(increq.record.id),
requester=increq.user,
community=increq.community,
curate_link=curate_link,
)
for k, v in min_ctx.items():
if k not in ctx:
ctx[k] = v
msg_element = render_template_to_string(template, **ctx)
return msg_element | python | def format_request_email_templ(increq, template, **ctx):
"""Format the email message element for inclusion request notification.
Formats the message according to the provided template file, using
some default fields from 'increq' object as default context.
Arbitrary context can be provided as keywords ('ctx'), and those will
not be overwritten by the fields from 'increq' object.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param template: relative path to jinja template.
:type template: str
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Formatted message.
:rtype: str
"""
# Add minimal information to the contex (without overwriting).
curate_link = '{site_url}/communities/{id}/curate/'.format(
site_url=current_app.config['THEME_SITEURL'],
id=increq.community.id)
min_ctx = dict(
record=Record.get_record(increq.record.id),
requester=increq.user,
community=increq.community,
curate_link=curate_link,
)
for k, v in min_ctx.items():
if k not in ctx:
ctx[k] = v
msg_element = render_template_to_string(template, **ctx)
return msg_element | [
"def",
"format_request_email_templ",
"(",
"increq",
",",
"template",
",",
"*",
"*",
"ctx",
")",
":",
"# Add minimal information to the contex (without overwriting).",
"curate_link",
"=",
"'{site_url}/communities/{id}/curate/'",
".",
"format",
"(",
"site_url",
"=",
"current_app",
".",
"config",
"[",
"'THEME_SITEURL'",
"]",
",",
"id",
"=",
"increq",
".",
"community",
".",
"id",
")",
"min_ctx",
"=",
"dict",
"(",
"record",
"=",
"Record",
".",
"get_record",
"(",
"increq",
".",
"record",
".",
"id",
")",
",",
"requester",
"=",
"increq",
".",
"user",
",",
"community",
"=",
"increq",
".",
"community",
",",
"curate_link",
"=",
"curate_link",
",",
")",
"for",
"k",
",",
"v",
"in",
"min_ctx",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"ctx",
":",
"ctx",
"[",
"k",
"]",
"=",
"v",
"msg_element",
"=",
"render_template_to_string",
"(",
"template",
",",
"*",
"*",
"ctx",
")",
"return",
"msg_element"
] | Format the email message element for inclusion request notification.
Formats the message according to the provided template file, using
some default fields from 'increq' object as default context.
Arbitrary context can be provided as keywords ('ctx'), and those will
not be overwritten by the fields from 'increq' object.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param template: relative path to jinja template.
:type template: str
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Formatted message.
:rtype: str | [
"Format",
"the",
"email",
"message",
"element",
"for",
"inclusion",
"request",
"notification",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/utils.py#L143-L176 | train | 564 |
inveniosoftware/invenio-communities | invenio_communities/utils.py | format_request_email_title | def format_request_email_title(increq, **ctx):
"""Format the email message title for inclusion request notification.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Email message title.
:rtype: str
"""
template = current_app.config["COMMUNITIES_REQUEST_EMAIL_TITLE_TEMPLATE"],
return format_request_email_templ(increq, template, **ctx) | python | def format_request_email_title(increq, **ctx):
"""Format the email message title for inclusion request notification.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Email message title.
:rtype: str
"""
template = current_app.config["COMMUNITIES_REQUEST_EMAIL_TITLE_TEMPLATE"],
return format_request_email_templ(increq, template, **ctx) | [
"def",
"format_request_email_title",
"(",
"increq",
",",
"*",
"*",
"ctx",
")",
":",
"template",
"=",
"current_app",
".",
"config",
"[",
"\"COMMUNITIES_REQUEST_EMAIL_TITLE_TEMPLATE\"",
"]",
",",
"return",
"format_request_email_templ",
"(",
"increq",
",",
"template",
",",
"*",
"*",
"ctx",
")"
] | Format the email message title for inclusion request notification.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Email message title.
:rtype: str | [
"Format",
"the",
"email",
"message",
"title",
"for",
"inclusion",
"request",
"notification",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/utils.py#L179-L190 | train | 565 |
inveniosoftware/invenio-communities | invenio_communities/utils.py | format_request_email_body | def format_request_email_body(increq, **ctx):
"""Format the email message body for inclusion request notification.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Email message body.
:rtype: str
"""
template = current_app.config["COMMUNITIES_REQUEST_EMAIL_BODY_TEMPLATE"],
return format_request_email_templ(increq, template, **ctx) | python | def format_request_email_body(increq, **ctx):
"""Format the email message body for inclusion request notification.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Email message body.
:rtype: str
"""
template = current_app.config["COMMUNITIES_REQUEST_EMAIL_BODY_TEMPLATE"],
return format_request_email_templ(increq, template, **ctx) | [
"def",
"format_request_email_body",
"(",
"increq",
",",
"*",
"*",
"ctx",
")",
":",
"template",
"=",
"current_app",
".",
"config",
"[",
"\"COMMUNITIES_REQUEST_EMAIL_BODY_TEMPLATE\"",
"]",
",",
"return",
"format_request_email_templ",
"(",
"increq",
",",
"template",
",",
"*",
"*",
"ctx",
")"
] | Format the email message body for inclusion request notification.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param ctx: Optional extra context parameters passed to formatter.
:type ctx: dict.
:returns: Email message body.
:rtype: str | [
"Format",
"the",
"email",
"message",
"body",
"for",
"inclusion",
"request",
"notification",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/utils.py#L193-L204 | train | 566 |
inveniosoftware/invenio-communities | invenio_communities/utils.py | send_community_request_email | def send_community_request_email(increq):
"""Signal for sending emails after community inclusion request."""
from flask_mail import Message
from invenio_mail.tasks import send_email
msg_body = format_request_email_body(increq)
msg_title = format_request_email_title(increq)
sender = current_app.config['COMMUNITIES_REQUEST_EMAIL_SENDER']
msg = Message(
msg_title,
sender=sender,
recipients=[increq.community.owner.email, ],
body=msg_body
)
send_email.delay(msg.__dict__) | python | def send_community_request_email(increq):
"""Signal for sending emails after community inclusion request."""
from flask_mail import Message
from invenio_mail.tasks import send_email
msg_body = format_request_email_body(increq)
msg_title = format_request_email_title(increq)
sender = current_app.config['COMMUNITIES_REQUEST_EMAIL_SENDER']
msg = Message(
msg_title,
sender=sender,
recipients=[increq.community.owner.email, ],
body=msg_body
)
send_email.delay(msg.__dict__) | [
"def",
"send_community_request_email",
"(",
"increq",
")",
":",
"from",
"flask_mail",
"import",
"Message",
"from",
"invenio_mail",
".",
"tasks",
"import",
"send_email",
"msg_body",
"=",
"format_request_email_body",
"(",
"increq",
")",
"msg_title",
"=",
"format_request_email_title",
"(",
"increq",
")",
"sender",
"=",
"current_app",
".",
"config",
"[",
"'COMMUNITIES_REQUEST_EMAIL_SENDER'",
"]",
"msg",
"=",
"Message",
"(",
"msg_title",
",",
"sender",
"=",
"sender",
",",
"recipients",
"=",
"[",
"increq",
".",
"community",
".",
"owner",
".",
"email",
",",
"]",
",",
"body",
"=",
"msg_body",
")",
"send_email",
".",
"delay",
"(",
"msg",
".",
"__dict__",
")"
] | Signal for sending emails after community inclusion request. | [
"Signal",
"for",
"sending",
"emails",
"after",
"community",
"inclusion",
"request",
"."
] | 5c4de6783724d276ae1b6dd13a399a9e22fadc7a | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/utils.py#L207-L224 | train | 567 |
yamins81/tabular | tabular/tab.py | modifydocs | def modifydocs(a, b, desc=''):
"""
Convenience function for writing documentation.
For a class method `a` that is essentially a wrapper for an outside
function `b`, rope in the docstring from `b` and append to that of `a`.
Also modify the docstring of `a` to get the indentation right.
Will probably deprecate this soon.
**Parameters**
**a** : class method
Class method wrapping `b`.
**b** : function
Function wrapped by `a`.
**desc** : string, optional
Description of `b`, e.g. restructured text providing a link to the
documentation for `b`. Default is an empty string.
**Returns**
**newdoc** : string
New docstring for `a`.
"""
newdoc = a.func_doc.replace('\t\t', '\t')
newdoc += "Documentation from " + desc + ":\n" + b.func_doc
return newdoc | python | def modifydocs(a, b, desc=''):
"""
Convenience function for writing documentation.
For a class method `a` that is essentially a wrapper for an outside
function `b`, rope in the docstring from `b` and append to that of `a`.
Also modify the docstring of `a` to get the indentation right.
Will probably deprecate this soon.
**Parameters**
**a** : class method
Class method wrapping `b`.
**b** : function
Function wrapped by `a`.
**desc** : string, optional
Description of `b`, e.g. restructured text providing a link to the
documentation for `b`. Default is an empty string.
**Returns**
**newdoc** : string
New docstring for `a`.
"""
newdoc = a.func_doc.replace('\t\t', '\t')
newdoc += "Documentation from " + desc + ":\n" + b.func_doc
return newdoc | [
"def",
"modifydocs",
"(",
"a",
",",
"b",
",",
"desc",
"=",
"''",
")",
":",
"newdoc",
"=",
"a",
".",
"func_doc",
".",
"replace",
"(",
"'\\t\\t'",
",",
"'\\t'",
")",
"newdoc",
"+=",
"\"Documentation from \"",
"+",
"desc",
"+",
"\":\\n\"",
"+",
"b",
".",
"func_doc",
"return",
"newdoc"
] | Convenience function for writing documentation.
For a class method `a` that is essentially a wrapper for an outside
function `b`, rope in the docstring from `b` and append to that of `a`.
Also modify the docstring of `a` to get the indentation right.
Will probably deprecate this soon.
**Parameters**
**a** : class method
Class method wrapping `b`.
**b** : function
Function wrapped by `a`.
**desc** : string, optional
Description of `b`, e.g. restructured text providing a link to the
documentation for `b`. Default is an empty string.
**Returns**
**newdoc** : string
New docstring for `a`. | [
"Convenience",
"function",
"for",
"writing",
"documentation",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L34-L68 | train | 568 |
yamins81/tabular | tabular/tab.py | tab_join | def tab_join(ToMerge, keycols=None, nullvals=None, renamer=None,
returnrenaming=False, Names=None):
'''
Database-join for tabular arrays.
Wrapper for :func:`tabular.spreadsheet.join` that deals with the coloring
and returns the result as a tabarray.
Method calls::
data = tabular.spreadsheet.join
'''
[Result,Renaming] = spreadsheet.join(ToMerge, keycols=keycols,
nullvals=nullvals, renamer=renamer, returnrenaming=True, Names=Names)
if isinstance(ToMerge,dict):
Names = ToMerge.keys()
else:
Names = range(len(ToMerge))
Colorings = dict([(k,ToMerge[k].coloring) if 'coloring' in dir(ToMerge[k])
else {} for k in Names])
for k in Names:
if k in Renaming.keys():
l = ToMerge[k]
Colorings[k] = \
dict([(g, [n if not n in Renaming[k].keys() else Renaming[k][n]
for n in l.coloring[g]]) for g in Colorings[k].keys()])
Coloring = {}
for k in Colorings.keys():
for j in Colorings[k].keys():
if j in Coloring.keys():
Coloring[j] = utils.uniqify(Coloring[j] + Colorings[k][j])
else:
Coloring[j] = utils.uniqify(Colorings[k][j])
Result = Result.view(tabarray)
Result.coloring = Coloring
if returnrenaming:
return [Result,Renaming]
else:
return Result | python | def tab_join(ToMerge, keycols=None, nullvals=None, renamer=None,
returnrenaming=False, Names=None):
'''
Database-join for tabular arrays.
Wrapper for :func:`tabular.spreadsheet.join` that deals with the coloring
and returns the result as a tabarray.
Method calls::
data = tabular.spreadsheet.join
'''
[Result,Renaming] = spreadsheet.join(ToMerge, keycols=keycols,
nullvals=nullvals, renamer=renamer, returnrenaming=True, Names=Names)
if isinstance(ToMerge,dict):
Names = ToMerge.keys()
else:
Names = range(len(ToMerge))
Colorings = dict([(k,ToMerge[k].coloring) if 'coloring' in dir(ToMerge[k])
else {} for k in Names])
for k in Names:
if k in Renaming.keys():
l = ToMerge[k]
Colorings[k] = \
dict([(g, [n if not n in Renaming[k].keys() else Renaming[k][n]
for n in l.coloring[g]]) for g in Colorings[k].keys()])
Coloring = {}
for k in Colorings.keys():
for j in Colorings[k].keys():
if j in Coloring.keys():
Coloring[j] = utils.uniqify(Coloring[j] + Colorings[k][j])
else:
Coloring[j] = utils.uniqify(Colorings[k][j])
Result = Result.view(tabarray)
Result.coloring = Coloring
if returnrenaming:
return [Result,Renaming]
else:
return Result | [
"def",
"tab_join",
"(",
"ToMerge",
",",
"keycols",
"=",
"None",
",",
"nullvals",
"=",
"None",
",",
"renamer",
"=",
"None",
",",
"returnrenaming",
"=",
"False",
",",
"Names",
"=",
"None",
")",
":",
"[",
"Result",
",",
"Renaming",
"]",
"=",
"spreadsheet",
".",
"join",
"(",
"ToMerge",
",",
"keycols",
"=",
"keycols",
",",
"nullvals",
"=",
"nullvals",
",",
"renamer",
"=",
"renamer",
",",
"returnrenaming",
"=",
"True",
",",
"Names",
"=",
"Names",
")",
"if",
"isinstance",
"(",
"ToMerge",
",",
"dict",
")",
":",
"Names",
"=",
"ToMerge",
".",
"keys",
"(",
")",
"else",
":",
"Names",
"=",
"range",
"(",
"len",
"(",
"ToMerge",
")",
")",
"Colorings",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"ToMerge",
"[",
"k",
"]",
".",
"coloring",
")",
"if",
"'coloring'",
"in",
"dir",
"(",
"ToMerge",
"[",
"k",
"]",
")",
"else",
"{",
"}",
"for",
"k",
"in",
"Names",
"]",
")",
"for",
"k",
"in",
"Names",
":",
"if",
"k",
"in",
"Renaming",
".",
"keys",
"(",
")",
":",
"l",
"=",
"ToMerge",
"[",
"k",
"]",
"Colorings",
"[",
"k",
"]",
"=",
"dict",
"(",
"[",
"(",
"g",
",",
"[",
"n",
"if",
"not",
"n",
"in",
"Renaming",
"[",
"k",
"]",
".",
"keys",
"(",
")",
"else",
"Renaming",
"[",
"k",
"]",
"[",
"n",
"]",
"for",
"n",
"in",
"l",
".",
"coloring",
"[",
"g",
"]",
"]",
")",
"for",
"g",
"in",
"Colorings",
"[",
"k",
"]",
".",
"keys",
"(",
")",
"]",
")",
"Coloring",
"=",
"{",
"}",
"for",
"k",
"in",
"Colorings",
".",
"keys",
"(",
")",
":",
"for",
"j",
"in",
"Colorings",
"[",
"k",
"]",
".",
"keys",
"(",
")",
":",
"if",
"j",
"in",
"Coloring",
".",
"keys",
"(",
")",
":",
"Coloring",
"[",
"j",
"]",
"=",
"utils",
".",
"uniqify",
"(",
"Coloring",
"[",
"j",
"]",
"+",
"Colorings",
"[",
"k",
"]",
"[",
"j",
"]",
")",
"else",
":",
"Coloring",
"[",
"j",
"]",
"=",
"utils",
".",
"uniqify",
"(",
"Colorings",
"[",
"k",
"]",
"[",
"j",
"]",
")",
"Result",
"=",
"Result",
".",
"view",
"(",
"tabarray",
")",
"Result",
".",
"coloring",
"=",
"Coloring",
"if",
"returnrenaming",
":",
"return",
"[",
"Result",
",",
"Renaming",
"]",
"else",
":",
"return",
"Result"
] | Database-join for tabular arrays.
Wrapper for :func:`tabular.spreadsheet.join` that deals with the coloring
and returns the result as a tabarray.
Method calls::
data = tabular.spreadsheet.join | [
"Database",
"-",
"join",
"for",
"tabular",
"arrays",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L142-L186 | train | 569 |
yamins81/tabular | tabular/tab.py | tabarray.extract | def extract(self):
"""
Creates a copy of this tabarray in the form of a numpy ndarray.
Useful if you want to do math on array elements, e.g. if you have a
subset of the columns that are all numerical, you can construct a
numerical matrix and do matrix operations.
"""
return np.vstack([self[r] for r in self.dtype.names]).T.squeeze() | python | def extract(self):
"""
Creates a copy of this tabarray in the form of a numpy ndarray.
Useful if you want to do math on array elements, e.g. if you have a
subset of the columns that are all numerical, you can construct a
numerical matrix and do matrix operations.
"""
return np.vstack([self[r] for r in self.dtype.names]).T.squeeze() | [
"def",
"extract",
"(",
"self",
")",
":",
"return",
"np",
".",
"vstack",
"(",
"[",
"self",
"[",
"r",
"]",
"for",
"r",
"in",
"self",
".",
"dtype",
".",
"names",
"]",
")",
".",
"T",
".",
"squeeze",
"(",
")"
] | Creates a copy of this tabarray in the form of a numpy ndarray.
Useful if you want to do math on array elements, e.g. if you have a
subset of the columns that are all numerical, you can construct a
numerical matrix and do matrix operations. | [
"Creates",
"a",
"copy",
"of",
"this",
"tabarray",
"in",
"the",
"form",
"of",
"a",
"numpy",
"ndarray",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L550-L559 | train | 570 |
yamins81/tabular | tabular/tab.py | tabarray.addrecords | def addrecords(self, new):
"""
Append one or more records to the end of the array.
Method wraps::
tabular.spreadsheet.addrecords(self, new)
"""
data = spreadsheet.addrecords(self,new)
data = data.view(tabarray)
data.coloring = self.coloring
return data | python | def addrecords(self, new):
"""
Append one or more records to the end of the array.
Method wraps::
tabular.spreadsheet.addrecords(self, new)
"""
data = spreadsheet.addrecords(self,new)
data = data.view(tabarray)
data.coloring = self.coloring
return data | [
"def",
"addrecords",
"(",
"self",
",",
"new",
")",
":",
"data",
"=",
"spreadsheet",
".",
"addrecords",
"(",
"self",
",",
"new",
")",
"data",
"=",
"data",
".",
"view",
"(",
"tabarray",
")",
"data",
".",
"coloring",
"=",
"self",
".",
"coloring",
"return",
"data"
] | Append one or more records to the end of the array.
Method wraps::
tabular.spreadsheet.addrecords(self, new) | [
"Append",
"one",
"or",
"more",
"records",
"to",
"the",
"end",
"of",
"the",
"array",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L609-L621 | train | 571 |
yamins81/tabular | tabular/tab.py | tabarray.addcols | def addcols(self, cols, names=None):
"""
Add one or more new columns.
Method wraps::
tabular.spreadsheet.addcols(self, cols, names)
"""
data = spreadsheet.addcols(self, cols, names)
data = data.view(tabarray)
data.coloring = self.coloring
return data | python | def addcols(self, cols, names=None):
"""
Add one or more new columns.
Method wraps::
tabular.spreadsheet.addcols(self, cols, names)
"""
data = spreadsheet.addcols(self, cols, names)
data = data.view(tabarray)
data.coloring = self.coloring
return data | [
"def",
"addcols",
"(",
"self",
",",
"cols",
",",
"names",
"=",
"None",
")",
":",
"data",
"=",
"spreadsheet",
".",
"addcols",
"(",
"self",
",",
"cols",
",",
"names",
")",
"data",
"=",
"data",
".",
"view",
"(",
"tabarray",
")",
"data",
".",
"coloring",
"=",
"self",
".",
"coloring",
"return",
"data"
] | Add one or more new columns.
Method wraps::
tabular.spreadsheet.addcols(self, cols, names) | [
"Add",
"one",
"or",
"more",
"new",
"columns",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L625-L637 | train | 572 |
yamins81/tabular | tabular/tab.py | tabarray.renamecol | def renamecol(self, old, new):
"""
Rename column or color in-place.
Method wraps::
tabular.spreadsheet.renamecol(self, old, new)
"""
spreadsheet.renamecol(self,old,new)
for x in self.coloring.keys():
if old in self.coloring[x]:
ind = self.coloring[x].index(old)
self.coloring[x][ind] = new | python | def renamecol(self, old, new):
"""
Rename column or color in-place.
Method wraps::
tabular.spreadsheet.renamecol(self, old, new)
"""
spreadsheet.renamecol(self,old,new)
for x in self.coloring.keys():
if old in self.coloring[x]:
ind = self.coloring[x].index(old)
self.coloring[x][ind] = new | [
"def",
"renamecol",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"spreadsheet",
".",
"renamecol",
"(",
"self",
",",
"old",
",",
"new",
")",
"for",
"x",
"in",
"self",
".",
"coloring",
".",
"keys",
"(",
")",
":",
"if",
"old",
"in",
"self",
".",
"coloring",
"[",
"x",
"]",
":",
"ind",
"=",
"self",
".",
"coloring",
"[",
"x",
"]",
".",
"index",
"(",
"old",
")",
"self",
".",
"coloring",
"[",
"x",
"]",
"[",
"ind",
"]",
"=",
"new"
] | Rename column or color in-place.
Method wraps::
tabular.spreadsheet.renamecol(self, old, new) | [
"Rename",
"column",
"or",
"color",
"in",
"-",
"place",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L658-L671 | train | 573 |
yamins81/tabular | tabular/tab.py | tabarray.colstack | def colstack(self, new, mode='abort'):
"""
Horizontal stacking for tabarrays.
Stack tabarray(s) in `new` to the right of `self`.
**See also**
:func:`tabular.tabarray.tab_colstack`,
:func:`tabular.spreadsheet.colstack`
"""
if isinstance(new,list):
return tab_colstack([self] + new,mode)
else:
return tab_colstack([self, new], mode) | python | def colstack(self, new, mode='abort'):
"""
Horizontal stacking for tabarrays.
Stack tabarray(s) in `new` to the right of `self`.
**See also**
:func:`tabular.tabarray.tab_colstack`,
:func:`tabular.spreadsheet.colstack`
"""
if isinstance(new,list):
return tab_colstack([self] + new,mode)
else:
return tab_colstack([self, new], mode) | [
"def",
"colstack",
"(",
"self",
",",
"new",
",",
"mode",
"=",
"'abort'",
")",
":",
"if",
"isinstance",
"(",
"new",
",",
"list",
")",
":",
"return",
"tab_colstack",
"(",
"[",
"self",
"]",
"+",
"new",
",",
"mode",
")",
"else",
":",
"return",
"tab_colstack",
"(",
"[",
"self",
",",
"new",
"]",
",",
"mode",
")"
] | Horizontal stacking for tabarrays.
Stack tabarray(s) in `new` to the right of `self`.
**See also**
:func:`tabular.tabarray.tab_colstack`,
:func:`tabular.spreadsheet.colstack` | [
"Horizontal",
"stacking",
"for",
"tabarrays",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L713-L728 | train | 574 |
yamins81/tabular | tabular/tab.py | tabarray.rowstack | def rowstack(self, new, mode='nulls'):
"""
Vertical stacking for tabarrays.
Stack tabarray(s) in `new` below `self`.
**See also**
:func:`tabular.tabarray.tab_rowstack`,
:func:`tabular.spreadsheet.rowstack`
"""
if isinstance(new,list):
return tab_rowstack([self] + new, mode)
else:
return tab_rowstack([self, new], mode) | python | def rowstack(self, new, mode='nulls'):
"""
Vertical stacking for tabarrays.
Stack tabarray(s) in `new` below `self`.
**See also**
:func:`tabular.tabarray.tab_rowstack`,
:func:`tabular.spreadsheet.rowstack`
"""
if isinstance(new,list):
return tab_rowstack([self] + new, mode)
else:
return tab_rowstack([self, new], mode) | [
"def",
"rowstack",
"(",
"self",
",",
"new",
",",
"mode",
"=",
"'nulls'",
")",
":",
"if",
"isinstance",
"(",
"new",
",",
"list",
")",
":",
"return",
"tab_rowstack",
"(",
"[",
"self",
"]",
"+",
"new",
",",
"mode",
")",
"else",
":",
"return",
"tab_rowstack",
"(",
"[",
"self",
",",
"new",
"]",
",",
"mode",
")"
] | Vertical stacking for tabarrays.
Stack tabarray(s) in `new` below `self`.
**See also**
:func:`tabular.tabarray.tab_rowstack`,
:func:`tabular.spreadsheet.rowstack` | [
"Vertical",
"stacking",
"for",
"tabarrays",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L733-L748 | train | 575 |
yamins81/tabular | tabular/tab.py | tabarray.aggregate | def aggregate(self, On=None, AggFuncDict=None, AggFunc=None, AggList =
None, returnsort=False,KeepOthers=True, keyfuncdict=None):
"""
Aggregate a tabarray on columns for given functions.
Method wraps::
tabular.spreadsheet.aggregate(self, On, AggFuncDict, AggFunc, returnsort)
"""
if returnsort:
[data, s] = spreadsheet.aggregate(X=self,
On=On,
AggFuncDict=AggFuncDict,
AggFunc=AggFunc,
AggList=AggList,
returnsort=returnsort,
keyfuncdict=keyfuncdict)
else:
data = spreadsheet.aggregate(X=self, On=On, AggFuncDict=AggFuncDict,
AggFunc=AggFunc, AggList = AggList, returnsort=returnsort,
KeepOthers=KeepOthers,
keyfuncdict=keyfuncdict)
data = data.view(tabarray)
data.coloring = self.coloring
if returnsort:
return [data, s]
else:
return data | python | def aggregate(self, On=None, AggFuncDict=None, AggFunc=None, AggList =
None, returnsort=False,KeepOthers=True, keyfuncdict=None):
"""
Aggregate a tabarray on columns for given functions.
Method wraps::
tabular.spreadsheet.aggregate(self, On, AggFuncDict, AggFunc, returnsort)
"""
if returnsort:
[data, s] = spreadsheet.aggregate(X=self,
On=On,
AggFuncDict=AggFuncDict,
AggFunc=AggFunc,
AggList=AggList,
returnsort=returnsort,
keyfuncdict=keyfuncdict)
else:
data = spreadsheet.aggregate(X=self, On=On, AggFuncDict=AggFuncDict,
AggFunc=AggFunc, AggList = AggList, returnsort=returnsort,
KeepOthers=KeepOthers,
keyfuncdict=keyfuncdict)
data = data.view(tabarray)
data.coloring = self.coloring
if returnsort:
return [data, s]
else:
return data | [
"def",
"aggregate",
"(",
"self",
",",
"On",
"=",
"None",
",",
"AggFuncDict",
"=",
"None",
",",
"AggFunc",
"=",
"None",
",",
"AggList",
"=",
"None",
",",
"returnsort",
"=",
"False",
",",
"KeepOthers",
"=",
"True",
",",
"keyfuncdict",
"=",
"None",
")",
":",
"if",
"returnsort",
":",
"[",
"data",
",",
"s",
"]",
"=",
"spreadsheet",
".",
"aggregate",
"(",
"X",
"=",
"self",
",",
"On",
"=",
"On",
",",
"AggFuncDict",
"=",
"AggFuncDict",
",",
"AggFunc",
"=",
"AggFunc",
",",
"AggList",
"=",
"AggList",
",",
"returnsort",
"=",
"returnsort",
",",
"keyfuncdict",
"=",
"keyfuncdict",
")",
"else",
":",
"data",
"=",
"spreadsheet",
".",
"aggregate",
"(",
"X",
"=",
"self",
",",
"On",
"=",
"On",
",",
"AggFuncDict",
"=",
"AggFuncDict",
",",
"AggFunc",
"=",
"AggFunc",
",",
"AggList",
"=",
"AggList",
",",
"returnsort",
"=",
"returnsort",
",",
"KeepOthers",
"=",
"KeepOthers",
",",
"keyfuncdict",
"=",
"keyfuncdict",
")",
"data",
"=",
"data",
".",
"view",
"(",
"tabarray",
")",
"data",
".",
"coloring",
"=",
"self",
".",
"coloring",
"if",
"returnsort",
":",
"return",
"[",
"data",
",",
"s",
"]",
"else",
":",
"return",
"data"
] | Aggregate a tabarray on columns for given functions.
Method wraps::
tabular.spreadsheet.aggregate(self, On, AggFuncDict, AggFunc, returnsort) | [
"Aggregate",
"a",
"tabarray",
"on",
"columns",
"for",
"given",
"functions",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L753-L781 | train | 576 |
yamins81/tabular | tabular/tab.py | tabarray.aggregate_in | def aggregate_in(self, On=None, AggFuncDict=None, AggFunc=None,
AggList=None, interspersed=True):
"""
Aggregate a tabarray and include original data in the result.
See the :func:`aggregate` method.
Method wraps::
tabular.summarize.aggregate_in(self, On, AggFuncDict, AggFunc, interspersed)
"""
data = spreadsheet.aggregate_in(Data=self, On=On,
AggFuncDict=AggFuncDict, AggFunc=AggFunc,
AggList = AggList, interspersed=interspersed)
data = data.view(tabarray)
data.view = self.coloring
return data | python | def aggregate_in(self, On=None, AggFuncDict=None, AggFunc=None,
AggList=None, interspersed=True):
"""
Aggregate a tabarray and include original data in the result.
See the :func:`aggregate` method.
Method wraps::
tabular.summarize.aggregate_in(self, On, AggFuncDict, AggFunc, interspersed)
"""
data = spreadsheet.aggregate_in(Data=self, On=On,
AggFuncDict=AggFuncDict, AggFunc=AggFunc,
AggList = AggList, interspersed=interspersed)
data = data.view(tabarray)
data.view = self.coloring
return data | [
"def",
"aggregate_in",
"(",
"self",
",",
"On",
"=",
"None",
",",
"AggFuncDict",
"=",
"None",
",",
"AggFunc",
"=",
"None",
",",
"AggList",
"=",
"None",
",",
"interspersed",
"=",
"True",
")",
":",
"data",
"=",
"spreadsheet",
".",
"aggregate_in",
"(",
"Data",
"=",
"self",
",",
"On",
"=",
"On",
",",
"AggFuncDict",
"=",
"AggFuncDict",
",",
"AggFunc",
"=",
"AggFunc",
",",
"AggList",
"=",
"AggList",
",",
"interspersed",
"=",
"interspersed",
")",
"data",
"=",
"data",
".",
"view",
"(",
"tabarray",
")",
"data",
".",
"view",
"=",
"self",
".",
"coloring",
"return",
"data"
] | Aggregate a tabarray and include original data in the result.
See the :func:`aggregate` method.
Method wraps::
tabular.summarize.aggregate_in(self, On, AggFuncDict, AggFunc, interspersed) | [
"Aggregate",
"a",
"tabarray",
"and",
"include",
"original",
"data",
"in",
"the",
"result",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L785-L802 | train | 577 |
yamins81/tabular | tabular/tab.py | tabarray.pivot | def pivot(self, a, b, Keep=None, NullVals=None, order = None, prefix='_'):
"""
Pivot with `a` as the row axis and `b` values as the column axis.
Method wraps::
tabular.spreadsheet.pivot(X, a, b, Keep)
"""
[data,coloring] = spreadsheet.pivot(X=self, a=a, b=b, Keep=Keep,
NullVals=NullVals, order=order, prefix=prefix)
data = data.view(tabarray)
data.coloring = coloring
return data | python | def pivot(self, a, b, Keep=None, NullVals=None, order = None, prefix='_'):
"""
Pivot with `a` as the row axis and `b` values as the column axis.
Method wraps::
tabular.spreadsheet.pivot(X, a, b, Keep)
"""
[data,coloring] = spreadsheet.pivot(X=self, a=a, b=b, Keep=Keep,
NullVals=NullVals, order=order, prefix=prefix)
data = data.view(tabarray)
data.coloring = coloring
return data | [
"def",
"pivot",
"(",
"self",
",",
"a",
",",
"b",
",",
"Keep",
"=",
"None",
",",
"NullVals",
"=",
"None",
",",
"order",
"=",
"None",
",",
"prefix",
"=",
"'_'",
")",
":",
"[",
"data",
",",
"coloring",
"]",
"=",
"spreadsheet",
".",
"pivot",
"(",
"X",
"=",
"self",
",",
"a",
"=",
"a",
",",
"b",
"=",
"b",
",",
"Keep",
"=",
"Keep",
",",
"NullVals",
"=",
"NullVals",
",",
"order",
"=",
"order",
",",
"prefix",
"=",
"prefix",
")",
"data",
"=",
"data",
".",
"view",
"(",
"tabarray",
")",
"data",
".",
"coloring",
"=",
"coloring",
"return",
"data"
] | Pivot with `a` as the row axis and `b` values as the column axis.
Method wraps::
tabular.spreadsheet.pivot(X, a, b, Keep) | [
"Pivot",
"with",
"a",
"as",
"the",
"row",
"axis",
"and",
"b",
"values",
"as",
"the",
"column",
"axis",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L807-L820 | train | 578 |
yamins81/tabular | tabular/tab.py | tabarray.join | def join(self, ToMerge, keycols=None, nullvals=None,
renamer=None, returnrenaming=False, selfname=None, Names=None):
"""
Wrapper for spreadsheet.join, but handles coloring attributes.
The `selfname` argument allows naming of `self` to be used if `ToMerge`
is a dictionary.
**See also:** :func:`tabular.spreadsheet.join`, :func:`tab_join`
"""
if isinstance(ToMerge,np.ndarray):
ToMerge = [ToMerge]
if isinstance(ToMerge,dict):
assert selfname not in ToMerge.keys(), \
('Can\'t use "', selfname + '" for name of one of the things to '
'merge, since it is the same name as the self object.')
if selfname == None:
try:
selfname = self.name
except AttributeError:
selfname = 'self'
ToMerge.update({selfname:self})
else:
ToMerge = [self] + ToMerge
return tab_join(ToMerge, keycols=keycols, nullvals=nullvals,
renamer=renamer, returnrenaming=returnrenaming, Names=Names) | python | def join(self, ToMerge, keycols=None, nullvals=None,
renamer=None, returnrenaming=False, selfname=None, Names=None):
"""
Wrapper for spreadsheet.join, but handles coloring attributes.
The `selfname` argument allows naming of `self` to be used if `ToMerge`
is a dictionary.
**See also:** :func:`tabular.spreadsheet.join`, :func:`tab_join`
"""
if isinstance(ToMerge,np.ndarray):
ToMerge = [ToMerge]
if isinstance(ToMerge,dict):
assert selfname not in ToMerge.keys(), \
('Can\'t use "', selfname + '" for name of one of the things to '
'merge, since it is the same name as the self object.')
if selfname == None:
try:
selfname = self.name
except AttributeError:
selfname = 'self'
ToMerge.update({selfname:self})
else:
ToMerge = [self] + ToMerge
return tab_join(ToMerge, keycols=keycols, nullvals=nullvals,
renamer=renamer, returnrenaming=returnrenaming, Names=Names) | [
"def",
"join",
"(",
"self",
",",
"ToMerge",
",",
"keycols",
"=",
"None",
",",
"nullvals",
"=",
"None",
",",
"renamer",
"=",
"None",
",",
"returnrenaming",
"=",
"False",
",",
"selfname",
"=",
"None",
",",
"Names",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"ToMerge",
",",
"np",
".",
"ndarray",
")",
":",
"ToMerge",
"=",
"[",
"ToMerge",
"]",
"if",
"isinstance",
"(",
"ToMerge",
",",
"dict",
")",
":",
"assert",
"selfname",
"not",
"in",
"ToMerge",
".",
"keys",
"(",
")",
",",
"(",
"'Can\\'t use \"'",
",",
"selfname",
"+",
"'\" for name of one of the things to '",
"'merge, since it is the same name as the self object.'",
")",
"if",
"selfname",
"==",
"None",
":",
"try",
":",
"selfname",
"=",
"self",
".",
"name",
"except",
"AttributeError",
":",
"selfname",
"=",
"'self'",
"ToMerge",
".",
"update",
"(",
"{",
"selfname",
":",
"self",
"}",
")",
"else",
":",
"ToMerge",
"=",
"[",
"self",
"]",
"+",
"ToMerge",
"return",
"tab_join",
"(",
"ToMerge",
",",
"keycols",
"=",
"keycols",
",",
"nullvals",
"=",
"nullvals",
",",
"renamer",
"=",
"renamer",
",",
"returnrenaming",
"=",
"returnrenaming",
",",
"Names",
"=",
"Names",
")"
] | Wrapper for spreadsheet.join, but handles coloring attributes.
The `selfname` argument allows naming of `self` to be used if `ToMerge`
is a dictionary.
**See also:** :func:`tabular.spreadsheet.join`, :func:`tab_join` | [
"Wrapper",
"for",
"spreadsheet",
".",
"join",
"but",
"handles",
"coloring",
"attributes",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L839-L867 | train | 579 |
yamins81/tabular | tabular/tab.py | tabarray.argsort | def argsort(self, axis=-1, kind='quicksort', order=None):
"""
Returns the indices that would sort an array.
.. note::
This method wraps `numpy.argsort`. This documentation is
modified from that of `numpy.argsort`.
Perform an indirect sort along the given axis using the algorithm
specified by the `kind` keyword. It returns an array of indices of the
same shape as the original array that index data along the given axis
in sorted order.
**Parameters**
**axis** : int or None, optional
Axis along which to sort. The default is -1 (the last
axis). If `None`, the flattened array is used.
**kind** : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
**order** : list, optional
This argument specifies which fields to compare first,
second, etc. Not all fields need be specified.
**Returns**
**index_array** : ndarray, int
Array of indices that sort the tabarray along the
specified axis. In other words, ``a[index_array]``
yields a sorted `a`.
**See Also**
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
**Notes**
See `numpy.sort` for notes on the different sorting
algorithms.
**Examples**
Sorting with keys:
>>> x = tabarray([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
tabarray([(1, 0), (0, 1)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> x.argsort(order=('x','y'))
array([1, 0])
>>> x.argsort(order=('y','x'))
array([0, 1])
"""
index_array = np.core.fromnumeric._wrapit(self, 'argsort', axis,
kind, order)
index_array = index_array.view(np.ndarray)
return index_array | python | def argsort(self, axis=-1, kind='quicksort', order=None):
"""
Returns the indices that would sort an array.
.. note::
This method wraps `numpy.argsort`. This documentation is
modified from that of `numpy.argsort`.
Perform an indirect sort along the given axis using the algorithm
specified by the `kind` keyword. It returns an array of indices of the
same shape as the original array that index data along the given axis
in sorted order.
**Parameters**
**axis** : int or None, optional
Axis along which to sort. The default is -1 (the last
axis). If `None`, the flattened array is used.
**kind** : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
**order** : list, optional
This argument specifies which fields to compare first,
second, etc. Not all fields need be specified.
**Returns**
**index_array** : ndarray, int
Array of indices that sort the tabarray along the
specified axis. In other words, ``a[index_array]``
yields a sorted `a`.
**See Also**
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
**Notes**
See `numpy.sort` for notes on the different sorting
algorithms.
**Examples**
Sorting with keys:
>>> x = tabarray([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
tabarray([(1, 0), (0, 1)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> x.argsort(order=('x','y'))
array([1, 0])
>>> x.argsort(order=('y','x'))
array([0, 1])
"""
index_array = np.core.fromnumeric._wrapit(self, 'argsort', axis,
kind, order)
index_array = index_array.view(np.ndarray)
return index_array | [
"def",
"argsort",
"(",
"self",
",",
"axis",
"=",
"-",
"1",
",",
"kind",
"=",
"'quicksort'",
",",
"order",
"=",
"None",
")",
":",
"index_array",
"=",
"np",
".",
"core",
".",
"fromnumeric",
".",
"_wrapit",
"(",
"self",
",",
"'argsort'",
",",
"axis",
",",
"kind",
",",
"order",
")",
"index_array",
"=",
"index_array",
".",
"view",
"(",
"np",
".",
"ndarray",
")",
"return",
"index_array"
] | Returns the indices that would sort an array.
.. note::
This method wraps `numpy.argsort`. This documentation is
modified from that of `numpy.argsort`.
Perform an indirect sort along the given axis using the algorithm
specified by the `kind` keyword. It returns an array of indices of the
same shape as the original array that index data along the given axis
in sorted order.
**Parameters**
**axis** : int or None, optional
Axis along which to sort. The default is -1 (the last
axis). If `None`, the flattened array is used.
**kind** : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
**order** : list, optional
This argument specifies which fields to compare first,
second, etc. Not all fields need be specified.
**Returns**
**index_array** : ndarray, int
Array of indices that sort the tabarray along the
specified axis. In other words, ``a[index_array]``
yields a sorted `a`.
**See Also**
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
**Notes**
See `numpy.sort` for notes on the different sorting
algorithms.
**Examples**
Sorting with keys:
>>> x = tabarray([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
tabarray([(1, 0), (0, 1)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> x.argsort(order=('x','y'))
array([1, 0])
>>> x.argsort(order=('y','x'))
array([0, 1]) | [
"Returns",
"the",
"indices",
"that",
"would",
"sort",
"an",
"array",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L869-L937 | train | 580 |
hsolbrig/pyjsg | pyjsg/jsglib/jsg_strings.py | JSGPattern.matches | def matches(self, txt: str) -> bool:
"""Determine whether txt matches pattern
:param txt: text to check
:return: True if match
"""
# rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape')
if r'\\u' in self.pattern_re.pattern:
txt = txt.encode('utf-8').decode('unicode-escape')
match = self.pattern_re.match(txt)
return match is not None and match.end() == len(txt) | python | def matches(self, txt: str) -> bool:
"""Determine whether txt matches pattern
:param txt: text to check
:return: True if match
"""
# rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape')
if r'\\u' in self.pattern_re.pattern:
txt = txt.encode('utf-8').decode('unicode-escape')
match = self.pattern_re.match(txt)
return match is not None and match.end() == len(txt) | [
"def",
"matches",
"(",
"self",
",",
"txt",
":",
"str",
")",
"->",
"bool",
":",
"# rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape')",
"if",
"r'\\\\u'",
"in",
"self",
".",
"pattern_re",
".",
"pattern",
":",
"txt",
"=",
"txt",
".",
"encode",
"(",
"'utf-8'",
")",
".",
"decode",
"(",
"'unicode-escape'",
")",
"match",
"=",
"self",
".",
"pattern_re",
".",
"match",
"(",
"txt",
")",
"return",
"match",
"is",
"not",
"None",
"and",
"match",
".",
"end",
"(",
")",
"==",
"len",
"(",
"txt",
")"
] | Determine whether txt matches pattern
:param txt: text to check
:return: True if match | [
"Determine",
"whether",
"txt",
"matches",
"pattern"
] | 9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7 | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/jsglib/jsg_strings.py#L23-L33 | train | 581 |
yamins81/tabular | tabular/colors.py | Point2HexColor | def Point2HexColor(a, lfrac, tfrac):
"""
Return web-safe hex triplets.
"""
[H,S,V] = [math.floor(360 * a), lfrac, tfrac]
RGB = hsvToRGB(H, S, V)
H = [hex(int(math.floor(255 * x))) for x in RGB]
HEX = [a[a.find('x') + 1:] for a in H]
HEX = ['0' + h if len(h) == 1 else h for h in HEX]
return '#' + ''.join(HEX) | python | def Point2HexColor(a, lfrac, tfrac):
"""
Return web-safe hex triplets.
"""
[H,S,V] = [math.floor(360 * a), lfrac, tfrac]
RGB = hsvToRGB(H, S, V)
H = [hex(int(math.floor(255 * x))) for x in RGB]
HEX = [a[a.find('x') + 1:] for a in H]
HEX = ['0' + h if len(h) == 1 else h for h in HEX]
return '#' + ''.join(HEX) | [
"def",
"Point2HexColor",
"(",
"a",
",",
"lfrac",
",",
"tfrac",
")",
":",
"[",
"H",
",",
"S",
",",
"V",
"]",
"=",
"[",
"math",
".",
"floor",
"(",
"360",
"*",
"a",
")",
",",
"lfrac",
",",
"tfrac",
"]",
"RGB",
"=",
"hsvToRGB",
"(",
"H",
",",
"S",
",",
"V",
")",
"H",
"=",
"[",
"hex",
"(",
"int",
"(",
"math",
".",
"floor",
"(",
"255",
"*",
"x",
")",
")",
")",
"for",
"x",
"in",
"RGB",
"]",
"HEX",
"=",
"[",
"a",
"[",
"a",
".",
"find",
"(",
"'x'",
")",
"+",
"1",
":",
"]",
"for",
"a",
"in",
"H",
"]",
"HEX",
"=",
"[",
"'0'",
"+",
"h",
"if",
"len",
"(",
"h",
")",
"==",
"1",
"else",
"h",
"for",
"h",
"in",
"HEX",
"]",
"return",
"'#'",
"+",
"''",
".",
"join",
"(",
"HEX",
")"
] | Return web-safe hex triplets. | [
"Return",
"web",
"-",
"safe",
"hex",
"triplets",
"."
] | 1caf091c8c395960a9ad7078f95158b533cc52dd | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/colors.py#L13-L28 | train | 582 |
OpenTreeOfLife/peyotl | peyotl/utility/get_logger.py | warn_from_util_logger | def warn_from_util_logger(msg):
"""Only to be used in this file and peyotl.utility.get_config"""
global _LOG
# This check is necessary to avoid infinite recursion when called from get_config, because
# the _read_logging_conf can require reading a conf file.
if _LOG is None and _LOGGING_CONF is None:
sys.stderr.write('WARNING: (from peyotl before logging is configured) {}\n'.format(msg))
return
if _LOG is None:
_LOG = get_logger("peyotl.utility")
_LOG.warn(msg) | python | def warn_from_util_logger(msg):
"""Only to be used in this file and peyotl.utility.get_config"""
global _LOG
# This check is necessary to avoid infinite recursion when called from get_config, because
# the _read_logging_conf can require reading a conf file.
if _LOG is None and _LOGGING_CONF is None:
sys.stderr.write('WARNING: (from peyotl before logging is configured) {}\n'.format(msg))
return
if _LOG is None:
_LOG = get_logger("peyotl.utility")
_LOG.warn(msg) | [
"def",
"warn_from_util_logger",
"(",
"msg",
")",
":",
"global",
"_LOG",
"# This check is necessary to avoid infinite recursion when called from get_config, because",
"# the _read_logging_conf can require reading a conf file.",
"if",
"_LOG",
"is",
"None",
"and",
"_LOGGING_CONF",
"is",
"None",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'WARNING: (from peyotl before logging is configured) {}\\n'",
".",
"format",
"(",
"msg",
")",
")",
"return",
"if",
"_LOG",
"is",
"None",
":",
"_LOG",
"=",
"get_logger",
"(",
"\"peyotl.utility\"",
")",
"_LOG",
".",
"warn",
"(",
"msg",
")"
] | Only to be used in this file and peyotl.utility.get_config | [
"Only",
"to",
"be",
"used",
"in",
"this",
"file",
"and",
"peyotl",
".",
"utility",
".",
"get_config"
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/utility/get_logger.py#L85-L95 | train | 583 |
cydrobolt/pifx | pifx/core.py | PIFX.state_delta | def state_delta(self, selector='all',
power=None, duration=1.0, infrared=None, hue=None,
saturation=None, brightness=None, kelvin=None):
"""Given a state delta, apply the modifications to lights' state
over a given period of time.
selector: required String
The selector to limit which lights are controlled.
power: String
The power state you want to set on the selector. on or off
duration: Double
How long in seconds you want the power action to take.
Range: 0.0 – 3155760000.0 (100 years)
infrared: Double
The maximum brightness of the infrared channel.
hue: Double
Rotate the hue by this angle in degrees.
saturation: Double
Change the saturation by this additive amount; the resulting
saturation is clipped to [0, 1].
brightness: Double
Change the brightness by this additive amount; the resulting
brightness is clipped to [0, 1].
kelvin: Double
Change the kelvin by this additive amount; the resulting kelvin is
clipped to [2500, 9000].
"""
argument_tuples = [
("power", power),
("duration", duration),
("infrared", infrared),
("hue", hue),
("saturation", saturation),
("brightness", brightness),
("kelvin", kelvin)
]
return self.client.perform_request(
method='post', endpoint='lights/{}/state/delta',
endpoint_args=[selector], argument_tuples=argument_tuples) | python | def state_delta(self, selector='all',
power=None, duration=1.0, infrared=None, hue=None,
saturation=None, brightness=None, kelvin=None):
"""Given a state delta, apply the modifications to lights' state
over a given period of time.
selector: required String
The selector to limit which lights are controlled.
power: String
The power state you want to set on the selector. on or off
duration: Double
How long in seconds you want the power action to take.
Range: 0.0 – 3155760000.0 (100 years)
infrared: Double
The maximum brightness of the infrared channel.
hue: Double
Rotate the hue by this angle in degrees.
saturation: Double
Change the saturation by this additive amount; the resulting
saturation is clipped to [0, 1].
brightness: Double
Change the brightness by this additive amount; the resulting
brightness is clipped to [0, 1].
kelvin: Double
Change the kelvin by this additive amount; the resulting kelvin is
clipped to [2500, 9000].
"""
argument_tuples = [
("power", power),
("duration", duration),
("infrared", infrared),
("hue", hue),
("saturation", saturation),
("brightness", brightness),
("kelvin", kelvin)
]
return self.client.perform_request(
method='post', endpoint='lights/{}/state/delta',
endpoint_args=[selector], argument_tuples=argument_tuples) | [
"def",
"state_delta",
"(",
"self",
",",
"selector",
"=",
"'all'",
",",
"power",
"=",
"None",
",",
"duration",
"=",
"1.0",
",",
"infrared",
"=",
"None",
",",
"hue",
"=",
"None",
",",
"saturation",
"=",
"None",
",",
"brightness",
"=",
"None",
",",
"kelvin",
"=",
"None",
")",
":",
"argument_tuples",
"=",
"[",
"(",
"\"power\"",
",",
"power",
")",
",",
"(",
"\"duration\"",
",",
"duration",
")",
",",
"(",
"\"infrared\"",
",",
"infrared",
")",
",",
"(",
"\"hue\"",
",",
"hue",
")",
",",
"(",
"\"saturation\"",
",",
"saturation",
")",
",",
"(",
"\"brightness\"",
",",
"brightness",
")",
",",
"(",
"\"kelvin\"",
",",
"kelvin",
")",
"]",
"return",
"self",
".",
"client",
".",
"perform_request",
"(",
"method",
"=",
"'post'",
",",
"endpoint",
"=",
"'lights/{}/state/delta'",
",",
"endpoint_args",
"=",
"[",
"selector",
"]",
",",
"argument_tuples",
"=",
"argument_tuples",
")"
] | Given a state delta, apply the modifications to lights' state
over a given period of time.
selector: required String
The selector to limit which lights are controlled.
power: String
The power state you want to set on the selector. on or off
duration: Double
How long in seconds you want the power action to take.
Range: 0.0 – 3155760000.0 (100 years)
infrared: Double
The maximum brightness of the infrared channel.
hue: Double
Rotate the hue by this angle in degrees.
saturation: Double
Change the saturation by this additive amount; the resulting
saturation is clipped to [0, 1].
brightness: Double
Change the brightness by this additive amount; the resulting
brightness is clipped to [0, 1].
kelvin: Double
Change the kelvin by this additive amount; the resulting kelvin is
clipped to [2500, 9000]. | [
"Given",
"a",
"state",
"delta",
"apply",
"the",
"modifications",
"to",
"lights",
"state",
"over",
"a",
"given",
"period",
"of",
"time",
"."
] | c9de9c2695c3e6e72de4aa0de47b78fc13c457c3 | https://github.com/cydrobolt/pifx/blob/c9de9c2695c3e6e72de4aa0de47b78fc13c457c3/pifx/core.py#L75-L122 | train | 584 |
cydrobolt/pifx | pifx/core.py | PIFX.breathe_lights | def breathe_lights(self, color, selector='all',
from_color=None, period=1.0, cycles=1.0,
persist=False, power_on=True, peak=0.5):
"""Perform breathe effect on lights.
selector: String
The selector to limit which lights will run the effect.
default: all
color: required String
Color attributes to use during effect. See set_state for more.
from_color: String
The color to start the effect from. See set_state for more.
default: current bulb color
period: Double
The time in seconds for one cyles of the effect.
default: 1.0
cycles: Double
The number of times to repeat the effect.
default: 1.0
persist: Boolean
If false set the light back to its previous
value when effect ends, if true leave the last effect color.
default: false
power_on: Boolean
If true, turn the bulb on if it is not already on.
default: true
peak: String
Defines where in a period the target color is at its maximum.
Minimum 0.0, maximum 1.0.
default: 0.5
"""
argument_tuples = [
("color", color),
("from_color", from_color),
("period", period),
("cycles", cycles),
("persist", persist),
("power_on", power_on),
("peak", peak),
]
return self.client.perform_request(
method='post', endpoint='lights/{}/effects/breathe',
endpoint_args=[selector], argument_tuples=argument_tuples) | python | def breathe_lights(self, color, selector='all',
from_color=None, period=1.0, cycles=1.0,
persist=False, power_on=True, peak=0.5):
"""Perform breathe effect on lights.
selector: String
The selector to limit which lights will run the effect.
default: all
color: required String
Color attributes to use during effect. See set_state for more.
from_color: String
The color to start the effect from. See set_state for more.
default: current bulb color
period: Double
The time in seconds for one cyles of the effect.
default: 1.0
cycles: Double
The number of times to repeat the effect.
default: 1.0
persist: Boolean
If false set the light back to its previous
value when effect ends, if true leave the last effect color.
default: false
power_on: Boolean
If true, turn the bulb on if it is not already on.
default: true
peak: String
Defines where in a period the target color is at its maximum.
Minimum 0.0, maximum 1.0.
default: 0.5
"""
argument_tuples = [
("color", color),
("from_color", from_color),
("period", period),
("cycles", cycles),
("persist", persist),
("power_on", power_on),
("peak", peak),
]
return self.client.perform_request(
method='post', endpoint='lights/{}/effects/breathe',
endpoint_args=[selector], argument_tuples=argument_tuples) | [
"def",
"breathe_lights",
"(",
"self",
",",
"color",
",",
"selector",
"=",
"'all'",
",",
"from_color",
"=",
"None",
",",
"period",
"=",
"1.0",
",",
"cycles",
"=",
"1.0",
",",
"persist",
"=",
"False",
",",
"power_on",
"=",
"True",
",",
"peak",
"=",
"0.5",
")",
":",
"argument_tuples",
"=",
"[",
"(",
"\"color\"",
",",
"color",
")",
",",
"(",
"\"from_color\"",
",",
"from_color",
")",
",",
"(",
"\"period\"",
",",
"period",
")",
",",
"(",
"\"cycles\"",
",",
"cycles",
")",
",",
"(",
"\"persist\"",
",",
"persist",
")",
",",
"(",
"\"power_on\"",
",",
"power_on",
")",
",",
"(",
"\"peak\"",
",",
"peak",
")",
",",
"]",
"return",
"self",
".",
"client",
".",
"perform_request",
"(",
"method",
"=",
"'post'",
",",
"endpoint",
"=",
"'lights/{}/effects/breathe'",
",",
"endpoint_args",
"=",
"[",
"selector",
"]",
",",
"argument_tuples",
"=",
"argument_tuples",
")"
] | Perform breathe effect on lights.
selector: String
The selector to limit which lights will run the effect.
default: all
color: required String
Color attributes to use during effect. See set_state for more.
from_color: String
The color to start the effect from. See set_state for more.
default: current bulb color
period: Double
The time in seconds for one cyles of the effect.
default: 1.0
cycles: Double
The number of times to repeat the effect.
default: 1.0
persist: Boolean
If false set the light back to its previous
value when effect ends, if true leave the last effect color.
default: false
power_on: Boolean
If true, turn the bulb on if it is not already on.
default: true
peak: String
Defines where in a period the target color is at its maximum.
Minimum 0.0, maximum 1.0.
default: 0.5 | [
"Perform",
"breathe",
"effect",
"on",
"lights",
"."
] | c9de9c2695c3e6e72de4aa0de47b78fc13c457c3 | https://github.com/cydrobolt/pifx/blob/c9de9c2695c3e6e72de4aa0de47b78fc13c457c3/pifx/core.py#L135-L186 | train | 585 |
cydrobolt/pifx | pifx/core.py | PIFX.cycle_lights | def cycle_lights(self, states,
defaults, direction='forward', selector='all'):
"""Cycle through list of effects.
Provide array states as a list of dictionaries with set_state arguments.
See http://api.developer.lifx.com/docs/cycle
selector: String
The selector to limit which lights will run the effect.
default: all
states: required List of Dicts
List of arguments, named as per set_state. Must have 2 to 5 entries.
defaults: Object
Default values to use when not specified in each states[] object.
Argument names as per set_state.
direction: String
Direction in which to cycle through the list. Can be forward or backward
default: forward
"""
argument_tuples = [
("states", states),
("defaults", defaults),
("direction", direction)
]
return self.client.perform_request(
method='post', endpoint='lights/{}/cycle', endpoint_args=[selector],
argument_tuples=argument_tuples, json_body=True) | python | def cycle_lights(self, states,
defaults, direction='forward', selector='all'):
"""Cycle through list of effects.
Provide array states as a list of dictionaries with set_state arguments.
See http://api.developer.lifx.com/docs/cycle
selector: String
The selector to limit which lights will run the effect.
default: all
states: required List of Dicts
List of arguments, named as per set_state. Must have 2 to 5 entries.
defaults: Object
Default values to use when not specified in each states[] object.
Argument names as per set_state.
direction: String
Direction in which to cycle through the list. Can be forward or backward
default: forward
"""
argument_tuples = [
("states", states),
("defaults", defaults),
("direction", direction)
]
return self.client.perform_request(
method='post', endpoint='lights/{}/cycle', endpoint_args=[selector],
argument_tuples=argument_tuples, json_body=True) | [
"def",
"cycle_lights",
"(",
"self",
",",
"states",
",",
"defaults",
",",
"direction",
"=",
"'forward'",
",",
"selector",
"=",
"'all'",
")",
":",
"argument_tuples",
"=",
"[",
"(",
"\"states\"",
",",
"states",
")",
",",
"(",
"\"defaults\"",
",",
"defaults",
")",
",",
"(",
"\"direction\"",
",",
"direction",
")",
"]",
"return",
"self",
".",
"client",
".",
"perform_request",
"(",
"method",
"=",
"'post'",
",",
"endpoint",
"=",
"'lights/{}/cycle'",
",",
"endpoint_args",
"=",
"[",
"selector",
"]",
",",
"argument_tuples",
"=",
"argument_tuples",
",",
"json_body",
"=",
"True",
")"
] | Cycle through list of effects.
Provide array states as a list of dictionaries with set_state arguments.
See http://api.developer.lifx.com/docs/cycle
selector: String
The selector to limit which lights will run the effect.
default: all
states: required List of Dicts
List of arguments, named as per set_state. Must have 2 to 5 entries.
defaults: Object
Default values to use when not specified in each states[] object.
Argument names as per set_state.
direction: String
Direction in which to cycle through the list. Can be forward or backward
default: forward | [
"Cycle",
"through",
"list",
"of",
"effects",
"."
] | c9de9c2695c3e6e72de4aa0de47b78fc13c457c3 | https://github.com/cydrobolt/pifx/blob/c9de9c2695c3e6e72de4aa0de47b78fc13c457c3/pifx/core.py#L235-L266 | train | 586 |
cydrobolt/pifx | pifx/core.py | PIFX.activate_scene | def activate_scene(self, scene_uuid, duration=1.0):
"""Activate a scene.
See http://api.developer.lifx.com/docs/activate-scene
scene_uuid: required String
The UUID for the scene you wish to activate
duration: Double
The time in seconds to spend performing the scene transition.
default: 1.0
"""
argument_tuples = [
("duration", duration),
]
return self.client.perform_request(
method='put', endpoint='scenes/scene_id:{}/activate',
endpoint_args=[scene_uuid], argument_tuples=argument_tuples) | python | def activate_scene(self, scene_uuid, duration=1.0):
"""Activate a scene.
See http://api.developer.lifx.com/docs/activate-scene
scene_uuid: required String
The UUID for the scene you wish to activate
duration: Double
The time in seconds to spend performing the scene transition.
default: 1.0
"""
argument_tuples = [
("duration", duration),
]
return self.client.perform_request(
method='put', endpoint='scenes/scene_id:{}/activate',
endpoint_args=[scene_uuid], argument_tuples=argument_tuples) | [
"def",
"activate_scene",
"(",
"self",
",",
"scene_uuid",
",",
"duration",
"=",
"1.0",
")",
":",
"argument_tuples",
"=",
"[",
"(",
"\"duration\"",
",",
"duration",
")",
",",
"]",
"return",
"self",
".",
"client",
".",
"perform_request",
"(",
"method",
"=",
"'put'",
",",
"endpoint",
"=",
"'scenes/scene_id:{}/activate'",
",",
"endpoint_args",
"=",
"[",
"scene_uuid",
"]",
",",
"argument_tuples",
"=",
"argument_tuples",
")"
] | Activate a scene.
See http://api.developer.lifx.com/docs/activate-scene
scene_uuid: required String
The UUID for the scene you wish to activate
duration: Double
The time in seconds to spend performing the scene transition.
default: 1.0 | [
"Activate",
"a",
"scene",
"."
] | c9de9c2695c3e6e72de4aa0de47b78fc13c457c3 | https://github.com/cydrobolt/pifx/blob/c9de9c2695c3e6e72de4aa0de47b78fc13c457c3/pifx/core.py#L276-L295 | train | 587 |
OpenTreeOfLife/peyotl | peyotl/nexson_syntax/inspect.py | count_num_trees | def count_num_trees(nexson, nexson_version=None):
"""Returns the number of trees summed across all tree
groups.
"""
if nexson_version is None:
nexson_version = detect_nexson_version(nexson)
nex = get_nexml_el(nexson)
num_trees_by_group = []
if _is_by_id_hbf(nexson_version):
for tree_group in nex.get('treesById', {}).values():
nt = len(tree_group.get('treeById', {}))
num_trees_by_group.append(nt)
else:
trees_group = nex.get('trees', [])
if isinstance(trees_group, dict):
trees_group = [trees_group]
for tree_group in trees_group:
t = tree_group.get('tree')
if isinstance(t, list):
nt = len(t)
else:
nt = 1
num_trees_by_group.append(nt)
return sum(num_trees_by_group) | python | def count_num_trees(nexson, nexson_version=None):
"""Returns the number of trees summed across all tree
groups.
"""
if nexson_version is None:
nexson_version = detect_nexson_version(nexson)
nex = get_nexml_el(nexson)
num_trees_by_group = []
if _is_by_id_hbf(nexson_version):
for tree_group in nex.get('treesById', {}).values():
nt = len(tree_group.get('treeById', {}))
num_trees_by_group.append(nt)
else:
trees_group = nex.get('trees', [])
if isinstance(trees_group, dict):
trees_group = [trees_group]
for tree_group in trees_group:
t = tree_group.get('tree')
if isinstance(t, list):
nt = len(t)
else:
nt = 1
num_trees_by_group.append(nt)
return sum(num_trees_by_group) | [
"def",
"count_num_trees",
"(",
"nexson",
",",
"nexson_version",
"=",
"None",
")",
":",
"if",
"nexson_version",
"is",
"None",
":",
"nexson_version",
"=",
"detect_nexson_version",
"(",
"nexson",
")",
"nex",
"=",
"get_nexml_el",
"(",
"nexson",
")",
"num_trees_by_group",
"=",
"[",
"]",
"if",
"_is_by_id_hbf",
"(",
"nexson_version",
")",
":",
"for",
"tree_group",
"in",
"nex",
".",
"get",
"(",
"'treesById'",
",",
"{",
"}",
")",
".",
"values",
"(",
")",
":",
"nt",
"=",
"len",
"(",
"tree_group",
".",
"get",
"(",
"'treeById'",
",",
"{",
"}",
")",
")",
"num_trees_by_group",
".",
"append",
"(",
"nt",
")",
"else",
":",
"trees_group",
"=",
"nex",
".",
"get",
"(",
"'trees'",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"trees_group",
",",
"dict",
")",
":",
"trees_group",
"=",
"[",
"trees_group",
"]",
"for",
"tree_group",
"in",
"trees_group",
":",
"t",
"=",
"tree_group",
".",
"get",
"(",
"'tree'",
")",
"if",
"isinstance",
"(",
"t",
",",
"list",
")",
":",
"nt",
"=",
"len",
"(",
"t",
")",
"else",
":",
"nt",
"=",
"1",
"num_trees_by_group",
".",
"append",
"(",
"nt",
")",
"return",
"sum",
"(",
"num_trees_by_group",
")"
] | Returns the number of trees summed across all tree
groups. | [
"Returns",
"the",
"number",
"of",
"trees",
"summed",
"across",
"all",
"tree",
"groups",
"."
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_syntax/inspect.py#L15-L38 | train | 588 |
OpenTreeOfLife/peyotl | peyotl/collections_store/collections_umbrella.py | TreeCollectionStore | def TreeCollectionStore(repos_dict=None,
repos_par=None,
with_caching=True,
assumed_doc_version=None,
git_ssh=None,
pkey=None,
git_action_class=TreeCollectionsGitAction,
mirror_info=None,
infrastructure_commit_author='OpenTree API <[email protected]>'):
"""Factory function for a _TreeCollectionStore object.
A wrapper around the _TreeCollectionStore class instantiation for
the most common use case: a singleton _TreeCollectionStore.
If you need distinct _TreeCollectionStore objects, you'll need to
call that class directly.
"""
global _THE_TREE_COLLECTION_STORE
if _THE_TREE_COLLECTION_STORE is None:
_THE_TREE_COLLECTION_STORE = _TreeCollectionStore(repos_dict=repos_dict,
repos_par=repos_par,
with_caching=with_caching,
assumed_doc_version=assumed_doc_version,
git_ssh=git_ssh,
pkey=pkey,
git_action_class=git_action_class,
mirror_info=mirror_info,
infrastructure_commit_author=infrastructure_commit_author)
return _THE_TREE_COLLECTION_STORE | python | def TreeCollectionStore(repos_dict=None,
repos_par=None,
with_caching=True,
assumed_doc_version=None,
git_ssh=None,
pkey=None,
git_action_class=TreeCollectionsGitAction,
mirror_info=None,
infrastructure_commit_author='OpenTree API <[email protected]>'):
"""Factory function for a _TreeCollectionStore object.
A wrapper around the _TreeCollectionStore class instantiation for
the most common use case: a singleton _TreeCollectionStore.
If you need distinct _TreeCollectionStore objects, you'll need to
call that class directly.
"""
global _THE_TREE_COLLECTION_STORE
if _THE_TREE_COLLECTION_STORE is None:
_THE_TREE_COLLECTION_STORE = _TreeCollectionStore(repos_dict=repos_dict,
repos_par=repos_par,
with_caching=with_caching,
assumed_doc_version=assumed_doc_version,
git_ssh=git_ssh,
pkey=pkey,
git_action_class=git_action_class,
mirror_info=mirror_info,
infrastructure_commit_author=infrastructure_commit_author)
return _THE_TREE_COLLECTION_STORE | [
"def",
"TreeCollectionStore",
"(",
"repos_dict",
"=",
"None",
",",
"repos_par",
"=",
"None",
",",
"with_caching",
"=",
"True",
",",
"assumed_doc_version",
"=",
"None",
",",
"git_ssh",
"=",
"None",
",",
"pkey",
"=",
"None",
",",
"git_action_class",
"=",
"TreeCollectionsGitAction",
",",
"mirror_info",
"=",
"None",
",",
"infrastructure_commit_author",
"=",
"'OpenTree API <[email protected]>'",
")",
":",
"global",
"_THE_TREE_COLLECTION_STORE",
"if",
"_THE_TREE_COLLECTION_STORE",
"is",
"None",
":",
"_THE_TREE_COLLECTION_STORE",
"=",
"_TreeCollectionStore",
"(",
"repos_dict",
"=",
"repos_dict",
",",
"repos_par",
"=",
"repos_par",
",",
"with_caching",
"=",
"with_caching",
",",
"assumed_doc_version",
"=",
"assumed_doc_version",
",",
"git_ssh",
"=",
"git_ssh",
",",
"pkey",
"=",
"pkey",
",",
"git_action_class",
"=",
"git_action_class",
",",
"mirror_info",
"=",
"mirror_info",
",",
"infrastructure_commit_author",
"=",
"infrastructure_commit_author",
")",
"return",
"_THE_TREE_COLLECTION_STORE"
] | Factory function for a _TreeCollectionStore object.
A wrapper around the _TreeCollectionStore class instantiation for
the most common use case: a singleton _TreeCollectionStore.
If you need distinct _TreeCollectionStore objects, you'll need to
call that class directly. | [
"Factory",
"function",
"for",
"a",
"_TreeCollectionStore",
"object",
"."
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/collections_store/collections_umbrella.py#L287-L314 | train | 589 |
OpenTreeOfLife/peyotl | peyotl/collections_store/collections_umbrella.py | _TreeCollectionStore._slugify_internal_collection_name | def _slugify_internal_collection_name(self, json_repr):
"""Parse the JSON, find its name, return a slug of its name"""
collection = self._coerce_json_to_collection(json_repr)
if collection is None:
return None
internal_name = collection['name']
return slugify(internal_name) | python | def _slugify_internal_collection_name(self, json_repr):
"""Parse the JSON, find its name, return a slug of its name"""
collection = self._coerce_json_to_collection(json_repr)
if collection is None:
return None
internal_name = collection['name']
return slugify(internal_name) | [
"def",
"_slugify_internal_collection_name",
"(",
"self",
",",
"json_repr",
")",
":",
"collection",
"=",
"self",
".",
"_coerce_json_to_collection",
"(",
"json_repr",
")",
"if",
"collection",
"is",
"None",
":",
"return",
"None",
"internal_name",
"=",
"collection",
"[",
"'name'",
"]",
"return",
"slugify",
"(",
"internal_name",
")"
] | Parse the JSON, find its name, return a slug of its name | [
"Parse",
"the",
"JSON",
"find",
"its",
"name",
"return",
"a",
"slug",
"of",
"its",
"name"
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/collections_store/collections_umbrella.py#L238-L244 | train | 590 |
ncmiller/roku-cli | rokucli/discover.py | discover_roku | def discover_roku():
""" Search LAN for available Roku devices. Returns a Roku object. """
print("Searching for Roku devices within LAN ...")
rokus = Roku.discover()
if not rokus:
print("Unable to discover Roku devices. " +
"Try again, or manually specify the IP address with " +
"\'roku <ipaddr>\' (e.g. roku 192.168.1.130)")
return None
print("Found the following Roku devices:")
for i, r in enumerate(rokus):
# dinfo = ' '.join(re.split(', |: ', str(r.device_info))[1:3])
dinfo = ''
print("[" + str(i+1) + "] " + str(r.host) + ":" +
str(r.port) + ' (' + dinfo + ')')
print("")
if len(rokus) == 1:
print("Selecting Roku 1 by default")
return rokus[0]
else:
print("Multiple Rokus found. Select the index of the Roku to control:")
while True:
try:
query = "Select (1 to " + str(len(rokus)) + ") > "
sel = int(input(query)) - 1
if sel >= len(rokus):
raise ValueError
else:
break
except ValueError:
print("Invalid selection")
return rokus[sel] | python | def discover_roku():
""" Search LAN for available Roku devices. Returns a Roku object. """
print("Searching for Roku devices within LAN ...")
rokus = Roku.discover()
if not rokus:
print("Unable to discover Roku devices. " +
"Try again, or manually specify the IP address with " +
"\'roku <ipaddr>\' (e.g. roku 192.168.1.130)")
return None
print("Found the following Roku devices:")
for i, r in enumerate(rokus):
# dinfo = ' '.join(re.split(', |: ', str(r.device_info))[1:3])
dinfo = ''
print("[" + str(i+1) + "] " + str(r.host) + ":" +
str(r.port) + ' (' + dinfo + ')')
print("")
if len(rokus) == 1:
print("Selecting Roku 1 by default")
return rokus[0]
else:
print("Multiple Rokus found. Select the index of the Roku to control:")
while True:
try:
query = "Select (1 to " + str(len(rokus)) + ") > "
sel = int(input(query)) - 1
if sel >= len(rokus):
raise ValueError
else:
break
except ValueError:
print("Invalid selection")
return rokus[sel] | [
"def",
"discover_roku",
"(",
")",
":",
"print",
"(",
"\"Searching for Roku devices within LAN ...\"",
")",
"rokus",
"=",
"Roku",
".",
"discover",
"(",
")",
"if",
"not",
"rokus",
":",
"print",
"(",
"\"Unable to discover Roku devices. \"",
"+",
"\"Try again, or manually specify the IP address with \"",
"+",
"\"\\'roku <ipaddr>\\' (e.g. roku 192.168.1.130)\"",
")",
"return",
"None",
"print",
"(",
"\"Found the following Roku devices:\"",
")",
"for",
"i",
",",
"r",
"in",
"enumerate",
"(",
"rokus",
")",
":",
"# dinfo = ' '.join(re.split(', |: ', str(r.device_info))[1:3])",
"dinfo",
"=",
"''",
"print",
"(",
"\"[\"",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"\"] \"",
"+",
"str",
"(",
"r",
".",
"host",
")",
"+",
"\":\"",
"+",
"str",
"(",
"r",
".",
"port",
")",
"+",
"' ('",
"+",
"dinfo",
"+",
"')'",
")",
"print",
"(",
"\"\"",
")",
"if",
"len",
"(",
"rokus",
")",
"==",
"1",
":",
"print",
"(",
"\"Selecting Roku 1 by default\"",
")",
"return",
"rokus",
"[",
"0",
"]",
"else",
":",
"print",
"(",
"\"Multiple Rokus found. Select the index of the Roku to control:\"",
")",
"while",
"True",
":",
"try",
":",
"query",
"=",
"\"Select (1 to \"",
"+",
"str",
"(",
"len",
"(",
"rokus",
")",
")",
"+",
"\") > \"",
"sel",
"=",
"int",
"(",
"input",
"(",
"query",
")",
")",
"-",
"1",
"if",
"sel",
">=",
"len",
"(",
"rokus",
")",
":",
"raise",
"ValueError",
"else",
":",
"break",
"except",
"ValueError",
":",
"print",
"(",
"\"Invalid selection\"",
")",
"return",
"rokus",
"[",
"sel",
"]"
] | Search LAN for available Roku devices. Returns a Roku object. | [
"Search",
"LAN",
"for",
"available",
"Roku",
"devices",
".",
"Returns",
"a",
"Roku",
"object",
"."
] | 9101952edf9802146c794e63353abf2bf116c052 | https://github.com/ncmiller/roku-cli/blob/9101952edf9802146c794e63353abf2bf116c052/rokucli/discover.py#L6-L42 | train | 591 |
OpenTreeOfLife/peyotl | tutorials/ot-info-for-taxon-name.py | ot_tnrs_match_names | def ot_tnrs_match_names(name_list,
context_name=None,
do_approximate_matching=True,
include_dubious=False,
include_deprecated=True,
tnrs_wrapper=None):
"""Uses a peyotl wrapper around an Open Tree web service to get a list of OTT IDs matching
the `name_list`.
The tnrs_wrapper can be None (in which case the default wrapper from peyotl.sugar will be used.
All other arguments correspond to the arguments of the web-service call.
A ValueError will be raised if the `context_name` does not match one of the valid names for a
taxonomic context.
This uses the wrap_response option to create and return a TNRSRespose object around the response.
"""
if tnrs_wrapper is None:
from peyotl.sugar import tnrs
tnrs_wrapper = tnrs
match_obj = tnrs_wrapper.match_names(name_list,
context_name=context_name,
do_approximate_matching=do_approximate_matching,
include_deprecated=include_deprecated,
include_dubious=include_dubious,
wrap_response=True)
return match_obj | python | def ot_tnrs_match_names(name_list,
context_name=None,
do_approximate_matching=True,
include_dubious=False,
include_deprecated=True,
tnrs_wrapper=None):
"""Uses a peyotl wrapper around an Open Tree web service to get a list of OTT IDs matching
the `name_list`.
The tnrs_wrapper can be None (in which case the default wrapper from peyotl.sugar will be used.
All other arguments correspond to the arguments of the web-service call.
A ValueError will be raised if the `context_name` does not match one of the valid names for a
taxonomic context.
This uses the wrap_response option to create and return a TNRSRespose object around the response.
"""
if tnrs_wrapper is None:
from peyotl.sugar import tnrs
tnrs_wrapper = tnrs
match_obj = tnrs_wrapper.match_names(name_list,
context_name=context_name,
do_approximate_matching=do_approximate_matching,
include_deprecated=include_deprecated,
include_dubious=include_dubious,
wrap_response=True)
return match_obj | [
"def",
"ot_tnrs_match_names",
"(",
"name_list",
",",
"context_name",
"=",
"None",
",",
"do_approximate_matching",
"=",
"True",
",",
"include_dubious",
"=",
"False",
",",
"include_deprecated",
"=",
"True",
",",
"tnrs_wrapper",
"=",
"None",
")",
":",
"if",
"tnrs_wrapper",
"is",
"None",
":",
"from",
"peyotl",
".",
"sugar",
"import",
"tnrs",
"tnrs_wrapper",
"=",
"tnrs",
"match_obj",
"=",
"tnrs_wrapper",
".",
"match_names",
"(",
"name_list",
",",
"context_name",
"=",
"context_name",
",",
"do_approximate_matching",
"=",
"do_approximate_matching",
",",
"include_deprecated",
"=",
"include_deprecated",
",",
"include_dubious",
"=",
"include_dubious",
",",
"wrap_response",
"=",
"True",
")",
"return",
"match_obj"
] | Uses a peyotl wrapper around an Open Tree web service to get a list of OTT IDs matching
the `name_list`.
The tnrs_wrapper can be None (in which case the default wrapper from peyotl.sugar will be used.
All other arguments correspond to the arguments of the web-service call.
A ValueError will be raised if the `context_name` does not match one of the valid names for a
taxonomic context.
This uses the wrap_response option to create and return a TNRSRespose object around the response. | [
"Uses",
"a",
"peyotl",
"wrapper",
"around",
"an",
"Open",
"Tree",
"web",
"service",
"to",
"get",
"a",
"list",
"of",
"OTT",
"IDs",
"matching",
"the",
"name_list",
".",
"The",
"tnrs_wrapper",
"can",
"be",
"None",
"(",
"in",
"which",
"case",
"the",
"default",
"wrapper",
"from",
"peyotl",
".",
"sugar",
"will",
"be",
"used",
".",
"All",
"other",
"arguments",
"correspond",
"to",
"the",
"arguments",
"of",
"the",
"web",
"-",
"service",
"call",
".",
"A",
"ValueError",
"will",
"be",
"raised",
"if",
"the",
"context_name",
"does",
"not",
"match",
"one",
"of",
"the",
"valid",
"names",
"for",
"a",
"taxonomic",
"context",
".",
"This",
"uses",
"the",
"wrap_response",
"option",
"to",
"create",
"and",
"return",
"a",
"TNRSRespose",
"object",
"around",
"the",
"response",
"."
] | 5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0 | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/tutorials/ot-info-for-taxon-name.py#L10-L33 | train | 592 |
CybOXProject/mixbox | mixbox/entities.py | _objectify | def _objectify(field, value, ns_info):
"""Make `value` suitable for a binding object.
If `value` is an Entity, call to_obj() on it. Otherwise, pass it
off to the TypedField for an appropriate value.
"""
if (getattr(field.type_, "_treat_none_as_empty_list", False) and
value is None):
return []
if value is None:
return None
elif field.type_:
return value.to_obj(ns_info=ns_info)
return field.binding_value(value) | python | def _objectify(field, value, ns_info):
"""Make `value` suitable for a binding object.
If `value` is an Entity, call to_obj() on it. Otherwise, pass it
off to the TypedField for an appropriate value.
"""
if (getattr(field.type_, "_treat_none_as_empty_list", False) and
value is None):
return []
if value is None:
return None
elif field.type_:
return value.to_obj(ns_info=ns_info)
return field.binding_value(value) | [
"def",
"_objectify",
"(",
"field",
",",
"value",
",",
"ns_info",
")",
":",
"if",
"(",
"getattr",
"(",
"field",
".",
"type_",
",",
"\"_treat_none_as_empty_list\"",
",",
"False",
")",
"and",
"value",
"is",
"None",
")",
":",
"return",
"[",
"]",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"elif",
"field",
".",
"type_",
":",
"return",
"value",
".",
"to_obj",
"(",
"ns_info",
"=",
"ns_info",
")",
"return",
"field",
".",
"binding_value",
"(",
"value",
")"
] | Make `value` suitable for a binding object.
If `value` is an Entity, call to_obj() on it. Otherwise, pass it
off to the TypedField for an appropriate value. | [
"Make",
"value",
"suitable",
"for",
"a",
"binding",
"object",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/entities.py#L19-L33 | train | 593 |
CybOXProject/mixbox | mixbox/entities.py | _dictify | def _dictify(field, value):
"""Make `value` suitable for a dictionary.
* If `value` is an Entity, call to_dict() on it.
* If value is a timestamp, turn it into a string value.
* If none of the above are satisfied, return the input value
"""
if value is None:
return None
elif field.type_:
return value.to_dict()
return field.dict_value(value) | python | def _dictify(field, value):
"""Make `value` suitable for a dictionary.
* If `value` is an Entity, call to_dict() on it.
* If value is a timestamp, turn it into a string value.
* If none of the above are satisfied, return the input value
"""
if value is None:
return None
elif field.type_:
return value.to_dict()
return field.dict_value(value) | [
"def",
"_dictify",
"(",
"field",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"elif",
"field",
".",
"type_",
":",
"return",
"value",
".",
"to_dict",
"(",
")",
"return",
"field",
".",
"dict_value",
"(",
"value",
")"
] | Make `value` suitable for a dictionary.
* If `value` is an Entity, call to_dict() on it.
* If value is a timestamp, turn it into a string value.
* If none of the above are satisfied, return the input value | [
"Make",
"value",
"suitable",
"for",
"a",
"dictionary",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/entities.py#L36-L47 | train | 594 |
CybOXProject/mixbox | mixbox/entities.py | EntityFactory.from_dict | def from_dict(cls, cls_dict, fallback_xsi_type=None):
"""Parse the dictionary and return an Entity instance.
This will attempt to extract type information from the input
dictionary and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_dict: A dictionary representation of an Entity object.
fallback_xsi_type: An xsi_type to use for string input, which
doesn't have properties
Returns:
An Entity instance.
"""
if not cls_dict:
return None
if isinstance(cls_dict, six.string_types):
if not getattr(cls, "_convert_strings", False):
return cls_dict
try:
typekey = cls.dictkey(cls_dict)
except TypeError:
typekey = fallback_xsi_type
klass = cls.entity_class(typekey)
return klass.from_dict(cls_dict) | python | def from_dict(cls, cls_dict, fallback_xsi_type=None):
"""Parse the dictionary and return an Entity instance.
This will attempt to extract type information from the input
dictionary and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_dict: A dictionary representation of an Entity object.
fallback_xsi_type: An xsi_type to use for string input, which
doesn't have properties
Returns:
An Entity instance.
"""
if not cls_dict:
return None
if isinstance(cls_dict, six.string_types):
if not getattr(cls, "_convert_strings", False):
return cls_dict
try:
typekey = cls.dictkey(cls_dict)
except TypeError:
typekey = fallback_xsi_type
klass = cls.entity_class(typekey)
return klass.from_dict(cls_dict) | [
"def",
"from_dict",
"(",
"cls",
",",
"cls_dict",
",",
"fallback_xsi_type",
"=",
"None",
")",
":",
"if",
"not",
"cls_dict",
":",
"return",
"None",
"if",
"isinstance",
"(",
"cls_dict",
",",
"six",
".",
"string_types",
")",
":",
"if",
"not",
"getattr",
"(",
"cls",
",",
"\"_convert_strings\"",
",",
"False",
")",
":",
"return",
"cls_dict",
"try",
":",
"typekey",
"=",
"cls",
".",
"dictkey",
"(",
"cls_dict",
")",
"except",
"TypeError",
":",
"typekey",
"=",
"fallback_xsi_type",
"klass",
"=",
"cls",
".",
"entity_class",
"(",
"typekey",
")",
"return",
"klass",
".",
"from_dict",
"(",
"cls_dict",
")"
] | Parse the dictionary and return an Entity instance.
This will attempt to extract type information from the input
dictionary and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_dict: A dictionary representation of an Entity object.
fallback_xsi_type: An xsi_type to use for string input, which
doesn't have properties
Returns:
An Entity instance. | [
"Parse",
"the",
"dictionary",
"and",
"return",
"an",
"Entity",
"instance",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/entities.py#L137-L164 | train | 595 |
CybOXProject/mixbox | mixbox/entities.py | EntityFactory.from_obj | def from_obj(cls, cls_obj):
"""Parse the generateDS object and return an Entity instance.
This will attempt to extract type information from the input
object and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_obj: A generateDS object.
Returns:
An Entity instance.
"""
if not cls_obj:
return None
typekey = cls.objkey(cls_obj)
klass = cls.entity_class(typekey)
return klass.from_obj(cls_obj) | python | def from_obj(cls, cls_obj):
"""Parse the generateDS object and return an Entity instance.
This will attempt to extract type information from the input
object and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_obj: A generateDS object.
Returns:
An Entity instance.
"""
if not cls_obj:
return None
typekey = cls.objkey(cls_obj)
klass = cls.entity_class(typekey)
return klass.from_obj(cls_obj) | [
"def",
"from_obj",
"(",
"cls",
",",
"cls_obj",
")",
":",
"if",
"not",
"cls_obj",
":",
"return",
"None",
"typekey",
"=",
"cls",
".",
"objkey",
"(",
"cls_obj",
")",
"klass",
"=",
"cls",
".",
"entity_class",
"(",
"typekey",
")",
"return",
"klass",
".",
"from_obj",
"(",
"cls_obj",
")"
] | Parse the generateDS object and return an Entity instance.
This will attempt to extract type information from the input
object and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_obj: A generateDS object.
Returns:
An Entity instance. | [
"Parse",
"the",
"generateDS",
"object",
"and",
"return",
"an",
"Entity",
"instance",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/entities.py#L167-L185 | train | 596 |
CybOXProject/mixbox | mixbox/entities.py | Entity.typed_fields | def typed_fields(cls):
"""Return a tuple of this entity's TypedFields."""
# Checking cls._typed_fields could return a superclass _typed_fields
# value. So we check our class __dict__ which does not include
# inherited attributes.
klassdict = cls.__dict__
try:
return klassdict["_typed_fields"]
except KeyError:
fields = cls.typed_fields_with_attrnames()
cls._typed_fields = tuple(field for _, field in fields)
return cls._typed_fields | python | def typed_fields(cls):
"""Return a tuple of this entity's TypedFields."""
# Checking cls._typed_fields could return a superclass _typed_fields
# value. So we check our class __dict__ which does not include
# inherited attributes.
klassdict = cls.__dict__
try:
return klassdict["_typed_fields"]
except KeyError:
fields = cls.typed_fields_with_attrnames()
cls._typed_fields = tuple(field for _, field in fields)
return cls._typed_fields | [
"def",
"typed_fields",
"(",
"cls",
")",
":",
"# Checking cls._typed_fields could return a superclass _typed_fields",
"# value. So we check our class __dict__ which does not include",
"# inherited attributes.",
"klassdict",
"=",
"cls",
".",
"__dict__",
"try",
":",
"return",
"klassdict",
"[",
"\"_typed_fields\"",
"]",
"except",
"KeyError",
":",
"fields",
"=",
"cls",
".",
"typed_fields_with_attrnames",
"(",
")",
"cls",
".",
"_typed_fields",
"=",
"tuple",
"(",
"field",
"for",
"_",
",",
"field",
"in",
"fields",
")",
"return",
"cls",
".",
"_typed_fields"
] | Return a tuple of this entity's TypedFields. | [
"Return",
"a",
"tuple",
"of",
"this",
"entity",
"s",
"TypedFields",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/entities.py#L201-L214 | train | 597 |
CybOXProject/mixbox | mixbox/entities.py | Entity.to_obj | def to_obj(self, ns_info=None):
"""Convert to a GenerateDS binding object.
Subclasses can override this function.
Returns:
An instance of this Entity's ``_binding_class`` with properties
set from this Entity.
"""
if ns_info:
ns_info.collect(self)
# null behavior for classes that inherit from Entity but do not
# have _binding_class
if not hasattr(self, "_binding_class"):
return None
entity_obj = self._binding_class()
for field, val in six.iteritems(self._fields):
# EntityLists with no list items should be dropped
if isinstance(val, EntityList) and len(val) == 0:
val = None
elif field.multiple:
if val:
val = [_objectify(field, x, ns_info) for x in val]
else:
val = []
else:
val = _objectify(field, val, ns_info)
setattr(entity_obj, field.name, val)
self._finalize_obj(entity_obj)
return entity_obj | python | def to_obj(self, ns_info=None):
"""Convert to a GenerateDS binding object.
Subclasses can override this function.
Returns:
An instance of this Entity's ``_binding_class`` with properties
set from this Entity.
"""
if ns_info:
ns_info.collect(self)
# null behavior for classes that inherit from Entity but do not
# have _binding_class
if not hasattr(self, "_binding_class"):
return None
entity_obj = self._binding_class()
for field, val in six.iteritems(self._fields):
# EntityLists with no list items should be dropped
if isinstance(val, EntityList) and len(val) == 0:
val = None
elif field.multiple:
if val:
val = [_objectify(field, x, ns_info) for x in val]
else:
val = []
else:
val = _objectify(field, val, ns_info)
setattr(entity_obj, field.name, val)
self._finalize_obj(entity_obj)
return entity_obj | [
"def",
"to_obj",
"(",
"self",
",",
"ns_info",
"=",
"None",
")",
":",
"if",
"ns_info",
":",
"ns_info",
".",
"collect",
"(",
"self",
")",
"# null behavior for classes that inherit from Entity but do not",
"# have _binding_class",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_binding_class\"",
")",
":",
"return",
"None",
"entity_obj",
"=",
"self",
".",
"_binding_class",
"(",
")",
"for",
"field",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_fields",
")",
":",
"# EntityLists with no list items should be dropped",
"if",
"isinstance",
"(",
"val",
",",
"EntityList",
")",
"and",
"len",
"(",
"val",
")",
"==",
"0",
":",
"val",
"=",
"None",
"elif",
"field",
".",
"multiple",
":",
"if",
"val",
":",
"val",
"=",
"[",
"_objectify",
"(",
"field",
",",
"x",
",",
"ns_info",
")",
"for",
"x",
"in",
"val",
"]",
"else",
":",
"val",
"=",
"[",
"]",
"else",
":",
"val",
"=",
"_objectify",
"(",
"field",
",",
"val",
",",
"ns_info",
")",
"setattr",
"(",
"entity_obj",
",",
"field",
".",
"name",
",",
"val",
")",
"self",
".",
"_finalize_obj",
"(",
"entity_obj",
")",
"return",
"entity_obj"
] | Convert to a GenerateDS binding object.
Subclasses can override this function.
Returns:
An instance of this Entity's ``_binding_class`` with properties
set from this Entity. | [
"Convert",
"to",
"a",
"GenerateDS",
"binding",
"object",
"."
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/entities.py#L275-L309 | train | 598 |
CybOXProject/mixbox | mixbox/entities.py | Entity.to_dict | def to_dict(self):
"""Convert to a ``dict``
Subclasses can override this function.
Returns:
Python dict with keys set from this Entity.
"""
entity_dict = {}
for field, val in six.iteritems(self._fields):
if field.multiple:
if val:
val = [_dictify(field, x) for x in val]
else:
val = []
else:
val = _dictify(field, val)
# Only add non-None objects or non-empty lists
if val is not None and val != []:
entity_dict[field.key_name] = val
self._finalize_dict(entity_dict)
return entity_dict | python | def to_dict(self):
"""Convert to a ``dict``
Subclasses can override this function.
Returns:
Python dict with keys set from this Entity.
"""
entity_dict = {}
for field, val in six.iteritems(self._fields):
if field.multiple:
if val:
val = [_dictify(field, x) for x in val]
else:
val = []
else:
val = _dictify(field, val)
# Only add non-None objects or non-empty lists
if val is not None and val != []:
entity_dict[field.key_name] = val
self._finalize_dict(entity_dict)
return entity_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"entity_dict",
"=",
"{",
"}",
"for",
"field",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_fields",
")",
":",
"if",
"field",
".",
"multiple",
":",
"if",
"val",
":",
"val",
"=",
"[",
"_dictify",
"(",
"field",
",",
"x",
")",
"for",
"x",
"in",
"val",
"]",
"else",
":",
"val",
"=",
"[",
"]",
"else",
":",
"val",
"=",
"_dictify",
"(",
"field",
",",
"val",
")",
"# Only add non-None objects or non-empty lists",
"if",
"val",
"is",
"not",
"None",
"and",
"val",
"!=",
"[",
"]",
":",
"entity_dict",
"[",
"field",
".",
"key_name",
"]",
"=",
"val",
"self",
".",
"_finalize_dict",
"(",
"entity_dict",
")",
"return",
"entity_dict"
] | Convert to a ``dict``
Subclasses can override this function.
Returns:
Python dict with keys set from this Entity. | [
"Convert",
"to",
"a",
"dict"
] | 9097dae7a433f5b98c18171c4a5598f69a7d30af | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/entities.py#L318-L343 | train | 599 |