id
int32 0
252k
| 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
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
10,400
|
dadadel/pyment
|
pyment/docstring.py
|
isin_alone
|
def isin_alone(elems, line):
"""Check if an element from a list is the only element of a string.
:type elems: list
:type line: str
"""
found = False
for e in elems:
if line.strip().lower() == e.lower():
found = True
break
return found
|
python
|
def isin_alone(elems, line):
"""Check if an element from a list is the only element of a string.
:type elems: list
:type line: str
"""
found = False
for e in elems:
if line.strip().lower() == e.lower():
found = True
break
return found
|
[
"def",
"isin_alone",
"(",
"elems",
",",
"line",
")",
":",
"found",
"=",
"False",
"for",
"e",
"in",
"elems",
":",
"if",
"line",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"==",
"e",
".",
"lower",
"(",
")",
":",
"found",
"=",
"True",
"break",
"return",
"found"
] |
Check if an element from a list is the only element of a string.
:type elems: list
:type line: str
|
[
"Check",
"if",
"an",
"element",
"from",
"a",
"list",
"is",
"the",
"only",
"element",
"of",
"a",
"string",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L26-L38
|
10,401
|
dadadel/pyment
|
pyment/docstring.py
|
isin_start
|
def isin_start(elems, line):
"""Check if an element from a list starts a string.
:type elems: list
:type line: str
"""
found = False
elems = [elems] if type(elems) is not list else elems
for e in elems:
if line.lstrip().lower().startswith(e):
found = True
break
return found
|
python
|
def isin_start(elems, line):
"""Check if an element from a list starts a string.
:type elems: list
:type line: str
"""
found = False
elems = [elems] if type(elems) is not list else elems
for e in elems:
if line.lstrip().lower().startswith(e):
found = True
break
return found
|
[
"def",
"isin_start",
"(",
"elems",
",",
"line",
")",
":",
"found",
"=",
"False",
"elems",
"=",
"[",
"elems",
"]",
"if",
"type",
"(",
"elems",
")",
"is",
"not",
"list",
"else",
"elems",
"for",
"e",
"in",
"elems",
":",
"if",
"line",
".",
"lstrip",
"(",
")",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"e",
")",
":",
"found",
"=",
"True",
"break",
"return",
"found"
] |
Check if an element from a list starts a string.
:type elems: list
:type line: str
|
[
"Check",
"if",
"an",
"element",
"from",
"a",
"list",
"starts",
"a",
"string",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L41-L54
|
10,402
|
dadadel/pyment
|
pyment/docstring.py
|
isin
|
def isin(elems, line):
"""Check if an element from a list is in a string.
:type elems: list
:type line: str
"""
found = False
for e in elems:
if e in line.lower():
found = True
break
return found
|
python
|
def isin(elems, line):
"""Check if an element from a list is in a string.
:type elems: list
:type line: str
"""
found = False
for e in elems:
if e in line.lower():
found = True
break
return found
|
[
"def",
"isin",
"(",
"elems",
",",
"line",
")",
":",
"found",
"=",
"False",
"for",
"e",
"in",
"elems",
":",
"if",
"e",
"in",
"line",
".",
"lower",
"(",
")",
":",
"found",
"=",
"True",
"break",
"return",
"found"
] |
Check if an element from a list is in a string.
:type elems: list
:type line: str
|
[
"Check",
"if",
"an",
"element",
"from",
"a",
"list",
"is",
"in",
"a",
"string",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L57-L69
|
10,403
|
dadadel/pyment
|
pyment/docstring.py
|
get_leading_spaces
|
def get_leading_spaces(data):
"""Get the leading space of a string if it is not empty
:type data: str
"""
spaces = ''
m = re.match(r'^(\s*)', data)
if m:
spaces = m.group(1)
return spaces
|
python
|
def get_leading_spaces(data):
"""Get the leading space of a string if it is not empty
:type data: str
"""
spaces = ''
m = re.match(r'^(\s*)', data)
if m:
spaces = m.group(1)
return spaces
|
[
"def",
"get_leading_spaces",
"(",
"data",
")",
":",
"spaces",
"=",
"''",
"m",
"=",
"re",
".",
"match",
"(",
"r'^(\\s*)'",
",",
"data",
")",
"if",
"m",
":",
"spaces",
"=",
"m",
".",
"group",
"(",
"1",
")",
"return",
"spaces"
] |
Get the leading space of a string if it is not empty
:type data: str
|
[
"Get",
"the",
"leading",
"space",
"of",
"a",
"string",
"if",
"it",
"is",
"not",
"empty"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L72-L82
|
10,404
|
dadadel/pyment
|
pyment/docstring.py
|
DocToolsBase.get_mandatory_sections
|
def get_mandatory_sections(self):
"""Get mandatory sections"""
return [s for s in self.opt
if s not in self.optional_sections and
s not in self.excluded_sections]
|
python
|
def get_mandatory_sections(self):
"""Get mandatory sections"""
return [s for s in self.opt
if s not in self.optional_sections and
s not in self.excluded_sections]
|
[
"def",
"get_mandatory_sections",
"(",
"self",
")",
":",
"return",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"opt",
"if",
"s",
"not",
"in",
"self",
".",
"optional_sections",
"and",
"s",
"not",
"in",
"self",
".",
"excluded_sections",
"]"
] |
Get mandatory sections
|
[
"Get",
"mandatory",
"sections"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L133-L137
|
10,405
|
dadadel/pyment
|
pyment/docstring.py
|
NumpydocTools.get_raw_not_managed
|
def get_raw_not_managed(self, data):
"""Get elements not managed. They can be used as is.
:param data: the data to proceed
"""
keys = ['also', 'ref', 'note', 'other', 'example', 'method', 'attr']
elems = [self.opt[k] for k in self.opt if k in keys]
data = data.splitlines()
start = 0
init = 0
raw = ''
spaces = None
while start != -1:
start, end = self.get_next_section_lines(data[init:])
if start != -1:
init += start
if isin_alone(elems, data[init]) and \
not isin_alone([self.opt[e] for e in self.excluded_sections], data[init]):
spaces = get_leading_spaces(data[init])
if end != -1:
section = [d.replace(spaces, '', 1).rstrip() for d in data[init:init + end]]
else:
section = [d.replace(spaces, '', 1).rstrip() for d in data[init:]]
raw += '\n'.join(section) + '\n'
init += 2
return raw
|
python
|
def get_raw_not_managed(self, data):
"""Get elements not managed. They can be used as is.
:param data: the data to proceed
"""
keys = ['also', 'ref', 'note', 'other', 'example', 'method', 'attr']
elems = [self.opt[k] for k in self.opt if k in keys]
data = data.splitlines()
start = 0
init = 0
raw = ''
spaces = None
while start != -1:
start, end = self.get_next_section_lines(data[init:])
if start != -1:
init += start
if isin_alone(elems, data[init]) and \
not isin_alone([self.opt[e] for e in self.excluded_sections], data[init]):
spaces = get_leading_spaces(data[init])
if end != -1:
section = [d.replace(spaces, '', 1).rstrip() for d in data[init:init + end]]
else:
section = [d.replace(spaces, '', 1).rstrip() for d in data[init:]]
raw += '\n'.join(section) + '\n'
init += 2
return raw
|
[
"def",
"get_raw_not_managed",
"(",
"self",
",",
"data",
")",
":",
"keys",
"=",
"[",
"'also'",
",",
"'ref'",
",",
"'note'",
",",
"'other'",
",",
"'example'",
",",
"'method'",
",",
"'attr'",
"]",
"elems",
"=",
"[",
"self",
".",
"opt",
"[",
"k",
"]",
"for",
"k",
"in",
"self",
".",
"opt",
"if",
"k",
"in",
"keys",
"]",
"data",
"=",
"data",
".",
"splitlines",
"(",
")",
"start",
"=",
"0",
"init",
"=",
"0",
"raw",
"=",
"''",
"spaces",
"=",
"None",
"while",
"start",
"!=",
"-",
"1",
":",
"start",
",",
"end",
"=",
"self",
".",
"get_next_section_lines",
"(",
"data",
"[",
"init",
":",
"]",
")",
"if",
"start",
"!=",
"-",
"1",
":",
"init",
"+=",
"start",
"if",
"isin_alone",
"(",
"elems",
",",
"data",
"[",
"init",
"]",
")",
"and",
"not",
"isin_alone",
"(",
"[",
"self",
".",
"opt",
"[",
"e",
"]",
"for",
"e",
"in",
"self",
".",
"excluded_sections",
"]",
",",
"data",
"[",
"init",
"]",
")",
":",
"spaces",
"=",
"get_leading_spaces",
"(",
"data",
"[",
"init",
"]",
")",
"if",
"end",
"!=",
"-",
"1",
":",
"section",
"=",
"[",
"d",
".",
"replace",
"(",
"spaces",
",",
"''",
",",
"1",
")",
".",
"rstrip",
"(",
")",
"for",
"d",
"in",
"data",
"[",
"init",
":",
"init",
"+",
"end",
"]",
"]",
"else",
":",
"section",
"=",
"[",
"d",
".",
"replace",
"(",
"spaces",
",",
"''",
",",
"1",
")",
".",
"rstrip",
"(",
")",
"for",
"d",
"in",
"data",
"[",
"init",
":",
"]",
"]",
"raw",
"+=",
"'\\n'",
".",
"join",
"(",
"section",
")",
"+",
"'\\n'",
"init",
"+=",
"2",
"return",
"raw"
] |
Get elements not managed. They can be used as is.
:param data: the data to proceed
|
[
"Get",
"elements",
"not",
"managed",
".",
"They",
"can",
"be",
"used",
"as",
"is",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L411-L437
|
10,406
|
dadadel/pyment
|
pyment/docstring.py
|
NumpydocTools.get_key_section_header
|
def get_key_section_header(self, key, spaces):
"""Get the key of the header section
:param key: the key name
:param spaces: spaces to set at the beginning of the header
"""
header = super(NumpydocTools, self).get_key_section_header(key, spaces)
header = spaces + header + '\n' + spaces + '-' * len(header) + '\n'
return header
|
python
|
def get_key_section_header(self, key, spaces):
"""Get the key of the header section
:param key: the key name
:param spaces: spaces to set at the beginning of the header
"""
header = super(NumpydocTools, self).get_key_section_header(key, spaces)
header = spaces + header + '\n' + spaces + '-' * len(header) + '\n'
return header
|
[
"def",
"get_key_section_header",
"(",
"self",
",",
"key",
",",
"spaces",
")",
":",
"header",
"=",
"super",
"(",
"NumpydocTools",
",",
"self",
")",
".",
"get_key_section_header",
"(",
"key",
",",
"spaces",
")",
"header",
"=",
"spaces",
"+",
"header",
"+",
"'\\n'",
"+",
"spaces",
"+",
"'-'",
"*",
"len",
"(",
"header",
")",
"+",
"'\\n'",
"return",
"header"
] |
Get the key of the header section
:param key: the key name
:param spaces: spaces to set at the beginning of the header
|
[
"Get",
"the",
"key",
"of",
"the",
"header",
"section"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L439-L448
|
10,407
|
dadadel/pyment
|
pyment/docstring.py
|
DocsTools.autodetect_style
|
def autodetect_style(self, data):
"""Determine the style of a docstring,
and sets it as the default input one for the instance.
:param data: the docstring's data to recognize.
:type data: str
:returns: the style detected else 'unknown'
:rtype: str
"""
# evaluate styles with keys
found_keys = defaultdict(int)
for style in self.tagstyles:
for key in self.opt:
found_keys[style] += data.count(self.opt[key][style]['name'])
fkey = max(found_keys, key=found_keys.get)
detected_style = fkey if found_keys[fkey] else 'unknown'
# evaluate styles with groups
if detected_style == 'unknown':
found_groups = 0
found_googledoc = 0
found_numpydoc = 0
found_numpydocsep = 0
for line in data.strip().splitlines():
for key in self.groups:
found_groups += 1 if isin_start(self.groups[key], line) else 0
for key in self.googledoc:
found_googledoc += 1 if isin_start(self.googledoc[key], line) else 0
for key in self.numpydoc:
found_numpydoc += 1 if isin_start(self.numpydoc[key], line) else 0
if line.strip() and isin_alone(['-' * len(line.strip())], line):
found_numpydocsep += 1
elif isin(self.numpydoc.keywords, line):
found_numpydoc += 1
# TODO: check if not necessary to have > 1??
if found_numpydoc and found_numpydocsep:
detected_style = 'numpydoc'
elif found_googledoc >= found_groups:
detected_style = 'google'
elif found_groups:
detected_style = 'groups'
self.style['in'] = detected_style
return detected_style
|
python
|
def autodetect_style(self, data):
"""Determine the style of a docstring,
and sets it as the default input one for the instance.
:param data: the docstring's data to recognize.
:type data: str
:returns: the style detected else 'unknown'
:rtype: str
"""
# evaluate styles with keys
found_keys = defaultdict(int)
for style in self.tagstyles:
for key in self.opt:
found_keys[style] += data.count(self.opt[key][style]['name'])
fkey = max(found_keys, key=found_keys.get)
detected_style = fkey if found_keys[fkey] else 'unknown'
# evaluate styles with groups
if detected_style == 'unknown':
found_groups = 0
found_googledoc = 0
found_numpydoc = 0
found_numpydocsep = 0
for line in data.strip().splitlines():
for key in self.groups:
found_groups += 1 if isin_start(self.groups[key], line) else 0
for key in self.googledoc:
found_googledoc += 1 if isin_start(self.googledoc[key], line) else 0
for key in self.numpydoc:
found_numpydoc += 1 if isin_start(self.numpydoc[key], line) else 0
if line.strip() and isin_alone(['-' * len(line.strip())], line):
found_numpydocsep += 1
elif isin(self.numpydoc.keywords, line):
found_numpydoc += 1
# TODO: check if not necessary to have > 1??
if found_numpydoc and found_numpydocsep:
detected_style = 'numpydoc'
elif found_googledoc >= found_groups:
detected_style = 'google'
elif found_groups:
detected_style = 'groups'
self.style['in'] = detected_style
return detected_style
|
[
"def",
"autodetect_style",
"(",
"self",
",",
"data",
")",
":",
"# evaluate styles with keys",
"found_keys",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"style",
"in",
"self",
".",
"tagstyles",
":",
"for",
"key",
"in",
"self",
".",
"opt",
":",
"found_keys",
"[",
"style",
"]",
"+=",
"data",
".",
"count",
"(",
"self",
".",
"opt",
"[",
"key",
"]",
"[",
"style",
"]",
"[",
"'name'",
"]",
")",
"fkey",
"=",
"max",
"(",
"found_keys",
",",
"key",
"=",
"found_keys",
".",
"get",
")",
"detected_style",
"=",
"fkey",
"if",
"found_keys",
"[",
"fkey",
"]",
"else",
"'unknown'",
"# evaluate styles with groups",
"if",
"detected_style",
"==",
"'unknown'",
":",
"found_groups",
"=",
"0",
"found_googledoc",
"=",
"0",
"found_numpydoc",
"=",
"0",
"found_numpydocsep",
"=",
"0",
"for",
"line",
"in",
"data",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
":",
"for",
"key",
"in",
"self",
".",
"groups",
":",
"found_groups",
"+=",
"1",
"if",
"isin_start",
"(",
"self",
".",
"groups",
"[",
"key",
"]",
",",
"line",
")",
"else",
"0",
"for",
"key",
"in",
"self",
".",
"googledoc",
":",
"found_googledoc",
"+=",
"1",
"if",
"isin_start",
"(",
"self",
".",
"googledoc",
"[",
"key",
"]",
",",
"line",
")",
"else",
"0",
"for",
"key",
"in",
"self",
".",
"numpydoc",
":",
"found_numpydoc",
"+=",
"1",
"if",
"isin_start",
"(",
"self",
".",
"numpydoc",
"[",
"key",
"]",
",",
"line",
")",
"else",
"0",
"if",
"line",
".",
"strip",
"(",
")",
"and",
"isin_alone",
"(",
"[",
"'-'",
"*",
"len",
"(",
"line",
".",
"strip",
"(",
")",
")",
"]",
",",
"line",
")",
":",
"found_numpydocsep",
"+=",
"1",
"elif",
"isin",
"(",
"self",
".",
"numpydoc",
".",
"keywords",
",",
"line",
")",
":",
"found_numpydoc",
"+=",
"1",
"# TODO: check if not necessary to have > 1??",
"if",
"found_numpydoc",
"and",
"found_numpydocsep",
":",
"detected_style",
"=",
"'numpydoc'",
"elif",
"found_googledoc",
">=",
"found_groups",
":",
"detected_style",
"=",
"'google'",
"elif",
"found_groups",
":",
"detected_style",
"=",
"'groups'",
"self",
".",
"style",
"[",
"'in'",
"]",
"=",
"detected_style",
"return",
"detected_style"
] |
Determine the style of a docstring,
and sets it as the default input one for the instance.
:param data: the docstring's data to recognize.
:type data: str
:returns: the style detected else 'unknown'
:rtype: str
|
[
"Determine",
"the",
"style",
"of",
"a",
"docstring",
"and",
"sets",
"it",
"as",
"the",
"default",
"input",
"one",
"for",
"the",
"instance",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L647-L693
|
10,408
|
dadadel/pyment
|
pyment/docstring.py
|
DocsTools._get_options
|
def _get_options(self, style):
"""Get the list of keywords for a particular style
:param style: the style that the keywords are wanted
"""
return [self.opt[o][style]['name'] for o in self.opt]
|
python
|
def _get_options(self, style):
"""Get the list of keywords for a particular style
:param style: the style that the keywords are wanted
"""
return [self.opt[o][style]['name'] for o in self.opt]
|
[
"def",
"_get_options",
"(",
"self",
",",
"style",
")",
":",
"return",
"[",
"self",
".",
"opt",
"[",
"o",
"]",
"[",
"style",
"]",
"[",
"'name'",
"]",
"for",
"o",
"in",
"self",
".",
"opt",
"]"
] |
Get the list of keywords for a particular style
:param style: the style that the keywords are wanted
|
[
"Get",
"the",
"list",
"of",
"keywords",
"for",
"a",
"particular",
"style"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L713-L719
|
10,409
|
dadadel/pyment
|
pyment/docstring.py
|
DocsTools.get_group_key_line
|
def get_group_key_line(self, data, key):
"""Get the next group-style key's line number.
:param data: string to parse
:param key: the key category
:returns: the found line number else -1
"""
idx = -1
for i, line in enumerate(data.splitlines()):
if isin_start(self.groups[key], line):
idx = i
return idx
|
python
|
def get_group_key_line(self, data, key):
"""Get the next group-style key's line number.
:param data: string to parse
:param key: the key category
:returns: the found line number else -1
"""
idx = -1
for i, line in enumerate(data.splitlines()):
if isin_start(self.groups[key], line):
idx = i
return idx
|
[
"def",
"get_group_key_line",
"(",
"self",
",",
"data",
",",
"key",
")",
":",
"idx",
"=",
"-",
"1",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"data",
".",
"splitlines",
"(",
")",
")",
":",
"if",
"isin_start",
"(",
"self",
".",
"groups",
"[",
"key",
"]",
",",
"line",
")",
":",
"idx",
"=",
"i",
"return",
"idx"
] |
Get the next group-style key's line number.
:param data: string to parse
:param key: the key category
:returns: the found line number else -1
|
[
"Get",
"the",
"next",
"group",
"-",
"style",
"key",
"s",
"line",
"number",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L776-L788
|
10,410
|
dadadel/pyment
|
pyment/docstring.py
|
DocsTools.get_group_key_index
|
def get_group_key_index(self, data, key):
"""Get the next groups style's starting line index for a key
:param data: string to parse
:param key: the key category
:returns: the index if found else -1
"""
idx = -1
li = self.get_group_key_line(data, key)
if li != -1:
idx = 0
for line in data.splitlines()[:li]:
idx += len(line) + len('\n')
return idx
|
python
|
def get_group_key_index(self, data, key):
"""Get the next groups style's starting line index for a key
:param data: string to parse
:param key: the key category
:returns: the index if found else -1
"""
idx = -1
li = self.get_group_key_line(data, key)
if li != -1:
idx = 0
for line in data.splitlines()[:li]:
idx += len(line) + len('\n')
return idx
|
[
"def",
"get_group_key_index",
"(",
"self",
",",
"data",
",",
"key",
")",
":",
"idx",
"=",
"-",
"1",
"li",
"=",
"self",
".",
"get_group_key_line",
"(",
"data",
",",
"key",
")",
"if",
"li",
"!=",
"-",
"1",
":",
"idx",
"=",
"0",
"for",
"line",
"in",
"data",
".",
"splitlines",
"(",
")",
"[",
":",
"li",
"]",
":",
"idx",
"+=",
"len",
"(",
"line",
")",
"+",
"len",
"(",
"'\\n'",
")",
"return",
"idx"
] |
Get the next groups style's starting line index for a key
:param data: string to parse
:param key: the key category
:returns: the index if found else -1
|
[
"Get",
"the",
"next",
"groups",
"style",
"s",
"starting",
"line",
"index",
"for",
"a",
"key"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L794-L808
|
10,411
|
dadadel/pyment
|
pyment/docstring.py
|
DocsTools.get_group_line
|
def get_group_line(self, data):
"""Get the next group-style key's line.
:param data: the data to proceed
:returns: the line number
"""
idx = -1
for key in self.groups:
i = self.get_group_key_line(data, key)
if (i < idx and i != -1) or idx == -1:
idx = i
return idx
|
python
|
def get_group_line(self, data):
"""Get the next group-style key's line.
:param data: the data to proceed
:returns: the line number
"""
idx = -1
for key in self.groups:
i = self.get_group_key_line(data, key)
if (i < idx and i != -1) or idx == -1:
idx = i
return idx
|
[
"def",
"get_group_line",
"(",
"self",
",",
"data",
")",
":",
"idx",
"=",
"-",
"1",
"for",
"key",
"in",
"self",
".",
"groups",
":",
"i",
"=",
"self",
".",
"get_group_key_line",
"(",
"data",
",",
"key",
")",
"if",
"(",
"i",
"<",
"idx",
"and",
"i",
"!=",
"-",
"1",
")",
"or",
"idx",
"==",
"-",
"1",
":",
"idx",
"=",
"i",
"return",
"idx"
] |
Get the next group-style key's line.
:param data: the data to proceed
:returns: the line number
|
[
"Get",
"the",
"next",
"group",
"-",
"style",
"key",
"s",
"line",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L810-L822
|
10,412
|
dadadel/pyment
|
pyment/docstring.py
|
DocsTools.get_group_index
|
def get_group_index(self, data):
"""Get the next groups style's starting line index
:param data: string to parse
:returns: the index if found else -1
"""
idx = -1
li = self.get_group_line(data)
if li != -1:
idx = 0
for line in data.splitlines()[:li]:
idx += len(line) + len('\n')
return idx
|
python
|
def get_group_index(self, data):
"""Get the next groups style's starting line index
:param data: string to parse
:returns: the index if found else -1
"""
idx = -1
li = self.get_group_line(data)
if li != -1:
idx = 0
for line in data.splitlines()[:li]:
idx += len(line) + len('\n')
return idx
|
[
"def",
"get_group_index",
"(",
"self",
",",
"data",
")",
":",
"idx",
"=",
"-",
"1",
"li",
"=",
"self",
".",
"get_group_line",
"(",
"data",
")",
"if",
"li",
"!=",
"-",
"1",
":",
"idx",
"=",
"0",
"for",
"line",
"in",
"data",
".",
"splitlines",
"(",
")",
"[",
":",
"li",
"]",
":",
"idx",
"+=",
"len",
"(",
"line",
")",
"+",
"len",
"(",
"'\\n'",
")",
"return",
"idx"
] |
Get the next groups style's starting line index
:param data: string to parse
:returns: the index if found else -1
|
[
"Get",
"the",
"next",
"groups",
"style",
"s",
"starting",
"line",
"index"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L824-L837
|
10,413
|
dadadel/pyment
|
pyment/docstring.py
|
DocsTools.get_key_index
|
def get_key_index(self, data, key, starting=True):
"""Get from a docstring the next option with a given key.
:param data: string to parse
:param starting: does the key element must start the line (Default value = True)
:type starting: boolean
:param key: the key category. Can be 'param', 'type', 'return', ...
:returns: index of found element else -1
:rtype: integer
"""
key = self.opt[key][self.style['in']]['name']
if key.startswith(':returns'):
data = data.replace(':return:', ':returns:') # see issue 9
idx = len(data)
ini = 0
loop = True
if key in data:
while loop:
i = data.find(key)
if i != -1:
if starting:
if not data[:i].rstrip(' \t').endswith('\n') and len(data[:i].strip()) > 0:
ini = i + 1
data = data[ini:]
else:
idx = ini + i
loop = False
else:
idx = ini + i
loop = False
else:
loop = False
if idx == len(data):
idx = -1
return idx
|
python
|
def get_key_index(self, data, key, starting=True):
"""Get from a docstring the next option with a given key.
:param data: string to parse
:param starting: does the key element must start the line (Default value = True)
:type starting: boolean
:param key: the key category. Can be 'param', 'type', 'return', ...
:returns: index of found element else -1
:rtype: integer
"""
key = self.opt[key][self.style['in']]['name']
if key.startswith(':returns'):
data = data.replace(':return:', ':returns:') # see issue 9
idx = len(data)
ini = 0
loop = True
if key in data:
while loop:
i = data.find(key)
if i != -1:
if starting:
if not data[:i].rstrip(' \t').endswith('\n') and len(data[:i].strip()) > 0:
ini = i + 1
data = data[ini:]
else:
idx = ini + i
loop = False
else:
idx = ini + i
loop = False
else:
loop = False
if idx == len(data):
idx = -1
return idx
|
[
"def",
"get_key_index",
"(",
"self",
",",
"data",
",",
"key",
",",
"starting",
"=",
"True",
")",
":",
"key",
"=",
"self",
".",
"opt",
"[",
"key",
"]",
"[",
"self",
".",
"style",
"[",
"'in'",
"]",
"]",
"[",
"'name'",
"]",
"if",
"key",
".",
"startswith",
"(",
"':returns'",
")",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"':return:'",
",",
"':returns:'",
")",
"# see issue 9",
"idx",
"=",
"len",
"(",
"data",
")",
"ini",
"=",
"0",
"loop",
"=",
"True",
"if",
"key",
"in",
"data",
":",
"while",
"loop",
":",
"i",
"=",
"data",
".",
"find",
"(",
"key",
")",
"if",
"i",
"!=",
"-",
"1",
":",
"if",
"starting",
":",
"if",
"not",
"data",
"[",
":",
"i",
"]",
".",
"rstrip",
"(",
"' \\t'",
")",
".",
"endswith",
"(",
"'\\n'",
")",
"and",
"len",
"(",
"data",
"[",
":",
"i",
"]",
".",
"strip",
"(",
")",
")",
">",
"0",
":",
"ini",
"=",
"i",
"+",
"1",
"data",
"=",
"data",
"[",
"ini",
":",
"]",
"else",
":",
"idx",
"=",
"ini",
"+",
"i",
"loop",
"=",
"False",
"else",
":",
"idx",
"=",
"ini",
"+",
"i",
"loop",
"=",
"False",
"else",
":",
"loop",
"=",
"False",
"if",
"idx",
"==",
"len",
"(",
"data",
")",
":",
"idx",
"=",
"-",
"1",
"return",
"idx"
] |
Get from a docstring the next option with a given key.
:param data: string to parse
:param starting: does the key element must start the line (Default value = True)
:type starting: boolean
:param key: the key category. Can be 'param', 'type', 'return', ...
:returns: index of found element else -1
:rtype: integer
|
[
"Get",
"from",
"a",
"docstring",
"the",
"next",
"option",
"with",
"a",
"given",
"key",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L839-L874
|
10,414
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._extract_docs_description
|
def _extract_docs_description(self):
"""Extract main description from docstring"""
# FIXME: the indentation of descriptions is lost
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
if self.dst.style['in'] == 'groups':
idx = self.dst.get_group_index(data)
elif self.dst.style['in'] == 'google':
lines = data.splitlines()
line_num = self.dst.googledoc.get_next_section_start_line(lines)
if line_num == -1:
idx = -1
else:
idx = len('\n'.join(lines[:line_num]))
elif self.dst.style['in'] == 'numpydoc':
lines = data.splitlines()
line_num = self.dst.numpydoc.get_next_section_start_line(lines)
if line_num == -1:
idx = -1
else:
idx = len('\n'.join(lines[:line_num]))
elif self.dst.style['in'] == 'unknown':
idx = -1
else:
idx = self.dst.get_elem_index(data)
if idx == 0:
self.docs['in']['desc'] = ''
elif idx == -1:
self.docs['in']['desc'] = data
else:
self.docs['in']['desc'] = data[:idx]
|
python
|
def _extract_docs_description(self):
"""Extract main description from docstring"""
# FIXME: the indentation of descriptions is lost
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
if self.dst.style['in'] == 'groups':
idx = self.dst.get_group_index(data)
elif self.dst.style['in'] == 'google':
lines = data.splitlines()
line_num = self.dst.googledoc.get_next_section_start_line(lines)
if line_num == -1:
idx = -1
else:
idx = len('\n'.join(lines[:line_num]))
elif self.dst.style['in'] == 'numpydoc':
lines = data.splitlines()
line_num = self.dst.numpydoc.get_next_section_start_line(lines)
if line_num == -1:
idx = -1
else:
idx = len('\n'.join(lines[:line_num]))
elif self.dst.style['in'] == 'unknown':
idx = -1
else:
idx = self.dst.get_elem_index(data)
if idx == 0:
self.docs['in']['desc'] = ''
elif idx == -1:
self.docs['in']['desc'] = data
else:
self.docs['in']['desc'] = data[:idx]
|
[
"def",
"_extract_docs_description",
"(",
"self",
")",
":",
"# FIXME: the indentation of descriptions is lost",
"data",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"d",
".",
"rstrip",
"(",
")",
".",
"replace",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
",",
"''",
",",
"1",
")",
"for",
"d",
"in",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raw'",
"]",
".",
"splitlines",
"(",
")",
"]",
")",
"if",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'groups'",
":",
"idx",
"=",
"self",
".",
"dst",
".",
"get_group_index",
"(",
"data",
")",
"elif",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'google'",
":",
"lines",
"=",
"data",
".",
"splitlines",
"(",
")",
"line_num",
"=",
"self",
".",
"dst",
".",
"googledoc",
".",
"get_next_section_start_line",
"(",
"lines",
")",
"if",
"line_num",
"==",
"-",
"1",
":",
"idx",
"=",
"-",
"1",
"else",
":",
"idx",
"=",
"len",
"(",
"'\\n'",
".",
"join",
"(",
"lines",
"[",
":",
"line_num",
"]",
")",
")",
"elif",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'numpydoc'",
":",
"lines",
"=",
"data",
".",
"splitlines",
"(",
")",
"line_num",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_next_section_start_line",
"(",
"lines",
")",
"if",
"line_num",
"==",
"-",
"1",
":",
"idx",
"=",
"-",
"1",
"else",
":",
"idx",
"=",
"len",
"(",
"'\\n'",
".",
"join",
"(",
"lines",
"[",
":",
"line_num",
"]",
")",
")",
"elif",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'unknown'",
":",
"idx",
"=",
"-",
"1",
"else",
":",
"idx",
"=",
"self",
".",
"dst",
".",
"get_elem_index",
"(",
"data",
")",
"if",
"idx",
"==",
"0",
":",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'desc'",
"]",
"=",
"''",
"elif",
"idx",
"==",
"-",
"1",
":",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'desc'",
"]",
"=",
"data",
"else",
":",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'desc'",
"]",
"=",
"data",
"[",
":",
"idx",
"]"
] |
Extract main description from docstring
|
[
"Extract",
"main",
"description",
"from",
"docstring"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1387-L1416
|
10,415
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._extract_groupstyle_docs_params
|
def _extract_groupstyle_docs_params(self):
"""Extract group style parameters"""
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
idx = self.dst.get_group_key_line(data, 'param')
if idx >= 0:
data = data.splitlines()[idx + 1:]
end = self.dst.get_group_line('\n'.join(data))
end = end if end != -1 else len(data)
for i in range(end):
# FIXME: see how retrieve multiline param description and how get type
line = data[i]
param = None
desc = ''
ptype = ''
m = re.match(r'^\W*(\w+)[\W\s]+(\w[\s\w]+)', line.strip())
if m:
param = m.group(1).strip()
desc = m.group(2).strip()
else:
m = re.match(r'^\W*(\w+)\W*', line.strip())
if m:
param = m.group(1).strip()
if param:
self.docs['in']['params'].append((param, desc, ptype))
|
python
|
def _extract_groupstyle_docs_params(self):
"""Extract group style parameters"""
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
idx = self.dst.get_group_key_line(data, 'param')
if idx >= 0:
data = data.splitlines()[idx + 1:]
end = self.dst.get_group_line('\n'.join(data))
end = end if end != -1 else len(data)
for i in range(end):
# FIXME: see how retrieve multiline param description and how get type
line = data[i]
param = None
desc = ''
ptype = ''
m = re.match(r'^\W*(\w+)[\W\s]+(\w[\s\w]+)', line.strip())
if m:
param = m.group(1).strip()
desc = m.group(2).strip()
else:
m = re.match(r'^\W*(\w+)\W*', line.strip())
if m:
param = m.group(1).strip()
if param:
self.docs['in']['params'].append((param, desc, ptype))
|
[
"def",
"_extract_groupstyle_docs_params",
"(",
"self",
")",
":",
"data",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"d",
".",
"rstrip",
"(",
")",
".",
"replace",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
",",
"''",
",",
"1",
")",
"for",
"d",
"in",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raw'",
"]",
".",
"splitlines",
"(",
")",
"]",
")",
"idx",
"=",
"self",
".",
"dst",
".",
"get_group_key_line",
"(",
"data",
",",
"'param'",
")",
"if",
"idx",
">=",
"0",
":",
"data",
"=",
"data",
".",
"splitlines",
"(",
")",
"[",
"idx",
"+",
"1",
":",
"]",
"end",
"=",
"self",
".",
"dst",
".",
"get_group_line",
"(",
"'\\n'",
".",
"join",
"(",
"data",
")",
")",
"end",
"=",
"end",
"if",
"end",
"!=",
"-",
"1",
"else",
"len",
"(",
"data",
")",
"for",
"i",
"in",
"range",
"(",
"end",
")",
":",
"# FIXME: see how retrieve multiline param description and how get type",
"line",
"=",
"data",
"[",
"i",
"]",
"param",
"=",
"None",
"desc",
"=",
"''",
"ptype",
"=",
"''",
"m",
"=",
"re",
".",
"match",
"(",
"r'^\\W*(\\w+)[\\W\\s]+(\\w[\\s\\w]+)'",
",",
"line",
".",
"strip",
"(",
")",
")",
"if",
"m",
":",
"param",
"=",
"m",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"desc",
"=",
"m",
".",
"group",
"(",
"2",
")",
".",
"strip",
"(",
")",
"else",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'^\\W*(\\w+)\\W*'",
",",
"line",
".",
"strip",
"(",
")",
")",
"if",
"m",
":",
"param",
"=",
"m",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"if",
"param",
":",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'params'",
"]",
".",
"append",
"(",
"(",
"param",
",",
"desc",
",",
"ptype",
")",
")"
] |
Extract group style parameters
|
[
"Extract",
"group",
"style",
"parameters"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1418-L1441
|
10,416
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._extract_docs_return
|
def _extract_docs_return(self):
"""Extract return description and type"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
self.docs['in']['return'] = self.dst.numpydoc.get_return_list(data)
self.docs['in']['rtype'] = None
# TODO: fix this
elif self.dst.style['in'] == 'google':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
self.docs['in']['return'] = self.dst.googledoc.get_return_list(data)
self.docs['in']['rtype'] = None
elif self.dst.style['in'] == 'groups':
self._extract_groupstyle_docs_return()
elif self.dst.style['in'] in ['javadoc', 'reST']:
self._extract_tagstyle_docs_return()
|
python
|
def _extract_docs_return(self):
"""Extract return description and type"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
self.docs['in']['return'] = self.dst.numpydoc.get_return_list(data)
self.docs['in']['rtype'] = None
# TODO: fix this
elif self.dst.style['in'] == 'google':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
self.docs['in']['return'] = self.dst.googledoc.get_return_list(data)
self.docs['in']['rtype'] = None
elif self.dst.style['in'] == 'groups':
self._extract_groupstyle_docs_return()
elif self.dst.style['in'] in ['javadoc', 'reST']:
self._extract_tagstyle_docs_return()
|
[
"def",
"_extract_docs_return",
"(",
"self",
")",
":",
"if",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'numpydoc'",
":",
"data",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"d",
".",
"rstrip",
"(",
")",
".",
"replace",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
",",
"''",
",",
"1",
")",
"for",
"d",
"in",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raw'",
"]",
".",
"splitlines",
"(",
")",
"]",
")",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'return'",
"]",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_return_list",
"(",
"data",
")",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'rtype'",
"]",
"=",
"None",
"# TODO: fix this",
"elif",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'google'",
":",
"data",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"d",
".",
"rstrip",
"(",
")",
".",
"replace",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
",",
"''",
",",
"1",
")",
"for",
"d",
"in",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raw'",
"]",
".",
"splitlines",
"(",
")",
"]",
")",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'return'",
"]",
"=",
"self",
".",
"dst",
".",
"googledoc",
".",
"get_return_list",
"(",
"data",
")",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'rtype'",
"]",
"=",
"None",
"elif",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'groups'",
":",
"self",
".",
"_extract_groupstyle_docs_return",
"(",
")",
"elif",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"in",
"[",
"'javadoc'",
",",
"'reST'",
"]",
":",
"self",
".",
"_extract_tagstyle_docs_return",
"(",
")"
] |
Extract return description and type
|
[
"Extract",
"return",
"description",
"and",
"type"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1585-L1599
|
10,417
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._extract_docs_other
|
def _extract_docs_other(self):
"""Extract other specific sections"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
lst = self.dst.numpydoc.get_list_key(data, 'also')
lst = self.dst.numpydoc.get_list_key(data, 'ref')
lst = self.dst.numpydoc.get_list_key(data, 'note')
lst = self.dst.numpydoc.get_list_key(data, 'other')
lst = self.dst.numpydoc.get_list_key(data, 'example')
lst = self.dst.numpydoc.get_list_key(data, 'attr')
|
python
|
def _extract_docs_other(self):
"""Extract other specific sections"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
lst = self.dst.numpydoc.get_list_key(data, 'also')
lst = self.dst.numpydoc.get_list_key(data, 'ref')
lst = self.dst.numpydoc.get_list_key(data, 'note')
lst = self.dst.numpydoc.get_list_key(data, 'other')
lst = self.dst.numpydoc.get_list_key(data, 'example')
lst = self.dst.numpydoc.get_list_key(data, 'attr')
|
[
"def",
"_extract_docs_other",
"(",
"self",
")",
":",
"if",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'numpydoc'",
":",
"data",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"d",
".",
"rstrip",
"(",
")",
".",
"replace",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
",",
"''",
",",
"1",
")",
"for",
"d",
"in",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raw'",
"]",
".",
"splitlines",
"(",
")",
"]",
")",
"lst",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_list_key",
"(",
"data",
",",
"'also'",
")",
"lst",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_list_key",
"(",
"data",
",",
"'ref'",
")",
"lst",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_list_key",
"(",
"data",
",",
"'note'",
")",
"lst",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_list_key",
"(",
"data",
",",
"'other'",
")",
"lst",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_list_key",
"(",
"data",
",",
"'example'",
")",
"lst",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_list_key",
"(",
"data",
",",
"'attr'",
")"
] |
Extract other specific sections
|
[
"Extract",
"other",
"specific",
"sections"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1601-L1610
|
10,418
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._set_desc
|
def _set_desc(self):
"""Sets the global description if any"""
# TODO: manage different in/out styles
if self.docs['in']['desc']:
self.docs['out']['desc'] = self.docs['in']['desc']
else:
self.docs['out']['desc'] = ''
|
python
|
def _set_desc(self):
"""Sets the global description if any"""
# TODO: manage different in/out styles
if self.docs['in']['desc']:
self.docs['out']['desc'] = self.docs['in']['desc']
else:
self.docs['out']['desc'] = ''
|
[
"def",
"_set_desc",
"(",
"self",
")",
":",
"# TODO: manage different in/out styles",
"if",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'desc'",
"]",
":",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'desc'",
"]",
"=",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'desc'",
"]",
"else",
":",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'desc'",
"]",
"=",
"''"
] |
Sets the global description if any
|
[
"Sets",
"the",
"global",
"description",
"if",
"any"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1638-L1644
|
10,419
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._set_params
|
def _set_params(self):
"""Sets the parameters with types, descriptions and default value if any"""
# TODO: manage different in/out styles
if self.docs['in']['params']:
# list of parameters is like: (name, description, type)
self.docs['out']['params'] = list(self.docs['in']['params'])
for e in self.element['params']:
if type(e) is tuple:
# tuple is: (name, default)
param = e[0]
else:
param = e
found = False
for i, p in enumerate(self.docs['out']['params']):
if param == p[0]:
found = True
# add default value if any
if type(e) is tuple:
# param will contain: (name, desc, type, default)
self.docs['out']['params'][i] = (p[0], p[1], p[2], e[1])
if not found:
if type(e) is tuple:
p = (param, '', None, e[1])
else:
p = (param, '', None, None)
self.docs['out']['params'].append(p)
|
python
|
def _set_params(self):
"""Sets the parameters with types, descriptions and default value if any"""
# TODO: manage different in/out styles
if self.docs['in']['params']:
# list of parameters is like: (name, description, type)
self.docs['out']['params'] = list(self.docs['in']['params'])
for e in self.element['params']:
if type(e) is tuple:
# tuple is: (name, default)
param = e[0]
else:
param = e
found = False
for i, p in enumerate(self.docs['out']['params']):
if param == p[0]:
found = True
# add default value if any
if type(e) is tuple:
# param will contain: (name, desc, type, default)
self.docs['out']['params'][i] = (p[0], p[1], p[2], e[1])
if not found:
if type(e) is tuple:
p = (param, '', None, e[1])
else:
p = (param, '', None, None)
self.docs['out']['params'].append(p)
|
[
"def",
"_set_params",
"(",
"self",
")",
":",
"# TODO: manage different in/out styles",
"if",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'params'",
"]",
":",
"# list of parameters is like: (name, description, type)",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'params'",
"]",
"=",
"list",
"(",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'params'",
"]",
")",
"for",
"e",
"in",
"self",
".",
"element",
"[",
"'params'",
"]",
":",
"if",
"type",
"(",
"e",
")",
"is",
"tuple",
":",
"# tuple is: (name, default)",
"param",
"=",
"e",
"[",
"0",
"]",
"else",
":",
"param",
"=",
"e",
"found",
"=",
"False",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'params'",
"]",
")",
":",
"if",
"param",
"==",
"p",
"[",
"0",
"]",
":",
"found",
"=",
"True",
"# add default value if any",
"if",
"type",
"(",
"e",
")",
"is",
"tuple",
":",
"# param will contain: (name, desc, type, default)",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'params'",
"]",
"[",
"i",
"]",
"=",
"(",
"p",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
",",
"e",
"[",
"1",
"]",
")",
"if",
"not",
"found",
":",
"if",
"type",
"(",
"e",
")",
"is",
"tuple",
":",
"p",
"=",
"(",
"param",
",",
"''",
",",
"None",
",",
"e",
"[",
"1",
"]",
")",
"else",
":",
"p",
"=",
"(",
"param",
",",
"''",
",",
"None",
",",
"None",
")",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'params'",
"]",
".",
"append",
"(",
"p",
")"
] |
Sets the parameters with types, descriptions and default value if any
|
[
"Sets",
"the",
"parameters",
"with",
"types",
"descriptions",
"and",
"default",
"value",
"if",
"any"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1646-L1671
|
10,420
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._set_raises
|
def _set_raises(self):
"""Sets the raises and descriptions"""
# TODO: manage different in/out styles
# manage setting if not mandatory for numpy but optional
if self.docs['in']['raises']:
if self.dst.style['out'] != 'numpydoc' or self.dst.style['in'] == 'numpydoc' or \
(self.dst.style['out'] == 'numpydoc' and
'raise' not in self.dst.numpydoc.get_excluded_sections()):
# list of parameters is like: (name, description)
self.docs['out']['raises'] = list(self.docs['in']['raises'])
|
python
|
def _set_raises(self):
"""Sets the raises and descriptions"""
# TODO: manage different in/out styles
# manage setting if not mandatory for numpy but optional
if self.docs['in']['raises']:
if self.dst.style['out'] != 'numpydoc' or self.dst.style['in'] == 'numpydoc' or \
(self.dst.style['out'] == 'numpydoc' and
'raise' not in self.dst.numpydoc.get_excluded_sections()):
# list of parameters is like: (name, description)
self.docs['out']['raises'] = list(self.docs['in']['raises'])
|
[
"def",
"_set_raises",
"(",
"self",
")",
":",
"# TODO: manage different in/out styles",
"# manage setting if not mandatory for numpy but optional",
"if",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raises'",
"]",
":",
"if",
"self",
".",
"dst",
".",
"style",
"[",
"'out'",
"]",
"!=",
"'numpydoc'",
"or",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'numpydoc'",
"or",
"(",
"self",
".",
"dst",
".",
"style",
"[",
"'out'",
"]",
"==",
"'numpydoc'",
"and",
"'raise'",
"not",
"in",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_excluded_sections",
"(",
")",
")",
":",
"# list of parameters is like: (name, description)",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'raises'",
"]",
"=",
"list",
"(",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raises'",
"]",
")"
] |
Sets the raises and descriptions
|
[
"Sets",
"the",
"raises",
"and",
"descriptions"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1673-L1682
|
10,421
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._set_return
|
def _set_return(self):
"""Sets the return parameter with description and rtype if any"""
# TODO: manage return retrieved from element code (external)
# TODO: manage different in/out styles
if type(self.docs['in']['return']) is list and self.dst.style['out'] not in ['groups', 'numpydoc', 'google']:
# TODO: manage return names
# manage not setting return if not mandatory for numpy
lst = self.docs['in']['return']
if lst:
if lst[0][0] is not None:
self.docs['out']['return'] = "%s-> %s" % (lst[0][0], lst[0][1])
else:
self.docs['out']['return'] = lst[0][1]
self.docs['out']['rtype'] = lst[0][2]
else:
self.docs['out']['return'] = self.docs['in']['return']
self.docs['out']['rtype'] = self.docs['in']['rtype']
|
python
|
def _set_return(self):
"""Sets the return parameter with description and rtype if any"""
# TODO: manage return retrieved from element code (external)
# TODO: manage different in/out styles
if type(self.docs['in']['return']) is list and self.dst.style['out'] not in ['groups', 'numpydoc', 'google']:
# TODO: manage return names
# manage not setting return if not mandatory for numpy
lst = self.docs['in']['return']
if lst:
if lst[0][0] is not None:
self.docs['out']['return'] = "%s-> %s" % (lst[0][0], lst[0][1])
else:
self.docs['out']['return'] = lst[0][1]
self.docs['out']['rtype'] = lst[0][2]
else:
self.docs['out']['return'] = self.docs['in']['return']
self.docs['out']['rtype'] = self.docs['in']['rtype']
|
[
"def",
"_set_return",
"(",
"self",
")",
":",
"# TODO: manage return retrieved from element code (external)",
"# TODO: manage different in/out styles",
"if",
"type",
"(",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'return'",
"]",
")",
"is",
"list",
"and",
"self",
".",
"dst",
".",
"style",
"[",
"'out'",
"]",
"not",
"in",
"[",
"'groups'",
",",
"'numpydoc'",
",",
"'google'",
"]",
":",
"# TODO: manage return names",
"# manage not setting return if not mandatory for numpy",
"lst",
"=",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'return'",
"]",
"if",
"lst",
":",
"if",
"lst",
"[",
"0",
"]",
"[",
"0",
"]",
"is",
"not",
"None",
":",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'return'",
"]",
"=",
"\"%s-> %s\"",
"%",
"(",
"lst",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"lst",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"else",
":",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'return'",
"]",
"=",
"lst",
"[",
"0",
"]",
"[",
"1",
"]",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'rtype'",
"]",
"=",
"lst",
"[",
"0",
"]",
"[",
"2",
"]",
"else",
":",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'return'",
"]",
"=",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'return'",
"]",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'rtype'",
"]",
"=",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'rtype'",
"]"
] |
Sets the return parameter with description and rtype if any
|
[
"Sets",
"the",
"return",
"parameter",
"with",
"description",
"and",
"rtype",
"if",
"any"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1684-L1700
|
10,422
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._set_other
|
def _set_other(self):
"""Sets other specific sections"""
# manage not setting if not mandatory for numpy
if self.dst.style['in'] == 'numpydoc':
if self.docs['in']['raw'] is not None:
self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw'])
elif 'post' not in self.docs['out'] or self.docs['out']['post'] is None:
self.docs['out']['post'] = ''
|
python
|
def _set_other(self):
"""Sets other specific sections"""
# manage not setting if not mandatory for numpy
if self.dst.style['in'] == 'numpydoc':
if self.docs['in']['raw'] is not None:
self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw'])
elif 'post' not in self.docs['out'] or self.docs['out']['post'] is None:
self.docs['out']['post'] = ''
|
[
"def",
"_set_other",
"(",
"self",
")",
":",
"# manage not setting if not mandatory for numpy",
"if",
"self",
".",
"dst",
".",
"style",
"[",
"'in'",
"]",
"==",
"'numpydoc'",
":",
"if",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raw'",
"]",
"is",
"not",
"None",
":",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'post'",
"]",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"get_raw_not_managed",
"(",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'raw'",
"]",
")",
"elif",
"'post'",
"not",
"in",
"self",
".",
"docs",
"[",
"'out'",
"]",
"or",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'post'",
"]",
"is",
"None",
":",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'post'",
"]",
"=",
"''"
] |
Sets other specific sections
|
[
"Sets",
"other",
"specific",
"sections"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1702-L1709
|
10,423
|
dadadel/pyment
|
pyment/docstring.py
|
DocString._set_raw
|
def _set_raw(self):
"""Sets the output raw docstring"""
sep = self.dst.get_sep(target='out')
sep = sep + ' ' if sep != ' ' else sep
with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + l if i > 0 else l for i, l in enumerate(s.splitlines())])
# sets the description section
raw = self.docs['out']['spaces'] + self.quotes
desc = self.docs['out']['desc'].strip()
if not desc or not desc.count('\n'):
if not self.docs['out']['params'] and not self.docs['out']['return'] and not self.docs['out']['rtype'] and not self.docs['out']['raises']:
raw += desc if desc else self.trailing_space
raw += self.quotes
self.docs['out']['raw'] = raw.rstrip()
return
if not self.first_line:
raw += '\n' + self.docs['out']['spaces']
raw += with_space(self.docs['out']['desc']).strip() + '\n'
# sets the parameters section
raw += self._set_raw_params(sep)
# sets the return section
raw += self._set_raw_return(sep)
# sets the raises section
raw += self._set_raw_raise(sep)
# sets post specific if any
if 'post' in self.docs['out']:
raw += self.docs['out']['spaces'] + with_space(self.docs['out']['post']).strip() + '\n'
# sets the doctests if any
if 'doctests' in self.docs['out']:
raw += self.docs['out']['spaces'] + with_space(self.docs['out']['doctests']).strip() + '\n'
if raw.count(self.quotes) == 1:
raw += self.docs['out']['spaces'] + self.quotes
self.docs['out']['raw'] = raw.rstrip()
|
python
|
def _set_raw(self):
"""Sets the output raw docstring"""
sep = self.dst.get_sep(target='out')
sep = sep + ' ' if sep != ' ' else sep
with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + l if i > 0 else l for i, l in enumerate(s.splitlines())])
# sets the description section
raw = self.docs['out']['spaces'] + self.quotes
desc = self.docs['out']['desc'].strip()
if not desc or not desc.count('\n'):
if not self.docs['out']['params'] and not self.docs['out']['return'] and not self.docs['out']['rtype'] and not self.docs['out']['raises']:
raw += desc if desc else self.trailing_space
raw += self.quotes
self.docs['out']['raw'] = raw.rstrip()
return
if not self.first_line:
raw += '\n' + self.docs['out']['spaces']
raw += with_space(self.docs['out']['desc']).strip() + '\n'
# sets the parameters section
raw += self._set_raw_params(sep)
# sets the return section
raw += self._set_raw_return(sep)
# sets the raises section
raw += self._set_raw_raise(sep)
# sets post specific if any
if 'post' in self.docs['out']:
raw += self.docs['out']['spaces'] + with_space(self.docs['out']['post']).strip() + '\n'
# sets the doctests if any
if 'doctests' in self.docs['out']:
raw += self.docs['out']['spaces'] + with_space(self.docs['out']['doctests']).strip() + '\n'
if raw.count(self.quotes) == 1:
raw += self.docs['out']['spaces'] + self.quotes
self.docs['out']['raw'] = raw.rstrip()
|
[
"def",
"_set_raw",
"(",
"self",
")",
":",
"sep",
"=",
"self",
".",
"dst",
".",
"get_sep",
"(",
"target",
"=",
"'out'",
")",
"sep",
"=",
"sep",
"+",
"' '",
"if",
"sep",
"!=",
"' '",
"else",
"sep",
"with_space",
"=",
"lambda",
"s",
":",
"'\\n'",
".",
"join",
"(",
"[",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
"+",
"l",
"if",
"i",
">",
"0",
"else",
"l",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"s",
".",
"splitlines",
"(",
")",
")",
"]",
")",
"# sets the description section",
"raw",
"=",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
"+",
"self",
".",
"quotes",
"desc",
"=",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'desc'",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"desc",
"or",
"not",
"desc",
".",
"count",
"(",
"'\\n'",
")",
":",
"if",
"not",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'params'",
"]",
"and",
"not",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'return'",
"]",
"and",
"not",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'rtype'",
"]",
"and",
"not",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'raises'",
"]",
":",
"raw",
"+=",
"desc",
"if",
"desc",
"else",
"self",
".",
"trailing_space",
"raw",
"+=",
"self",
".",
"quotes",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'raw'",
"]",
"=",
"raw",
".",
"rstrip",
"(",
")",
"return",
"if",
"not",
"self",
".",
"first_line",
":",
"raw",
"+=",
"'\\n'",
"+",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
"raw",
"+=",
"with_space",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'desc'",
"]",
")",
".",
"strip",
"(",
")",
"+",
"'\\n'",
"# sets the parameters section",
"raw",
"+=",
"self",
".",
"_set_raw_params",
"(",
"sep",
")",
"# sets the return section",
"raw",
"+=",
"self",
".",
"_set_raw_return",
"(",
"sep",
")",
"# sets the raises section",
"raw",
"+=",
"self",
".",
"_set_raw_raise",
"(",
"sep",
")",
"# sets post specific if any",
"if",
"'post'",
"in",
"self",
".",
"docs",
"[",
"'out'",
"]",
":",
"raw",
"+=",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
"+",
"with_space",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'post'",
"]",
")",
".",
"strip",
"(",
")",
"+",
"'\\n'",
"# sets the doctests if any",
"if",
"'doctests'",
"in",
"self",
".",
"docs",
"[",
"'out'",
"]",
":",
"raw",
"+=",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
"+",
"with_space",
"(",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'doctests'",
"]",
")",
".",
"strip",
"(",
")",
"+",
"'\\n'",
"if",
"raw",
".",
"count",
"(",
"self",
".",
"quotes",
")",
"==",
"1",
":",
"raw",
"+=",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'spaces'",
"]",
"+",
"self",
".",
"quotes",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'raw'",
"]",
"=",
"raw",
".",
"rstrip",
"(",
")"
] |
Sets the output raw docstring
|
[
"Sets",
"the",
"output",
"raw",
"docstring"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1912-L1950
|
10,424
|
dadadel/pyment
|
pyment/docstring.py
|
DocString.generate_docs
|
def generate_docs(self):
"""Generates the output docstring"""
if self.dst.style['out'] == 'numpydoc' and self.dst.numpydoc.first_line is not None:
self.first_line = self.dst.numpydoc.first_line
self._set_desc()
self._set_params()
self._set_return()
self._set_raises()
self._set_other()
self._set_raw()
self.generated_docs = True
|
python
|
def generate_docs(self):
"""Generates the output docstring"""
if self.dst.style['out'] == 'numpydoc' and self.dst.numpydoc.first_line is not None:
self.first_line = self.dst.numpydoc.first_line
self._set_desc()
self._set_params()
self._set_return()
self._set_raises()
self._set_other()
self._set_raw()
self.generated_docs = True
|
[
"def",
"generate_docs",
"(",
"self",
")",
":",
"if",
"self",
".",
"dst",
".",
"style",
"[",
"'out'",
"]",
"==",
"'numpydoc'",
"and",
"self",
".",
"dst",
".",
"numpydoc",
".",
"first_line",
"is",
"not",
"None",
":",
"self",
".",
"first_line",
"=",
"self",
".",
"dst",
".",
"numpydoc",
".",
"first_line",
"self",
".",
"_set_desc",
"(",
")",
"self",
".",
"_set_params",
"(",
")",
"self",
".",
"_set_return",
"(",
")",
"self",
".",
"_set_raises",
"(",
")",
"self",
".",
"_set_other",
"(",
")",
"self",
".",
"_set_raw",
"(",
")",
"self",
".",
"generated_docs",
"=",
"True"
] |
Generates the output docstring
|
[
"Generates",
"the",
"output",
"docstring"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1952-L1962
|
10,425
|
dadadel/pyment
|
pyment/pymentapp.py
|
get_files_from_dir
|
def get_files_from_dir(path, recursive=True, depth=0, file_ext='.py'):
"""Retrieve the list of files from a folder.
@param path: file or directory where to search files
@param recursive: if True will search also sub-directories
@param depth: if explore recursively, the depth of sub directories to follow
@param file_ext: the files extension to get. Default is '.py'
@return: the file list retrieved. if the input is a file then a one element list.
"""
file_list = []
if os.path.isfile(path) or path == '-':
return [path]
if path[-1] != os.sep:
path = path + os.sep
for f in glob.glob(path + "*"):
if os.path.isdir(f):
if depth < MAX_DEPTH_RECUR: # avoid infinite recursive loop
file_list.extend(get_files_from_dir(f, recursive, depth + 1))
else:
continue
elif f.endswith(file_ext):
file_list.append(f)
return file_list
|
python
|
def get_files_from_dir(path, recursive=True, depth=0, file_ext='.py'):
"""Retrieve the list of files from a folder.
@param path: file or directory where to search files
@param recursive: if True will search also sub-directories
@param depth: if explore recursively, the depth of sub directories to follow
@param file_ext: the files extension to get. Default is '.py'
@return: the file list retrieved. if the input is a file then a one element list.
"""
file_list = []
if os.path.isfile(path) or path == '-':
return [path]
if path[-1] != os.sep:
path = path + os.sep
for f in glob.glob(path + "*"):
if os.path.isdir(f):
if depth < MAX_DEPTH_RECUR: # avoid infinite recursive loop
file_list.extend(get_files_from_dir(f, recursive, depth + 1))
else:
continue
elif f.endswith(file_ext):
file_list.append(f)
return file_list
|
[
"def",
"get_files_from_dir",
"(",
"path",
",",
"recursive",
"=",
"True",
",",
"depth",
"=",
"0",
",",
"file_ext",
"=",
"'.py'",
")",
":",
"file_list",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"or",
"path",
"==",
"'-'",
":",
"return",
"[",
"path",
"]",
"if",
"path",
"[",
"-",
"1",
"]",
"!=",
"os",
".",
"sep",
":",
"path",
"=",
"path",
"+",
"os",
".",
"sep",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"path",
"+",
"\"*\"",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"f",
")",
":",
"if",
"depth",
"<",
"MAX_DEPTH_RECUR",
":",
"# avoid infinite recursive loop",
"file_list",
".",
"extend",
"(",
"get_files_from_dir",
"(",
"f",
",",
"recursive",
",",
"depth",
"+",
"1",
")",
")",
"else",
":",
"continue",
"elif",
"f",
".",
"endswith",
"(",
"file_ext",
")",
":",
"file_list",
".",
"append",
"(",
"f",
")",
"return",
"file_list"
] |
Retrieve the list of files from a folder.
@param path: file or directory where to search files
@param recursive: if True will search also sub-directories
@param depth: if explore recursively, the depth of sub directories to follow
@param file_ext: the files extension to get. Default is '.py'
@return: the file list retrieved. if the input is a file then a one element list.
|
[
"Retrieve",
"the",
"list",
"of",
"files",
"from",
"a",
"folder",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pymentapp.py#L17-L40
|
10,426
|
dadadel/pyment
|
pyment/pymentapp.py
|
get_config
|
def get_config(config_file):
"""Get the configuration from a file.
@param config_file: the configuration file
@return: the configuration
@rtype: dict
"""
config = {}
tobool = lambda s: True if s.lower() == 'true' else False
if config_file:
try:
f = open(config_file, 'r')
except:
print ("Unable to open configuration file '{0}'".format(config_file))
else:
for line in f.readlines():
if len(line.strip()):
key, value = line.split("=", 1)
key, value = key.strip(), value.strip()
if key in ['init2class', 'first_line', 'convert_only']:
value = tobool(value)
config[key] = value
return config
|
python
|
def get_config(config_file):
"""Get the configuration from a file.
@param config_file: the configuration file
@return: the configuration
@rtype: dict
"""
config = {}
tobool = lambda s: True if s.lower() == 'true' else False
if config_file:
try:
f = open(config_file, 'r')
except:
print ("Unable to open configuration file '{0}'".format(config_file))
else:
for line in f.readlines():
if len(line.strip()):
key, value = line.split("=", 1)
key, value = key.strip(), value.strip()
if key in ['init2class', 'first_line', 'convert_only']:
value = tobool(value)
config[key] = value
return config
|
[
"def",
"get_config",
"(",
"config_file",
")",
":",
"config",
"=",
"{",
"}",
"tobool",
"=",
"lambda",
"s",
":",
"True",
"if",
"s",
".",
"lower",
"(",
")",
"==",
"'true'",
"else",
"False",
"if",
"config_file",
":",
"try",
":",
"f",
"=",
"open",
"(",
"config_file",
",",
"'r'",
")",
"except",
":",
"print",
"(",
"\"Unable to open configuration file '{0}'\"",
".",
"format",
"(",
"config_file",
")",
")",
"else",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"len",
"(",
"line",
".",
"strip",
"(",
")",
")",
":",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"key",
",",
"value",
"=",
"key",
".",
"strip",
"(",
")",
",",
"value",
".",
"strip",
"(",
")",
"if",
"key",
"in",
"[",
"'init2class'",
",",
"'first_line'",
",",
"'convert_only'",
"]",
":",
"value",
"=",
"tobool",
"(",
"value",
")",
"config",
"[",
"key",
"]",
"=",
"value",
"return",
"config"
] |
Get the configuration from a file.
@param config_file: the configuration file
@return: the configuration
@rtype: dict
|
[
"Get",
"the",
"configuration",
"from",
"a",
"file",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pymentapp.py#L43-L66
|
10,427
|
dadadel/pyment
|
pyment/pyment.py
|
PyComment.get_output_docs
|
def get_output_docs(self):
"""Return the output docstrings once formatted
:returns: the formatted docstrings
:rtype: list
"""
if not self.parsed:
self._parse()
lst = []
for e in self.docs_list:
lst.append(e['docs'].get_raw_docs())
return lst
|
python
|
def get_output_docs(self):
"""Return the output docstrings once formatted
:returns: the formatted docstrings
:rtype: list
"""
if not self.parsed:
self._parse()
lst = []
for e in self.docs_list:
lst.append(e['docs'].get_raw_docs())
return lst
|
[
"def",
"get_output_docs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parsed",
":",
"self",
".",
"_parse",
"(",
")",
"lst",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"docs_list",
":",
"lst",
".",
"append",
"(",
"e",
"[",
"'docs'",
"]",
".",
"get_raw_docs",
"(",
")",
")",
"return",
"lst"
] |
Return the output docstrings once formatted
:returns: the formatted docstrings
:rtype: list
|
[
"Return",
"the",
"output",
"docstrings",
"once",
"formatted"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L222-L234
|
10,428
|
dadadel/pyment
|
pyment/pyment.py
|
PyComment.compute_before_after
|
def compute_before_after(self):
"""Compute the list of lines before and after the proposed docstring changes.
:return: tuple of before,after where each is a list of lines of python code.
"""
if not self.parsed:
self._parse()
list_from = self.input_lines
list_to = []
last = 0
for e in self.docs_list:
start, end = e['location']
if start <= 0:
start, end = -start, -end
list_to.extend(list_from[last:start + 1])
else:
list_to.extend(list_from[last:start])
docs = e['docs'].get_raw_docs()
list_docs = [l + '\n' for l in docs.splitlines()]
list_to.extend(list_docs)
last = end + 1
if last < len(list_from):
list_to.extend(list_from[last:])
return list_from, list_to
|
python
|
def compute_before_after(self):
"""Compute the list of lines before and after the proposed docstring changes.
:return: tuple of before,after where each is a list of lines of python code.
"""
if not self.parsed:
self._parse()
list_from = self.input_lines
list_to = []
last = 0
for e in self.docs_list:
start, end = e['location']
if start <= 0:
start, end = -start, -end
list_to.extend(list_from[last:start + 1])
else:
list_to.extend(list_from[last:start])
docs = e['docs'].get_raw_docs()
list_docs = [l + '\n' for l in docs.splitlines()]
list_to.extend(list_docs)
last = end + 1
if last < len(list_from):
list_to.extend(list_from[last:])
return list_from, list_to
|
[
"def",
"compute_before_after",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parsed",
":",
"self",
".",
"_parse",
"(",
")",
"list_from",
"=",
"self",
".",
"input_lines",
"list_to",
"=",
"[",
"]",
"last",
"=",
"0",
"for",
"e",
"in",
"self",
".",
"docs_list",
":",
"start",
",",
"end",
"=",
"e",
"[",
"'location'",
"]",
"if",
"start",
"<=",
"0",
":",
"start",
",",
"end",
"=",
"-",
"start",
",",
"-",
"end",
"list_to",
".",
"extend",
"(",
"list_from",
"[",
"last",
":",
"start",
"+",
"1",
"]",
")",
"else",
":",
"list_to",
".",
"extend",
"(",
"list_from",
"[",
"last",
":",
"start",
"]",
")",
"docs",
"=",
"e",
"[",
"'docs'",
"]",
".",
"get_raw_docs",
"(",
")",
"list_docs",
"=",
"[",
"l",
"+",
"'\\n'",
"for",
"l",
"in",
"docs",
".",
"splitlines",
"(",
")",
"]",
"list_to",
".",
"extend",
"(",
"list_docs",
")",
"last",
"=",
"end",
"+",
"1",
"if",
"last",
"<",
"len",
"(",
"list_from",
")",
":",
"list_to",
".",
"extend",
"(",
"list_from",
"[",
"last",
":",
"]",
")",
"return",
"list_from",
",",
"list_to"
] |
Compute the list of lines before and after the proposed docstring changes.
:return: tuple of before,after where each is a list of lines of python code.
|
[
"Compute",
"the",
"list",
"of",
"lines",
"before",
"and",
"after",
"the",
"proposed",
"docstring",
"changes",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L236-L260
|
10,429
|
dadadel/pyment
|
pyment/pyment.py
|
PyComment.diff
|
def diff(self, source_path='', target_path='', which=-1):
"""Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_path: (Default value = '')
:param target_path: (Default value = '')
:returns: the resulted diff
:rtype: List[str]
"""
list_from, list_to = self.compute_before_after()
if source_path.startswith(os.sep):
source_path = source_path[1:]
if source_path and not source_path.endswith(os.sep):
source_path += os.sep
if target_path.startswith(os.sep):
target_path = target_path[1:]
if target_path and not target_path.endswith(os.sep):
target_path += os.sep
fromfile = 'a/' + source_path + os.path.basename(self.input_file)
tofile = 'b/' + target_path + os.path.basename(self.input_file)
diff_list = difflib.unified_diff(list_from, list_to, fromfile, tofile)
return [d for d in diff_list]
|
python
|
def diff(self, source_path='', target_path='', which=-1):
"""Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_path: (Default value = '')
:param target_path: (Default value = '')
:returns: the resulted diff
:rtype: List[str]
"""
list_from, list_to = self.compute_before_after()
if source_path.startswith(os.sep):
source_path = source_path[1:]
if source_path and not source_path.endswith(os.sep):
source_path += os.sep
if target_path.startswith(os.sep):
target_path = target_path[1:]
if target_path and not target_path.endswith(os.sep):
target_path += os.sep
fromfile = 'a/' + source_path + os.path.basename(self.input_file)
tofile = 'b/' + target_path + os.path.basename(self.input_file)
diff_list = difflib.unified_diff(list_from, list_to, fromfile, tofile)
return [d for d in diff_list]
|
[
"def",
"diff",
"(",
"self",
",",
"source_path",
"=",
"''",
",",
"target_path",
"=",
"''",
",",
"which",
"=",
"-",
"1",
")",
":",
"list_from",
",",
"list_to",
"=",
"self",
".",
"compute_before_after",
"(",
")",
"if",
"source_path",
".",
"startswith",
"(",
"os",
".",
"sep",
")",
":",
"source_path",
"=",
"source_path",
"[",
"1",
":",
"]",
"if",
"source_path",
"and",
"not",
"source_path",
".",
"endswith",
"(",
"os",
".",
"sep",
")",
":",
"source_path",
"+=",
"os",
".",
"sep",
"if",
"target_path",
".",
"startswith",
"(",
"os",
".",
"sep",
")",
":",
"target_path",
"=",
"target_path",
"[",
"1",
":",
"]",
"if",
"target_path",
"and",
"not",
"target_path",
".",
"endswith",
"(",
"os",
".",
"sep",
")",
":",
"target_path",
"+=",
"os",
".",
"sep",
"fromfile",
"=",
"'a/'",
"+",
"source_path",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"input_file",
")",
"tofile",
"=",
"'b/'",
"+",
"target_path",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"input_file",
")",
"diff_list",
"=",
"difflib",
".",
"unified_diff",
"(",
"list_from",
",",
"list_to",
",",
"fromfile",
",",
"tofile",
")",
"return",
"[",
"d",
"for",
"d",
"in",
"diff_list",
"]"
] |
Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_path: (Default value = '')
:param target_path: (Default value = '')
:returns: the resulted diff
:rtype: List[str]
|
[
"Build",
"the",
"diff",
"between",
"original",
"docstring",
"and",
"proposed",
"docstring",
"."
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L262-L287
|
10,430
|
dadadel/pyment
|
pyment/pyment.py
|
PyComment.get_patch_lines
|
def get_patch_lines(self, source_path, target_path):
"""Return the diff between source_path and target_path
:param source_path: name of the original file (Default value = '')
:param target_path: name of the final file (Default value = '')
:return: the diff as a list of \n terminated lines
:rtype: List[str]
"""
diff = self.diff(source_path, target_path)
return ["# Patch generated by Pyment v{0}\n\n".format(__version__)] + diff
|
python
|
def get_patch_lines(self, source_path, target_path):
"""Return the diff between source_path and target_path
:param source_path: name of the original file (Default value = '')
:param target_path: name of the final file (Default value = '')
:return: the diff as a list of \n terminated lines
:rtype: List[str]
"""
diff = self.diff(source_path, target_path)
return ["# Patch generated by Pyment v{0}\n\n".format(__version__)] + diff
|
[
"def",
"get_patch_lines",
"(",
"self",
",",
"source_path",
",",
"target_path",
")",
":",
"diff",
"=",
"self",
".",
"diff",
"(",
"source_path",
",",
"target_path",
")",
"return",
"[",
"\"# Patch generated by Pyment v{0}\\n\\n\"",
".",
"format",
"(",
"__version__",
")",
"]",
"+",
"diff"
] |
Return the diff between source_path and target_path
:param source_path: name of the original file (Default value = '')
:param target_path: name of the final file (Default value = '')
:return: the diff as a list of \n terminated lines
:rtype: List[str]
|
[
"Return",
"the",
"diff",
"between",
"source_path",
"and",
"target_path"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L289-L300
|
10,431
|
dadadel/pyment
|
pyment/pyment.py
|
PyComment.write_patch_file
|
def write_patch_file(self, patch_file, lines_to_write):
"""Write lines_to_write to a the file called patch_file
:param patch_file: file name of the patch to generate
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: list[str]
:return: None
"""
with open(patch_file, 'w') as f:
f.writelines(lines_to_write)
|
python
|
def write_patch_file(self, patch_file, lines_to_write):
"""Write lines_to_write to a the file called patch_file
:param patch_file: file name of the patch to generate
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: list[str]
:return: None
"""
with open(patch_file, 'w') as f:
f.writelines(lines_to_write)
|
[
"def",
"write_patch_file",
"(",
"self",
",",
"patch_file",
",",
"lines_to_write",
")",
":",
"with",
"open",
"(",
"patch_file",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"writelines",
"(",
"lines_to_write",
")"
] |
Write lines_to_write to a the file called patch_file
:param patch_file: file name of the patch to generate
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: list[str]
:return: None
|
[
"Write",
"lines_to_write",
"to",
"a",
"the",
"file",
"called",
"patch_file"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L302-L312
|
10,432
|
dadadel/pyment
|
pyment/pyment.py
|
PyComment.overwrite_source_file
|
def overwrite_source_file(self, lines_to_write):
"""overwrite the file with line_to_write
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: List[str]
:return: None
"""
tmp_filename = '{0}.writing'.format(self.input_file)
ok = False
try:
with open(tmp_filename, 'w') as fh:
fh.writelines(lines_to_write)
ok = True
finally:
if ok:
if platform.system() == 'Windows':
self._windows_rename(tmp_filename)
else:
os.rename(tmp_filename, self.input_file)
else:
os.unlink(tmp_filename)
|
python
|
def overwrite_source_file(self, lines_to_write):
"""overwrite the file with line_to_write
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: List[str]
:return: None
"""
tmp_filename = '{0}.writing'.format(self.input_file)
ok = False
try:
with open(tmp_filename, 'w') as fh:
fh.writelines(lines_to_write)
ok = True
finally:
if ok:
if platform.system() == 'Windows':
self._windows_rename(tmp_filename)
else:
os.rename(tmp_filename, self.input_file)
else:
os.unlink(tmp_filename)
|
[
"def",
"overwrite_source_file",
"(",
"self",
",",
"lines_to_write",
")",
":",
"tmp_filename",
"=",
"'{0}.writing'",
".",
"format",
"(",
"self",
".",
"input_file",
")",
"ok",
"=",
"False",
"try",
":",
"with",
"open",
"(",
"tmp_filename",
",",
"'w'",
")",
"as",
"fh",
":",
"fh",
".",
"writelines",
"(",
"lines_to_write",
")",
"ok",
"=",
"True",
"finally",
":",
"if",
"ok",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"self",
".",
"_windows_rename",
"(",
"tmp_filename",
")",
"else",
":",
"os",
".",
"rename",
"(",
"tmp_filename",
",",
"self",
".",
"input_file",
")",
"else",
":",
"os",
".",
"unlink",
"(",
"tmp_filename",
")"
] |
overwrite the file with line_to_write
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: List[str]
:return: None
|
[
"overwrite",
"the",
"file",
"with",
"line_to_write"
] |
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L314-L335
|
10,433
|
what-studio/profiling
|
profiling/sortkeys.py
|
by_own_time_per_call
|
def by_own_time_per_call(stat):
"""Sorting by exclusive elapsed time per call in descending order."""
return (-stat.own_time_per_call if stat.own_hits else -stat.own_time,
by_deep_time_per_call(stat))
|
python
|
def by_own_time_per_call(stat):
"""Sorting by exclusive elapsed time per call in descending order."""
return (-stat.own_time_per_call if stat.own_hits else -stat.own_time,
by_deep_time_per_call(stat))
|
[
"def",
"by_own_time_per_call",
"(",
"stat",
")",
":",
"return",
"(",
"-",
"stat",
".",
"own_time_per_call",
"if",
"stat",
".",
"own_hits",
"else",
"-",
"stat",
".",
"own_time",
",",
"by_deep_time_per_call",
"(",
"stat",
")",
")"
] |
Sorting by exclusive elapsed time per call in descending order.
|
[
"Sorting",
"by",
"exclusive",
"elapsed",
"time",
"per",
"call",
"in",
"descending",
"order",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/sortkeys.py#L61-L64
|
10,434
|
what-studio/profiling
|
profiling/profiler.py
|
Profiler.result
|
def result(self):
"""Gets the frozen statistics to serialize by Pickle."""
try:
cpu_time = max(0, time.clock() - self._cpu_time_started)
wall_time = max(0, time.time() - self._wall_time_started)
except AttributeError:
cpu_time = wall_time = 0.0
return self.stats, cpu_time, wall_time
|
python
|
def result(self):
"""Gets the frozen statistics to serialize by Pickle."""
try:
cpu_time = max(0, time.clock() - self._cpu_time_started)
wall_time = max(0, time.time() - self._wall_time_started)
except AttributeError:
cpu_time = wall_time = 0.0
return self.stats, cpu_time, wall_time
|
[
"def",
"result",
"(",
"self",
")",
":",
"try",
":",
"cpu_time",
"=",
"max",
"(",
"0",
",",
"time",
".",
"clock",
"(",
")",
"-",
"self",
".",
"_cpu_time_started",
")",
"wall_time",
"=",
"max",
"(",
"0",
",",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_wall_time_started",
")",
"except",
"AttributeError",
":",
"cpu_time",
"=",
"wall_time",
"=",
"0.0",
"return",
"self",
".",
"stats",
",",
"cpu_time",
",",
"wall_time"
] |
Gets the frozen statistics to serialize by Pickle.
|
[
"Gets",
"the",
"frozen",
"statistics",
"to",
"serialize",
"by",
"Pickle",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/profiler.py#L65-L72
|
10,435
|
what-studio/profiling
|
profiling/profiler.py
|
Profiler.dump
|
def dump(self, dump_filename, pickle_protocol=pickle.HIGHEST_PROTOCOL):
"""Saves the profiling result to a file
:param dump_filename: path to a file
:type dump_filename: str
:param pickle_protocol: version of pickle protocol
:type pickle_protocol: int
"""
result = self.result()
with open(dump_filename, 'wb') as f:
pickle.dump((self.__class__, result), f, pickle_protocol)
|
python
|
def dump(self, dump_filename, pickle_protocol=pickle.HIGHEST_PROTOCOL):
"""Saves the profiling result to a file
:param dump_filename: path to a file
:type dump_filename: str
:param pickle_protocol: version of pickle protocol
:type pickle_protocol: int
"""
result = self.result()
with open(dump_filename, 'wb') as f:
pickle.dump((self.__class__, result), f, pickle_protocol)
|
[
"def",
"dump",
"(",
"self",
",",
"dump_filename",
",",
"pickle_protocol",
"=",
"pickle",
".",
"HIGHEST_PROTOCOL",
")",
":",
"result",
"=",
"self",
".",
"result",
"(",
")",
"with",
"open",
"(",
"dump_filename",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"(",
"self",
".",
"__class__",
",",
"result",
")",
",",
"f",
",",
"pickle_protocol",
")"
] |
Saves the profiling result to a file
:param dump_filename: path to a file
:type dump_filename: str
:param pickle_protocol: version of pickle protocol
:type pickle_protocol: int
|
[
"Saves",
"the",
"profiling",
"result",
"to",
"a",
"file"
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/profiler.py#L74-L86
|
10,436
|
what-studio/profiling
|
profiling/profiler.py
|
Profiler.make_viewer
|
def make_viewer(self, title=None, at=None):
"""Makes a statistics viewer from the profiling result.
"""
viewer = StatisticsViewer()
viewer.set_profiler_class(self.__class__)
stats, cpu_time, wall_time = self.result()
viewer.set_result(stats, cpu_time, wall_time, title=title, at=at)
viewer.activate()
return viewer
|
python
|
def make_viewer(self, title=None, at=None):
"""Makes a statistics viewer from the profiling result.
"""
viewer = StatisticsViewer()
viewer.set_profiler_class(self.__class__)
stats, cpu_time, wall_time = self.result()
viewer.set_result(stats, cpu_time, wall_time, title=title, at=at)
viewer.activate()
return viewer
|
[
"def",
"make_viewer",
"(",
"self",
",",
"title",
"=",
"None",
",",
"at",
"=",
"None",
")",
":",
"viewer",
"=",
"StatisticsViewer",
"(",
")",
"viewer",
".",
"set_profiler_class",
"(",
"self",
".",
"__class__",
")",
"stats",
",",
"cpu_time",
",",
"wall_time",
"=",
"self",
".",
"result",
"(",
")",
"viewer",
".",
"set_result",
"(",
"stats",
",",
"cpu_time",
",",
"wall_time",
",",
"title",
"=",
"title",
",",
"at",
"=",
"at",
")",
"viewer",
".",
"activate",
"(",
")",
"return",
"viewer"
] |
Makes a statistics viewer from the profiling result.
|
[
"Makes",
"a",
"statistics",
"viewer",
"from",
"the",
"profiling",
"result",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/profiler.py#L88-L96
|
10,437
|
what-studio/profiling
|
profiling/remote/__init__.py
|
pack_msg
|
def pack_msg(method, msg, pickle_protocol=PICKLE_PROTOCOL):
"""Packs a method and message."""
dump = io.BytesIO()
pickle.dump(msg, dump, pickle_protocol)
size = dump.tell()
return (struct.pack(METHOD_STRUCT_FORMAT, method) +
struct.pack(SIZE_STRUCT_FORMAT, size) + dump.getvalue())
|
python
|
def pack_msg(method, msg, pickle_protocol=PICKLE_PROTOCOL):
"""Packs a method and message."""
dump = io.BytesIO()
pickle.dump(msg, dump, pickle_protocol)
size = dump.tell()
return (struct.pack(METHOD_STRUCT_FORMAT, method) +
struct.pack(SIZE_STRUCT_FORMAT, size) + dump.getvalue())
|
[
"def",
"pack_msg",
"(",
"method",
",",
"msg",
",",
"pickle_protocol",
"=",
"PICKLE_PROTOCOL",
")",
":",
"dump",
"=",
"io",
".",
"BytesIO",
"(",
")",
"pickle",
".",
"dump",
"(",
"msg",
",",
"dump",
",",
"pickle_protocol",
")",
"size",
"=",
"dump",
".",
"tell",
"(",
")",
"return",
"(",
"struct",
".",
"pack",
"(",
"METHOD_STRUCT_FORMAT",
",",
"method",
")",
"+",
"struct",
".",
"pack",
"(",
"SIZE_STRUCT_FORMAT",
",",
"size",
")",
"+",
"dump",
".",
"getvalue",
"(",
")",
")"
] |
Packs a method and message.
|
[
"Packs",
"a",
"method",
"and",
"message",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L60-L66
|
10,438
|
what-studio/profiling
|
profiling/remote/__init__.py
|
recv
|
def recv(sock, size):
"""Receives exactly `size` bytes. This function blocks the thread."""
data = sock.recv(size, socket.MSG_WAITALL)
if len(data) < size:
raise socket.error(ECONNRESET, 'Connection closed')
return data
|
python
|
def recv(sock, size):
"""Receives exactly `size` bytes. This function blocks the thread."""
data = sock.recv(size, socket.MSG_WAITALL)
if len(data) < size:
raise socket.error(ECONNRESET, 'Connection closed')
return data
|
[
"def",
"recv",
"(",
"sock",
",",
"size",
")",
":",
"data",
"=",
"sock",
".",
"recv",
"(",
"size",
",",
"socket",
".",
"MSG_WAITALL",
")",
"if",
"len",
"(",
"data",
")",
"<",
"size",
":",
"raise",
"socket",
".",
"error",
"(",
"ECONNRESET",
",",
"'Connection closed'",
")",
"return",
"data"
] |
Receives exactly `size` bytes. This function blocks the thread.
|
[
"Receives",
"exactly",
"size",
"bytes",
".",
"This",
"function",
"blocks",
"the",
"thread",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L69-L74
|
10,439
|
what-studio/profiling
|
profiling/remote/__init__.py
|
recv_msg
|
def recv_msg(sock):
"""Receives a method and message from the socket. This function blocks the
current thread.
"""
data = recv(sock, struct.calcsize(METHOD_STRUCT_FORMAT))
method, = struct.unpack(METHOD_STRUCT_FORMAT, data)
data = recv(sock, struct.calcsize(SIZE_STRUCT_FORMAT))
size, = struct.unpack(SIZE_STRUCT_FORMAT, data)
data = recv(sock, size)
msg = pickle.loads(data)
return method, msg
|
python
|
def recv_msg(sock):
"""Receives a method and message from the socket. This function blocks the
current thread.
"""
data = recv(sock, struct.calcsize(METHOD_STRUCT_FORMAT))
method, = struct.unpack(METHOD_STRUCT_FORMAT, data)
data = recv(sock, struct.calcsize(SIZE_STRUCT_FORMAT))
size, = struct.unpack(SIZE_STRUCT_FORMAT, data)
data = recv(sock, size)
msg = pickle.loads(data)
return method, msg
|
[
"def",
"recv_msg",
"(",
"sock",
")",
":",
"data",
"=",
"recv",
"(",
"sock",
",",
"struct",
".",
"calcsize",
"(",
"METHOD_STRUCT_FORMAT",
")",
")",
"method",
",",
"=",
"struct",
".",
"unpack",
"(",
"METHOD_STRUCT_FORMAT",
",",
"data",
")",
"data",
"=",
"recv",
"(",
"sock",
",",
"struct",
".",
"calcsize",
"(",
"SIZE_STRUCT_FORMAT",
")",
")",
"size",
",",
"=",
"struct",
".",
"unpack",
"(",
"SIZE_STRUCT_FORMAT",
",",
"data",
")",
"data",
"=",
"recv",
"(",
"sock",
",",
"size",
")",
"msg",
"=",
"pickle",
".",
"loads",
"(",
"data",
")",
"return",
"method",
",",
"msg"
] |
Receives a method and message from the socket. This function blocks the
current thread.
|
[
"Receives",
"a",
"method",
"and",
"message",
"from",
"the",
"socket",
".",
"This",
"function",
"blocks",
"the",
"current",
"thread",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L77-L87
|
10,440
|
what-studio/profiling
|
profiling/remote/__init__.py
|
ProfilingServer.connected
|
def connected(self, client):
"""Call this method when a client connected."""
self.clients.add(client)
self._log_connected(client)
self._start_watching(client)
self.send_msg(client, WELCOME, (self.pickle_protocol, __version__),
pickle_protocol=0)
profiler = self.profiler
while True:
try:
profiler = profiler.profiler
except AttributeError:
break
self.send_msg(client, PROFILER, type(profiler))
if self._latest_result_data is not None:
try:
self._send(client, self._latest_result_data)
except socket.error as exc:
if exc.errno in (EBADF, EPIPE):
self.disconnected(client)
return
raise
if len(self.clients) == 1:
self._start_profiling()
|
python
|
def connected(self, client):
"""Call this method when a client connected."""
self.clients.add(client)
self._log_connected(client)
self._start_watching(client)
self.send_msg(client, WELCOME, (self.pickle_protocol, __version__),
pickle_protocol=0)
profiler = self.profiler
while True:
try:
profiler = profiler.profiler
except AttributeError:
break
self.send_msg(client, PROFILER, type(profiler))
if self._latest_result_data is not None:
try:
self._send(client, self._latest_result_data)
except socket.error as exc:
if exc.errno in (EBADF, EPIPE):
self.disconnected(client)
return
raise
if len(self.clients) == 1:
self._start_profiling()
|
[
"def",
"connected",
"(",
"self",
",",
"client",
")",
":",
"self",
".",
"clients",
".",
"add",
"(",
"client",
")",
"self",
".",
"_log_connected",
"(",
"client",
")",
"self",
".",
"_start_watching",
"(",
"client",
")",
"self",
".",
"send_msg",
"(",
"client",
",",
"WELCOME",
",",
"(",
"self",
".",
"pickle_protocol",
",",
"__version__",
")",
",",
"pickle_protocol",
"=",
"0",
")",
"profiler",
"=",
"self",
".",
"profiler",
"while",
"True",
":",
"try",
":",
"profiler",
"=",
"profiler",
".",
"profiler",
"except",
"AttributeError",
":",
"break",
"self",
".",
"send_msg",
"(",
"client",
",",
"PROFILER",
",",
"type",
"(",
"profiler",
")",
")",
"if",
"self",
".",
"_latest_result_data",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"_send",
"(",
"client",
",",
"self",
".",
"_latest_result_data",
")",
"except",
"socket",
".",
"error",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"in",
"(",
"EBADF",
",",
"EPIPE",
")",
":",
"self",
".",
"disconnected",
"(",
"client",
")",
"return",
"raise",
"if",
"len",
"(",
"self",
".",
"clients",
")",
"==",
"1",
":",
"self",
".",
"_start_profiling",
"(",
")"
] |
Call this method when a client connected.
|
[
"Call",
"this",
"method",
"when",
"a",
"client",
"connected",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L205-L228
|
10,441
|
what-studio/profiling
|
profiling/remote/__init__.py
|
ProfilingServer.disconnected
|
def disconnected(self, client):
"""Call this method when a client disconnected."""
if client not in self.clients:
# already disconnected.
return
self.clients.remove(client)
self._log_disconnected(client)
self._close(client)
|
python
|
def disconnected(self, client):
"""Call this method when a client disconnected."""
if client not in self.clients:
# already disconnected.
return
self.clients.remove(client)
self._log_disconnected(client)
self._close(client)
|
[
"def",
"disconnected",
"(",
"self",
",",
"client",
")",
":",
"if",
"client",
"not",
"in",
"self",
".",
"clients",
":",
"# already disconnected.",
"return",
"self",
".",
"clients",
".",
"remove",
"(",
"client",
")",
"self",
".",
"_log_disconnected",
"(",
"client",
")",
"self",
".",
"_close",
"(",
"client",
")"
] |
Call this method when a client disconnected.
|
[
"Call",
"this",
"method",
"when",
"a",
"client",
"disconnected",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L230-L237
|
10,442
|
what-studio/profiling
|
profiling/viewer.py
|
StatisticsWidget.get_mark
|
def get_mark(self):
"""Gets an expanded, collapsed, or leaf icon."""
if self.is_leaf:
char = self.icon_chars[2]
else:
char = self.icon_chars[int(self.expanded)]
return urwid.SelectableIcon(('mark', char), 0)
|
python
|
def get_mark(self):
"""Gets an expanded, collapsed, or leaf icon."""
if self.is_leaf:
char = self.icon_chars[2]
else:
char = self.icon_chars[int(self.expanded)]
return urwid.SelectableIcon(('mark', char), 0)
|
[
"def",
"get_mark",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_leaf",
":",
"char",
"=",
"self",
".",
"icon_chars",
"[",
"2",
"]",
"else",
":",
"char",
"=",
"self",
".",
"icon_chars",
"[",
"int",
"(",
"self",
".",
"expanded",
")",
"]",
"return",
"urwid",
".",
"SelectableIcon",
"(",
"(",
"'mark'",
",",
"char",
")",
",",
"0",
")"
] |
Gets an expanded, collapsed, or leaf icon.
|
[
"Gets",
"an",
"expanded",
"collapsed",
"or",
"leaf",
"icon",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/viewer.py#L271-L277
|
10,443
|
what-studio/profiling
|
profiling/viewer.py
|
StatisticsTable.get_path
|
def get_path(self):
"""Gets the path to the focused statistics. Each step is a hash of
statistics object.
"""
path = deque()
__, node = self.get_focus()
while not node.is_root():
stats = node.get_value()
path.appendleft(hash(stats))
node = node.get_parent()
return path
|
python
|
def get_path(self):
"""Gets the path to the focused statistics. Each step is a hash of
statistics object.
"""
path = deque()
__, node = self.get_focus()
while not node.is_root():
stats = node.get_value()
path.appendleft(hash(stats))
node = node.get_parent()
return path
|
[
"def",
"get_path",
"(",
"self",
")",
":",
"path",
"=",
"deque",
"(",
")",
"__",
",",
"node",
"=",
"self",
".",
"get_focus",
"(",
")",
"while",
"not",
"node",
".",
"is_root",
"(",
")",
":",
"stats",
"=",
"node",
".",
"get_value",
"(",
")",
"path",
".",
"appendleft",
"(",
"hash",
"(",
"stats",
")",
")",
"node",
"=",
"node",
".",
"get_parent",
"(",
")",
"return",
"path"
] |
Gets the path to the focused statistics. Each step is a hash of
statistics object.
|
[
"Gets",
"the",
"path",
"to",
"the",
"focused",
"statistics",
".",
"Each",
"step",
"is",
"a",
"hash",
"of",
"statistics",
"object",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/viewer.py#L551-L561
|
10,444
|
what-studio/profiling
|
profiling/viewer.py
|
StatisticsTable.find_node
|
def find_node(self, node, path):
"""Finds a node by the given path from the given node."""
for hash_value in path:
if isinstance(node, LeafStatisticsNode):
break
for stats in node.get_child_keys():
if hash(stats) == hash_value:
node = node.get_child_node(stats)
break
else:
break
return node
|
python
|
def find_node(self, node, path):
"""Finds a node by the given path from the given node."""
for hash_value in path:
if isinstance(node, LeafStatisticsNode):
break
for stats in node.get_child_keys():
if hash(stats) == hash_value:
node = node.get_child_node(stats)
break
else:
break
return node
|
[
"def",
"find_node",
"(",
"self",
",",
"node",
",",
"path",
")",
":",
"for",
"hash_value",
"in",
"path",
":",
"if",
"isinstance",
"(",
"node",
",",
"LeafStatisticsNode",
")",
":",
"break",
"for",
"stats",
"in",
"node",
".",
"get_child_keys",
"(",
")",
":",
"if",
"hash",
"(",
"stats",
")",
"==",
"hash_value",
":",
"node",
"=",
"node",
".",
"get_child_node",
"(",
"stats",
")",
"break",
"else",
":",
"break",
"return",
"node"
] |
Finds a node by the given path from the given node.
|
[
"Finds",
"a",
"node",
"by",
"the",
"given",
"path",
"from",
"the",
"given",
"node",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/viewer.py#L563-L574
|
10,445
|
what-studio/profiling
|
profiling/viewer.py
|
StatisticsViewer.update_result
|
def update_result(self):
"""Updates the result on the table."""
try:
if self.paused:
result = self._paused_result
else:
result = self._final_result
except AttributeError:
self.table.update_frame()
return
stats, cpu_time, wall_time, title, at = result
self.table.set_result(stats, cpu_time, wall_time, title, at)
|
python
|
def update_result(self):
"""Updates the result on the table."""
try:
if self.paused:
result = self._paused_result
else:
result = self._final_result
except AttributeError:
self.table.update_frame()
return
stats, cpu_time, wall_time, title, at = result
self.table.set_result(stats, cpu_time, wall_time, title, at)
|
[
"def",
"update_result",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"paused",
":",
"result",
"=",
"self",
".",
"_paused_result",
"else",
":",
"result",
"=",
"self",
".",
"_final_result",
"except",
"AttributeError",
":",
"self",
".",
"table",
".",
"update_frame",
"(",
")",
"return",
"stats",
",",
"cpu_time",
",",
"wall_time",
",",
"title",
",",
"at",
"=",
"result",
"self",
".",
"table",
".",
"set_result",
"(",
"stats",
",",
"cpu_time",
",",
"wall_time",
",",
"title",
",",
"at",
")"
] |
Updates the result on the table.
|
[
"Updates",
"the",
"result",
"on",
"the",
"table",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/viewer.py#L812-L823
|
10,446
|
what-studio/profiling
|
profiling/__main__.py
|
option_getter
|
def option_getter(type):
"""Gets an unbound method to get a configuration option as the given type.
"""
option_getters = {None: ConfigParser.get,
int: ConfigParser.getint,
float: ConfigParser.getfloat,
bool: ConfigParser.getboolean}
return option_getters.get(type, option_getters[None])
|
python
|
def option_getter(type):
"""Gets an unbound method to get a configuration option as the given type.
"""
option_getters = {None: ConfigParser.get,
int: ConfigParser.getint,
float: ConfigParser.getfloat,
bool: ConfigParser.getboolean}
return option_getters.get(type, option_getters[None])
|
[
"def",
"option_getter",
"(",
"type",
")",
":",
"option_getters",
"=",
"{",
"None",
":",
"ConfigParser",
".",
"get",
",",
"int",
":",
"ConfigParser",
".",
"getint",
",",
"float",
":",
"ConfigParser",
".",
"getfloat",
",",
"bool",
":",
"ConfigParser",
".",
"getboolean",
"}",
"return",
"option_getters",
".",
"get",
"(",
"type",
",",
"option_getters",
"[",
"None",
"]",
")"
] |
Gets an unbound method to get a configuration option as the given type.
|
[
"Gets",
"an",
"unbound",
"method",
"to",
"get",
"a",
"configuration",
"option",
"as",
"the",
"given",
"type",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L116-L123
|
10,447
|
what-studio/profiling
|
profiling/__main__.py
|
config_default
|
def config_default(option, default=None, type=None, section=cli.name):
"""Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale'))
"""
def f(option=option, default=default, type=type, section=section):
config = read_config()
if type is None and default is not None:
# detect type from default.
type = builtins.type(default)
get_option = option_getter(type)
try:
return get_option(config, section, option)
except (NoOptionError, NoSectionError):
return default
return f
|
python
|
def config_default(option, default=None, type=None, section=cli.name):
"""Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale'))
"""
def f(option=option, default=default, type=type, section=section):
config = read_config()
if type is None and default is not None:
# detect type from default.
type = builtins.type(default)
get_option = option_getter(type)
try:
return get_option(config, section, option)
except (NoOptionError, NoSectionError):
return default
return f
|
[
"def",
"config_default",
"(",
"option",
",",
"default",
"=",
"None",
",",
"type",
"=",
"None",
",",
"section",
"=",
"cli",
".",
"name",
")",
":",
"def",
"f",
"(",
"option",
"=",
"option",
",",
"default",
"=",
"default",
",",
"type",
"=",
"type",
",",
"section",
"=",
"section",
")",
":",
"config",
"=",
"read_config",
"(",
")",
"if",
"type",
"is",
"None",
"and",
"default",
"is",
"not",
"None",
":",
"# detect type from default.",
"type",
"=",
"builtins",
".",
"type",
"(",
"default",
")",
"get_option",
"=",
"option_getter",
"(",
"type",
")",
"try",
":",
"return",
"get_option",
"(",
"config",
",",
"section",
",",
"option",
")",
"except",
"(",
"NoOptionError",
",",
"NoSectionError",
")",
":",
"return",
"default",
"return",
"f"
] |
Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale'))
|
[
"Guesses",
"a",
"default",
"value",
"of",
"a",
"CLI",
"option",
"from",
"the",
"configuration",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L126-L144
|
10,448
|
what-studio/profiling
|
profiling/__main__.py
|
config_flag
|
def config_flag(option, value, default=False, section=cli.name):
"""Guesses whether a CLI flag should be turned on or off from the
configuration. If the configuration option value is same with the given
value, it returns ``True``.
::
@click.option('--ko-kr', 'locale', is_flag=True,
default=config_flag('locale', 'ko_KR'))
"""
class x(object):
def __bool__(self, option=option, value=value,
default=default, section=section):
config = read_config()
type = builtins.type(value)
get_option = option_getter(type)
try:
return get_option(config, section, option) == value
except (NoOptionError, NoSectionError):
return default
__nonzero__ = __bool__
return x()
|
python
|
def config_flag(option, value, default=False, section=cli.name):
"""Guesses whether a CLI flag should be turned on or off from the
configuration. If the configuration option value is same with the given
value, it returns ``True``.
::
@click.option('--ko-kr', 'locale', is_flag=True,
default=config_flag('locale', 'ko_KR'))
"""
class x(object):
def __bool__(self, option=option, value=value,
default=default, section=section):
config = read_config()
type = builtins.type(value)
get_option = option_getter(type)
try:
return get_option(config, section, option) == value
except (NoOptionError, NoSectionError):
return default
__nonzero__ = __bool__
return x()
|
[
"def",
"config_flag",
"(",
"option",
",",
"value",
",",
"default",
"=",
"False",
",",
"section",
"=",
"cli",
".",
"name",
")",
":",
"class",
"x",
"(",
"object",
")",
":",
"def",
"__bool__",
"(",
"self",
",",
"option",
"=",
"option",
",",
"value",
"=",
"value",
",",
"default",
"=",
"default",
",",
"section",
"=",
"section",
")",
":",
"config",
"=",
"read_config",
"(",
")",
"type",
"=",
"builtins",
".",
"type",
"(",
"value",
")",
"get_option",
"=",
"option_getter",
"(",
"type",
")",
"try",
":",
"return",
"get_option",
"(",
"config",
",",
"section",
",",
"option",
")",
"==",
"value",
"except",
"(",
"NoOptionError",
",",
"NoSectionError",
")",
":",
"return",
"default",
"__nonzero__",
"=",
"__bool__",
"return",
"x",
"(",
")"
] |
Guesses whether a CLI flag should be turned on or off from the
configuration. If the configuration option value is same with the given
value, it returns ``True``.
::
@click.option('--ko-kr', 'locale', is_flag=True,
default=config_flag('locale', 'ko_KR'))
|
[
"Guesses",
"whether",
"a",
"CLI",
"flag",
"should",
"be",
"turned",
"on",
"or",
"off",
"from",
"the",
"configuration",
".",
"If",
"the",
"configuration",
"option",
"value",
"is",
"same",
"with",
"the",
"given",
"value",
"it",
"returns",
"True",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L147-L169
|
10,449
|
what-studio/profiling
|
profiling/__main__.py
|
get_title
|
def get_title(src_name, src_type=None):
"""Normalizes a source name as a string to be used for viewer's title."""
if src_type == 'tcp':
return '{0}:{1}'.format(*src_name)
return os.path.basename(src_name)
|
python
|
def get_title(src_name, src_type=None):
"""Normalizes a source name as a string to be used for viewer's title."""
if src_type == 'tcp':
return '{0}:{1}'.format(*src_name)
return os.path.basename(src_name)
|
[
"def",
"get_title",
"(",
"src_name",
",",
"src_type",
"=",
"None",
")",
":",
"if",
"src_type",
"==",
"'tcp'",
":",
"return",
"'{0}:{1}'",
".",
"format",
"(",
"*",
"src_name",
")",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"src_name",
")"
] |
Normalizes a source name as a string to be used for viewer's title.
|
[
"Normalizes",
"a",
"source",
"name",
"as",
"a",
"string",
"to",
"be",
"used",
"for",
"viewer",
"s",
"title",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L172-L176
|
10,450
|
what-studio/profiling
|
profiling/__main__.py
|
spawn_thread
|
def spawn_thread(func, *args, **kwargs):
"""Spawns a daemon thread."""
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread
|
python
|
def spawn_thread(func, *args, **kwargs):
"""Spawns a daemon thread."""
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread
|
[
"def",
"spawn_thread",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
")",
"return",
"thread"
] |
Spawns a daemon thread.
|
[
"Spawns",
"a",
"daemon",
"thread",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L189-L194
|
10,451
|
what-studio/profiling
|
profiling/__main__.py
|
spawn
|
def spawn(mode, func, *args, **kwargs):
"""Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
"""
if mode is None:
# 'threading' is the default mode.
mode = 'threading'
elif mode not in spawn.modes:
# validate the given mode.
raise ValueError('Invalid spawn mode: %s' % mode)
if mode == 'threading':
return spawn_thread(func, *args, **kwargs)
elif mode == 'gevent':
import gevent
import gevent.monkey
gevent.monkey.patch_select()
gevent.monkey.patch_socket()
return gevent.spawn(func, *args, **kwargs)
elif mode == 'eventlet':
import eventlet
eventlet.patcher.monkey_patch(select=True, socket=True)
return eventlet.spawn(func, *args, **kwargs)
assert False
|
python
|
def spawn(mode, func, *args, **kwargs):
"""Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
"""
if mode is None:
# 'threading' is the default mode.
mode = 'threading'
elif mode not in spawn.modes:
# validate the given mode.
raise ValueError('Invalid spawn mode: %s' % mode)
if mode == 'threading':
return spawn_thread(func, *args, **kwargs)
elif mode == 'gevent':
import gevent
import gevent.monkey
gevent.monkey.patch_select()
gevent.monkey.patch_socket()
return gevent.spawn(func, *args, **kwargs)
elif mode == 'eventlet':
import eventlet
eventlet.patcher.monkey_patch(select=True, socket=True)
return eventlet.spawn(func, *args, **kwargs)
assert False
|
[
"def",
"spawn",
"(",
"mode",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"is",
"None",
":",
"# 'threading' is the default mode.",
"mode",
"=",
"'threading'",
"elif",
"mode",
"not",
"in",
"spawn",
".",
"modes",
":",
"# validate the given mode.",
"raise",
"ValueError",
"(",
"'Invalid spawn mode: %s'",
"%",
"mode",
")",
"if",
"mode",
"==",
"'threading'",
":",
"return",
"spawn_thread",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"elif",
"mode",
"==",
"'gevent'",
":",
"import",
"gevent",
"import",
"gevent",
".",
"monkey",
"gevent",
".",
"monkey",
".",
"patch_select",
"(",
")",
"gevent",
".",
"monkey",
".",
"patch_socket",
"(",
")",
"return",
"gevent",
".",
"spawn",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"elif",
"mode",
"==",
"'eventlet'",
":",
"import",
"eventlet",
"eventlet",
".",
"patcher",
".",
"monkey_patch",
"(",
"select",
"=",
"True",
",",
"socket",
"=",
"True",
")",
"return",
"eventlet",
".",
"spawn",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"assert",
"False"
] |
Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
|
[
"Spawns",
"a",
"thread",
"-",
"like",
"object",
"which",
"runs",
"the",
"given",
"function",
"concurrently",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L197-L225
|
10,452
|
what-studio/profiling
|
profiling/__main__.py
|
profile
|
def profile(script, argv, profiler_factory,
pickle_protocol, dump_filename, mono):
"""Profile a Python script."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
__profile__(filename, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono)
|
python
|
def profile(script, argv, profiler_factory,
pickle_protocol, dump_filename, mono):
"""Profile a Python script."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
__profile__(filename, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono)
|
[
"def",
"profile",
"(",
"script",
",",
"argv",
",",
"profiler_factory",
",",
"pickle_protocol",
",",
"dump_filename",
",",
"mono",
")",
":",
"filename",
",",
"code",
",",
"globals_",
"=",
"script",
"sys",
".",
"argv",
"[",
":",
"]",
"=",
"[",
"filename",
"]",
"+",
"list",
"(",
"argv",
")",
"__profile__",
"(",
"filename",
",",
"code",
",",
"globals_",
",",
"profiler_factory",
",",
"pickle_protocol",
"=",
"pickle_protocol",
",",
"dump_filename",
"=",
"dump_filename",
",",
"mono",
"=",
"mono",
")"
] |
Profile a Python script.
|
[
"Profile",
"a",
"Python",
"script",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L582-L589
|
10,453
|
what-studio/profiling
|
profiling/__main__.py
|
live_profile
|
def live_profile(script, argv, profiler_factory, interval, spawn, signum,
pickle_protocol, mono):
"""Profile a Python script continuously."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
parent_sock, child_sock = socket.socketpair()
stderr_r_fd, stderr_w_fd = os.pipe()
pid = os.fork()
if pid:
# parent
os.close(stderr_w_fd)
viewer, loop = make_viewer(mono)
# loop.screen._term_output_file = open(os.devnull, 'w')
title = get_title(filename)
client = ProfilingClient(viewer, loop.event_loop, parent_sock, title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
os.kill(pid, signal.SIGINT)
except BaseException:
# unexpected profiler error.
os.kill(pid, signal.SIGTERM)
raise
finally:
parent_sock.close()
# get exit code of child.
w_pid, status = os.waitpid(pid, os.WNOHANG)
if w_pid == 0:
os.kill(pid, signal.SIGTERM)
exit_code = os.WEXITSTATUS(status)
# print stderr of child.
with os.fdopen(stderr_r_fd, 'r') as f:
child_stderr = f.read()
if child_stderr:
sys.stdout.flush()
sys.stderr.write(child_stderr)
# exit with exit code of child.
sys.exit(exit_code)
else:
# child
os.close(stderr_r_fd)
# mute stdin, stdout.
devnull = os.open(os.devnull, os.O_RDWR)
for f in [sys.stdin, sys.stdout]:
os.dup2(devnull, f.fileno())
# redirect stderr to parent.
os.dup2(stderr_w_fd, sys.stderr.fileno())
frame = sys._getframe()
profiler = profiler_factory(base_frame=frame, base_code=code)
profiler_trigger = BackgroundProfiler(profiler, signum)
profiler_trigger.prepare()
server_args = (interval, noop, pickle_protocol)
server = SelectProfilingServer(None, profiler_trigger, *server_args)
server.clients.add(child_sock)
spawn(server.connected, child_sock)
try:
exec_(code, globals_)
finally:
os.close(stderr_w_fd)
child_sock.shutdown(socket.SHUT_WR)
|
python
|
def live_profile(script, argv, profiler_factory, interval, spawn, signum,
pickle_protocol, mono):
"""Profile a Python script continuously."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
parent_sock, child_sock = socket.socketpair()
stderr_r_fd, stderr_w_fd = os.pipe()
pid = os.fork()
if pid:
# parent
os.close(stderr_w_fd)
viewer, loop = make_viewer(mono)
# loop.screen._term_output_file = open(os.devnull, 'w')
title = get_title(filename)
client = ProfilingClient(viewer, loop.event_loop, parent_sock, title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
os.kill(pid, signal.SIGINT)
except BaseException:
# unexpected profiler error.
os.kill(pid, signal.SIGTERM)
raise
finally:
parent_sock.close()
# get exit code of child.
w_pid, status = os.waitpid(pid, os.WNOHANG)
if w_pid == 0:
os.kill(pid, signal.SIGTERM)
exit_code = os.WEXITSTATUS(status)
# print stderr of child.
with os.fdopen(stderr_r_fd, 'r') as f:
child_stderr = f.read()
if child_stderr:
sys.stdout.flush()
sys.stderr.write(child_stderr)
# exit with exit code of child.
sys.exit(exit_code)
else:
# child
os.close(stderr_r_fd)
# mute stdin, stdout.
devnull = os.open(os.devnull, os.O_RDWR)
for f in [sys.stdin, sys.stdout]:
os.dup2(devnull, f.fileno())
# redirect stderr to parent.
os.dup2(stderr_w_fd, sys.stderr.fileno())
frame = sys._getframe()
profiler = profiler_factory(base_frame=frame, base_code=code)
profiler_trigger = BackgroundProfiler(profiler, signum)
profiler_trigger.prepare()
server_args = (interval, noop, pickle_protocol)
server = SelectProfilingServer(None, profiler_trigger, *server_args)
server.clients.add(child_sock)
spawn(server.connected, child_sock)
try:
exec_(code, globals_)
finally:
os.close(stderr_w_fd)
child_sock.shutdown(socket.SHUT_WR)
|
[
"def",
"live_profile",
"(",
"script",
",",
"argv",
",",
"profiler_factory",
",",
"interval",
",",
"spawn",
",",
"signum",
",",
"pickle_protocol",
",",
"mono",
")",
":",
"filename",
",",
"code",
",",
"globals_",
"=",
"script",
"sys",
".",
"argv",
"[",
":",
"]",
"=",
"[",
"filename",
"]",
"+",
"list",
"(",
"argv",
")",
"parent_sock",
",",
"child_sock",
"=",
"socket",
".",
"socketpair",
"(",
")",
"stderr_r_fd",
",",
"stderr_w_fd",
"=",
"os",
".",
"pipe",
"(",
")",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
":",
"# parent",
"os",
".",
"close",
"(",
"stderr_w_fd",
")",
"viewer",
",",
"loop",
"=",
"make_viewer",
"(",
"mono",
")",
"# loop.screen._term_output_file = open(os.devnull, 'w')",
"title",
"=",
"get_title",
"(",
"filename",
")",
"client",
"=",
"ProfilingClient",
"(",
"viewer",
",",
"loop",
".",
"event_loop",
",",
"parent_sock",
",",
"title",
")",
"client",
".",
"start",
"(",
")",
"try",
":",
"loop",
".",
"run",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGINT",
")",
"except",
"BaseException",
":",
"# unexpected profiler error.",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"raise",
"finally",
":",
"parent_sock",
".",
"close",
"(",
")",
"# get exit code of child.",
"w_pid",
",",
"status",
"=",
"os",
".",
"waitpid",
"(",
"pid",
",",
"os",
".",
"WNOHANG",
")",
"if",
"w_pid",
"==",
"0",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"exit_code",
"=",
"os",
".",
"WEXITSTATUS",
"(",
"status",
")",
"# print stderr of child.",
"with",
"os",
".",
"fdopen",
"(",
"stderr_r_fd",
",",
"'r'",
")",
"as",
"f",
":",
"child_stderr",
"=",
"f",
".",
"read",
"(",
")",
"if",
"child_stderr",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"child_stderr",
")",
"# exit with exit code of child.",
"sys",
".",
"exit",
"(",
"exit_code",
")",
"else",
":",
"# child",
"os",
".",
"close",
"(",
"stderr_r_fd",
")",
"# mute stdin, stdout.",
"devnull",
"=",
"os",
".",
"open",
"(",
"os",
".",
"devnull",
",",
"os",
".",
"O_RDWR",
")",
"for",
"f",
"in",
"[",
"sys",
".",
"stdin",
",",
"sys",
".",
"stdout",
"]",
":",
"os",
".",
"dup2",
"(",
"devnull",
",",
"f",
".",
"fileno",
"(",
")",
")",
"# redirect stderr to parent.",
"os",
".",
"dup2",
"(",
"stderr_w_fd",
",",
"sys",
".",
"stderr",
".",
"fileno",
"(",
")",
")",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
")",
"profiler",
"=",
"profiler_factory",
"(",
"base_frame",
"=",
"frame",
",",
"base_code",
"=",
"code",
")",
"profiler_trigger",
"=",
"BackgroundProfiler",
"(",
"profiler",
",",
"signum",
")",
"profiler_trigger",
".",
"prepare",
"(",
")",
"server_args",
"=",
"(",
"interval",
",",
"noop",
",",
"pickle_protocol",
")",
"server",
"=",
"SelectProfilingServer",
"(",
"None",
",",
"profiler_trigger",
",",
"*",
"server_args",
")",
"server",
".",
"clients",
".",
"add",
"(",
"child_sock",
")",
"spawn",
"(",
"server",
".",
"connected",
",",
"child_sock",
")",
"try",
":",
"exec_",
"(",
"code",
",",
"globals_",
")",
"finally",
":",
"os",
".",
"close",
"(",
"stderr_w_fd",
")",
"child_sock",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_WR",
")"
] |
Profile a Python script continuously.
|
[
"Profile",
"a",
"Python",
"script",
"continuously",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L597-L657
|
10,454
|
what-studio/profiling
|
profiling/__main__.py
|
view
|
def view(src, mono):
"""Inspect statistics by TUI view."""
src_type, src_name = src
title = get_title(src_name, src_type)
viewer, loop = make_viewer(mono)
if src_type == 'dump':
time = datetime.fromtimestamp(os.path.getmtime(src_name))
with open(src_name, 'rb') as f:
profiler_class, (stats, cpu_time, wall_time) = pickle.load(f)
viewer.set_profiler_class(profiler_class)
viewer.set_result(stats, cpu_time, wall_time, title=title, at=time)
viewer.activate()
elif src_type in ('tcp', 'sock'):
family = {'tcp': socket.AF_INET, 'sock': socket.AF_UNIX}[src_type]
client = FailoverProfilingClient(viewer, loop.event_loop,
src_name, family, title=title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
pass
|
python
|
def view(src, mono):
"""Inspect statistics by TUI view."""
src_type, src_name = src
title = get_title(src_name, src_type)
viewer, loop = make_viewer(mono)
if src_type == 'dump':
time = datetime.fromtimestamp(os.path.getmtime(src_name))
with open(src_name, 'rb') as f:
profiler_class, (stats, cpu_time, wall_time) = pickle.load(f)
viewer.set_profiler_class(profiler_class)
viewer.set_result(stats, cpu_time, wall_time, title=title, at=time)
viewer.activate()
elif src_type in ('tcp', 'sock'):
family = {'tcp': socket.AF_INET, 'sock': socket.AF_UNIX}[src_type]
client = FailoverProfilingClient(viewer, loop.event_loop,
src_name, family, title=title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
pass
|
[
"def",
"view",
"(",
"src",
",",
"mono",
")",
":",
"src_type",
",",
"src_name",
"=",
"src",
"title",
"=",
"get_title",
"(",
"src_name",
",",
"src_type",
")",
"viewer",
",",
"loop",
"=",
"make_viewer",
"(",
"mono",
")",
"if",
"src_type",
"==",
"'dump'",
":",
"time",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"src_name",
")",
")",
"with",
"open",
"(",
"src_name",
",",
"'rb'",
")",
"as",
"f",
":",
"profiler_class",
",",
"(",
"stats",
",",
"cpu_time",
",",
"wall_time",
")",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"viewer",
".",
"set_profiler_class",
"(",
"profiler_class",
")",
"viewer",
".",
"set_result",
"(",
"stats",
",",
"cpu_time",
",",
"wall_time",
",",
"title",
"=",
"title",
",",
"at",
"=",
"time",
")",
"viewer",
".",
"activate",
"(",
")",
"elif",
"src_type",
"in",
"(",
"'tcp'",
",",
"'sock'",
")",
":",
"family",
"=",
"{",
"'tcp'",
":",
"socket",
".",
"AF_INET",
",",
"'sock'",
":",
"socket",
".",
"AF_UNIX",
"}",
"[",
"src_type",
"]",
"client",
"=",
"FailoverProfilingClient",
"(",
"viewer",
",",
"loop",
".",
"event_loop",
",",
"src_name",
",",
"family",
",",
"title",
"=",
"title",
")",
"client",
".",
"start",
"(",
")",
"try",
":",
"loop",
".",
"run",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
] |
Inspect statistics by TUI view.
|
[
"Inspect",
"statistics",
"by",
"TUI",
"view",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L707-L727
|
10,455
|
what-studio/profiling
|
profiling/__main__.py
|
timeit_profile
|
def timeit_profile(stmt, number, repeat, setup,
profiler_factory, pickle_protocol, dump_filename, mono,
**_ignored):
"""Profile a Python statement like timeit."""
del _ignored
globals_ = {}
exec_(setup, globals_)
if number is None:
# determine number so that 0.2 <= total time < 2.0 like timeit.
dummy_profiler = profiler_factory()
dummy_profiler.start()
for x in range(1, 10):
number = 10 ** x
t = time.time()
for y in range(number):
exec_(stmt, globals_)
if time.time() - t >= 0.2:
break
dummy_profiler.stop()
del dummy_profiler
code = compile('for _ in range(%d): %s' % (number, stmt),
'STATEMENT', 'exec')
__profile__(stmt, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono)
|
python
|
def timeit_profile(stmt, number, repeat, setup,
profiler_factory, pickle_protocol, dump_filename, mono,
**_ignored):
"""Profile a Python statement like timeit."""
del _ignored
globals_ = {}
exec_(setup, globals_)
if number is None:
# determine number so that 0.2 <= total time < 2.0 like timeit.
dummy_profiler = profiler_factory()
dummy_profiler.start()
for x in range(1, 10):
number = 10 ** x
t = time.time()
for y in range(number):
exec_(stmt, globals_)
if time.time() - t >= 0.2:
break
dummy_profiler.stop()
del dummy_profiler
code = compile('for _ in range(%d): %s' % (number, stmt),
'STATEMENT', 'exec')
__profile__(stmt, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono)
|
[
"def",
"timeit_profile",
"(",
"stmt",
",",
"number",
",",
"repeat",
",",
"setup",
",",
"profiler_factory",
",",
"pickle_protocol",
",",
"dump_filename",
",",
"mono",
",",
"*",
"*",
"_ignored",
")",
":",
"del",
"_ignored",
"globals_",
"=",
"{",
"}",
"exec_",
"(",
"setup",
",",
"globals_",
")",
"if",
"number",
"is",
"None",
":",
"# determine number so that 0.2 <= total time < 2.0 like timeit.",
"dummy_profiler",
"=",
"profiler_factory",
"(",
")",
"dummy_profiler",
".",
"start",
"(",
")",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"number",
"=",
"10",
"**",
"x",
"t",
"=",
"time",
".",
"time",
"(",
")",
"for",
"y",
"in",
"range",
"(",
"number",
")",
":",
"exec_",
"(",
"stmt",
",",
"globals_",
")",
"if",
"time",
".",
"time",
"(",
")",
"-",
"t",
">=",
"0.2",
":",
"break",
"dummy_profiler",
".",
"stop",
"(",
")",
"del",
"dummy_profiler",
"code",
"=",
"compile",
"(",
"'for _ in range(%d): %s'",
"%",
"(",
"number",
",",
"stmt",
")",
",",
"'STATEMENT'",
",",
"'exec'",
")",
"__profile__",
"(",
"stmt",
",",
"code",
",",
"globals_",
",",
"profiler_factory",
",",
"pickle_protocol",
"=",
"pickle_protocol",
",",
"dump_filename",
"=",
"dump_filename",
",",
"mono",
"=",
"mono",
")"
] |
Profile a Python statement like timeit.
|
[
"Profile",
"a",
"Python",
"statement",
"like",
"timeit",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L744-L768
|
10,456
|
what-studio/profiling
|
profiling/stats.py
|
spread_stats
|
def spread_stats(stats, spreader=False):
"""Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded statistics also.
"""
spread = spread_t() if spreader else True
descendants = deque(stats)
while descendants:
_stats = descendants.popleft()
if spreader:
spread.clear()
yield _stats, spread
else:
yield _stats
if spread:
descendants.extend(_stats)
|
python
|
def spread_stats(stats, spreader=False):
"""Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded statistics also.
"""
spread = spread_t() if spreader else True
descendants = deque(stats)
while descendants:
_stats = descendants.popleft()
if spreader:
spread.clear()
yield _stats, spread
else:
yield _stats
if spread:
descendants.extend(_stats)
|
[
"def",
"spread_stats",
"(",
"stats",
",",
"spreader",
"=",
"False",
")",
":",
"spread",
"=",
"spread_t",
"(",
")",
"if",
"spreader",
"else",
"True",
"descendants",
"=",
"deque",
"(",
"stats",
")",
"while",
"descendants",
":",
"_stats",
"=",
"descendants",
".",
"popleft",
"(",
")",
"if",
"spreader",
":",
"spread",
".",
"clear",
"(",
")",
"yield",
"_stats",
",",
"spread",
"else",
":",
"yield",
"_stats",
"if",
"spread",
":",
"descendants",
".",
"extend",
"(",
"_stats",
")"
] |
Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded statistics also.
|
[
"Iterates",
"all",
"descendant",
"statistics",
"under",
"the",
"given",
"root",
"statistics",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/stats.py#L38-L56
|
10,457
|
what-studio/profiling
|
profiling/stats.py
|
Statistics.own_time
|
def own_time(self):
"""The exclusive execution time."""
sub_time = sum(stats.deep_time for stats in self)
return max(0., self.deep_time - sub_time)
|
python
|
def own_time(self):
"""The exclusive execution time."""
sub_time = sum(stats.deep_time for stats in self)
return max(0., self.deep_time - sub_time)
|
[
"def",
"own_time",
"(",
"self",
")",
":",
"sub_time",
"=",
"sum",
"(",
"stats",
".",
"deep_time",
"for",
"stats",
"in",
"self",
")",
"return",
"max",
"(",
"0.",
",",
"self",
".",
"deep_time",
"-",
"sub_time",
")"
] |
The exclusive execution time.
|
[
"The",
"exclusive",
"execution",
"time",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/stats.py#L137-L140
|
10,458
|
what-studio/profiling
|
profiling/stats.py
|
FlatFrozenStatistics.flatten
|
def flatten(cls, stats):
"""Makes a flat statistics from the given statistics."""
flat_children = {}
for _stats in spread_stats(stats):
key = (_stats.name, _stats.filename, _stats.lineno, _stats.module)
try:
flat_stats = flat_children[key]
except KeyError:
flat_stats = flat_children[key] = cls(*key)
flat_stats.own_hits += _stats.own_hits
flat_stats.deep_hits += _stats.deep_hits
flat_stats.own_time += _stats.own_time
flat_stats.deep_time += _stats.deep_time
children = list(itervalues(flat_children))
return cls(stats.name, stats.filename, stats.lineno, stats.module,
stats.own_hits, stats.deep_hits, stats.own_time,
stats.deep_time, children)
|
python
|
def flatten(cls, stats):
"""Makes a flat statistics from the given statistics."""
flat_children = {}
for _stats in spread_stats(stats):
key = (_stats.name, _stats.filename, _stats.lineno, _stats.module)
try:
flat_stats = flat_children[key]
except KeyError:
flat_stats = flat_children[key] = cls(*key)
flat_stats.own_hits += _stats.own_hits
flat_stats.deep_hits += _stats.deep_hits
flat_stats.own_time += _stats.own_time
flat_stats.deep_time += _stats.deep_time
children = list(itervalues(flat_children))
return cls(stats.name, stats.filename, stats.lineno, stats.module,
stats.own_hits, stats.deep_hits, stats.own_time,
stats.deep_time, children)
|
[
"def",
"flatten",
"(",
"cls",
",",
"stats",
")",
":",
"flat_children",
"=",
"{",
"}",
"for",
"_stats",
"in",
"spread_stats",
"(",
"stats",
")",
":",
"key",
"=",
"(",
"_stats",
".",
"name",
",",
"_stats",
".",
"filename",
",",
"_stats",
".",
"lineno",
",",
"_stats",
".",
"module",
")",
"try",
":",
"flat_stats",
"=",
"flat_children",
"[",
"key",
"]",
"except",
"KeyError",
":",
"flat_stats",
"=",
"flat_children",
"[",
"key",
"]",
"=",
"cls",
"(",
"*",
"key",
")",
"flat_stats",
".",
"own_hits",
"+=",
"_stats",
".",
"own_hits",
"flat_stats",
".",
"deep_hits",
"+=",
"_stats",
".",
"deep_hits",
"flat_stats",
".",
"own_time",
"+=",
"_stats",
".",
"own_time",
"flat_stats",
".",
"deep_time",
"+=",
"_stats",
".",
"deep_time",
"children",
"=",
"list",
"(",
"itervalues",
"(",
"flat_children",
")",
")",
"return",
"cls",
"(",
"stats",
".",
"name",
",",
"stats",
".",
"filename",
",",
"stats",
".",
"lineno",
",",
"stats",
".",
"module",
",",
"stats",
".",
"own_hits",
",",
"stats",
".",
"deep_hits",
",",
"stats",
".",
"own_time",
",",
"stats",
".",
"deep_time",
",",
"children",
")"
] |
Makes a flat statistics from the given statistics.
|
[
"Makes",
"a",
"flat",
"statistics",
"from",
"the",
"given",
"statistics",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/stats.py#L357-L373
|
10,459
|
what-studio/profiling
|
setup.py
|
requirements
|
def requirements(filename):
"""Reads requirements from a file."""
with open(filename) as f:
return [x.strip() for x in f.readlines() if x.strip()]
|
python
|
def requirements(filename):
"""Reads requirements from a file."""
with open(filename) as f:
return [x.strip() for x in f.readlines() if x.strip()]
|
[
"def",
"requirements",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"return",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"f",
".",
"readlines",
"(",
")",
"if",
"x",
".",
"strip",
"(",
")",
"]"
] |
Reads requirements from a file.
|
[
"Reads",
"requirements",
"from",
"a",
"file",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/setup.py#L68-L71
|
10,460
|
what-studio/profiling
|
profiling/sampling/__init__.py
|
SamplingProfiler.sample
|
def sample(self, frame):
"""Samples the given frame."""
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void)
stats = parent_stats.ensure_child(frame.f_code, RecordingStatistics)
stats.own_hits += 1
|
python
|
def sample(self, frame):
"""Samples the given frame."""
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void)
stats = parent_stats.ensure_child(frame.f_code, RecordingStatistics)
stats.own_hits += 1
|
[
"def",
"sample",
"(",
"self",
",",
"frame",
")",
":",
"frames",
"=",
"self",
".",
"frame_stack",
"(",
"frame",
")",
"if",
"frames",
":",
"frames",
".",
"pop",
"(",
")",
"parent_stats",
"=",
"self",
".",
"stats",
"for",
"f",
"in",
"frames",
":",
"parent_stats",
"=",
"parent_stats",
".",
"ensure_child",
"(",
"f",
".",
"f_code",
",",
"void",
")",
"stats",
"=",
"parent_stats",
".",
"ensure_child",
"(",
"frame",
".",
"f_code",
",",
"RecordingStatistics",
")",
"stats",
".",
"own_hits",
"+=",
"1"
] |
Samples the given frame.
|
[
"Samples",
"the",
"given",
"frame",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/sampling/__init__.py#L65-L74
|
10,461
|
what-studio/profiling
|
profiling/utils.py
|
deferral
|
def deferral():
"""Defers a function call when it is being required like Go.
::
with deferral() as defer:
sys.setprofile(f)
defer(sys.setprofile, None)
# do something.
"""
deferred = []
defer = lambda f, *a, **k: deferred.append((f, a, k))
try:
yield defer
finally:
while deferred:
f, a, k = deferred.pop()
f(*a, **k)
|
python
|
def deferral():
"""Defers a function call when it is being required like Go.
::
with deferral() as defer:
sys.setprofile(f)
defer(sys.setprofile, None)
# do something.
"""
deferred = []
defer = lambda f, *a, **k: deferred.append((f, a, k))
try:
yield defer
finally:
while deferred:
f, a, k = deferred.pop()
f(*a, **k)
|
[
"def",
"deferral",
"(",
")",
":",
"deferred",
"=",
"[",
"]",
"defer",
"=",
"lambda",
"f",
",",
"*",
"a",
",",
"*",
"*",
"k",
":",
"deferred",
".",
"append",
"(",
"(",
"f",
",",
"a",
",",
"k",
")",
")",
"try",
":",
"yield",
"defer",
"finally",
":",
"while",
"deferred",
":",
"f",
",",
"a",
",",
"k",
"=",
"deferred",
".",
"pop",
"(",
")",
"f",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")"
] |
Defers a function call when it is being required like Go.
::
with deferral() as defer:
sys.setprofile(f)
defer(sys.setprofile, None)
# do something.
|
[
"Defers",
"a",
"function",
"call",
"when",
"it",
"is",
"being",
"required",
"like",
"Go",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/utils.py#L135-L153
|
10,462
|
what-studio/profiling
|
profiling/utils.py
|
Runnable.start
|
def start(self, *args, **kwargs):
"""Starts the instance.
:raises RuntimeError: has been already started.
:raises TypeError: :meth:`run` is not canonical.
"""
if self.is_running():
raise RuntimeError('Already started')
self._running = self.run(*args, **kwargs)
try:
yielded = next(self._running)
except StopIteration:
raise TypeError('run() must yield just one time')
if yielded is not None:
raise TypeError('run() must yield without value')
|
python
|
def start(self, *args, **kwargs):
"""Starts the instance.
:raises RuntimeError: has been already started.
:raises TypeError: :meth:`run` is not canonical.
"""
if self.is_running():
raise RuntimeError('Already started')
self._running = self.run(*args, **kwargs)
try:
yielded = next(self._running)
except StopIteration:
raise TypeError('run() must yield just one time')
if yielded is not None:
raise TypeError('run() must yield without value')
|
[
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"is_running",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Already started'",
")",
"self",
".",
"_running",
"=",
"self",
".",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yielded",
"=",
"next",
"(",
"self",
".",
"_running",
")",
"except",
"StopIteration",
":",
"raise",
"TypeError",
"(",
"'run() must yield just one time'",
")",
"if",
"yielded",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"'run() must yield without value'",
")"
] |
Starts the instance.
:raises RuntimeError: has been already started.
:raises TypeError: :meth:`run` is not canonical.
|
[
"Starts",
"the",
"instance",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/utils.py#L38-L53
|
10,463
|
what-studio/profiling
|
profiling/utils.py
|
Runnable.stop
|
def stop(self):
"""Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical.
"""
if not self.is_running():
raise RuntimeError('Not started')
running, self._running = self._running, None
try:
next(running)
except StopIteration:
# expected.
pass
else:
raise TypeError('run() must yield just one time')
|
python
|
def stop(self):
"""Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical.
"""
if not self.is_running():
raise RuntimeError('Not started')
running, self._running = self._running, None
try:
next(running)
except StopIteration:
# expected.
pass
else:
raise TypeError('run() must yield just one time')
|
[
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_running",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Not started'",
")",
"running",
",",
"self",
".",
"_running",
"=",
"self",
".",
"_running",
",",
"None",
"try",
":",
"next",
"(",
"running",
")",
"except",
"StopIteration",
":",
"# expected.",
"pass",
"else",
":",
"raise",
"TypeError",
"(",
"'run() must yield just one time'",
")"
] |
Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical.
|
[
"Stops",
"the",
"instance",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/utils.py#L55-L71
|
10,464
|
what-studio/profiling
|
profiling/remote/select.py
|
SelectProfilingServer.sockets
|
def sockets(self):
"""Returns the set of the sockets."""
if self.listener is None:
return self.clients
else:
return self.clients.union([self.listener])
|
python
|
def sockets(self):
"""Returns the set of the sockets."""
if self.listener is None:
return self.clients
else:
return self.clients.union([self.listener])
|
[
"def",
"sockets",
"(",
"self",
")",
":",
"if",
"self",
".",
"listener",
"is",
"None",
":",
"return",
"self",
".",
"clients",
"else",
":",
"return",
"self",
".",
"clients",
".",
"union",
"(",
"[",
"self",
".",
"listener",
"]",
")"
] |
Returns the set of the sockets.
|
[
"Returns",
"the",
"set",
"of",
"the",
"sockets",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/select.py#L62-L67
|
10,465
|
what-studio/profiling
|
profiling/remote/select.py
|
SelectProfilingServer.select_sockets
|
def select_sockets(self, timeout=None):
"""EINTR safe version of `select`. It focuses on just incoming
sockets.
"""
if timeout is not None:
t = time.time()
while True:
try:
ready, __, __ = select.select(self.sockets(), (), (), timeout)
except ValueError:
# there's fd=0 socket.
pass
except select.error as exc:
# ignore an interrupted system call.
if exc.args[0] != EINTR:
raise
else:
# succeeded.
return ready
# retry.
if timeout is None:
continue
# decrease timeout.
t2 = time.time()
timeout -= t2 - t
t = t2
if timeout <= 0:
# timed out.
return []
|
python
|
def select_sockets(self, timeout=None):
"""EINTR safe version of `select`. It focuses on just incoming
sockets.
"""
if timeout is not None:
t = time.time()
while True:
try:
ready, __, __ = select.select(self.sockets(), (), (), timeout)
except ValueError:
# there's fd=0 socket.
pass
except select.error as exc:
# ignore an interrupted system call.
if exc.args[0] != EINTR:
raise
else:
# succeeded.
return ready
# retry.
if timeout is None:
continue
# decrease timeout.
t2 = time.time()
timeout -= t2 - t
t = t2
if timeout <= 0:
# timed out.
return []
|
[
"def",
"select_sockets",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"ready",
",",
"__",
",",
"__",
"=",
"select",
".",
"select",
"(",
"self",
".",
"sockets",
"(",
")",
",",
"(",
")",
",",
"(",
")",
",",
"timeout",
")",
"except",
"ValueError",
":",
"# there's fd=0 socket.",
"pass",
"except",
"select",
".",
"error",
"as",
"exc",
":",
"# ignore an interrupted system call.",
"if",
"exc",
".",
"args",
"[",
"0",
"]",
"!=",
"EINTR",
":",
"raise",
"else",
":",
"# succeeded.",
"return",
"ready",
"# retry.",
"if",
"timeout",
"is",
"None",
":",
"continue",
"# decrease timeout.",
"t2",
"=",
"time",
".",
"time",
"(",
")",
"timeout",
"-=",
"t2",
"-",
"t",
"t",
"=",
"t2",
"if",
"timeout",
"<=",
"0",
":",
"# timed out.",
"return",
"[",
"]"
] |
EINTR safe version of `select`. It focuses on just incoming
sockets.
|
[
"EINTR",
"safe",
"version",
"of",
"select",
".",
"It",
"focuses",
"on",
"just",
"incoming",
"sockets",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/select.py#L69-L97
|
10,466
|
what-studio/profiling
|
profiling/remote/select.py
|
SelectProfilingServer.dispatch_sockets
|
def dispatch_sockets(self, timeout=None):
"""Dispatches incoming sockets."""
for sock in self.select_sockets(timeout=timeout):
if sock is self.listener:
listener = sock
sock, addr = listener.accept()
self.connected(sock)
else:
try:
sock.recv(1)
except socket.error as exc:
if exc.errno != ECONNRESET:
raise
self.disconnected(sock)
|
python
|
def dispatch_sockets(self, timeout=None):
"""Dispatches incoming sockets."""
for sock in self.select_sockets(timeout=timeout):
if sock is self.listener:
listener = sock
sock, addr = listener.accept()
self.connected(sock)
else:
try:
sock.recv(1)
except socket.error as exc:
if exc.errno != ECONNRESET:
raise
self.disconnected(sock)
|
[
"def",
"dispatch_sockets",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"for",
"sock",
"in",
"self",
".",
"select_sockets",
"(",
"timeout",
"=",
"timeout",
")",
":",
"if",
"sock",
"is",
"self",
".",
"listener",
":",
"listener",
"=",
"sock",
"sock",
",",
"addr",
"=",
"listener",
".",
"accept",
"(",
")",
"self",
".",
"connected",
"(",
"sock",
")",
"else",
":",
"try",
":",
"sock",
".",
"recv",
"(",
"1",
")",
"except",
"socket",
".",
"error",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"ECONNRESET",
":",
"raise",
"self",
".",
"disconnected",
"(",
"sock",
")"
] |
Dispatches incoming sockets.
|
[
"Dispatches",
"incoming",
"sockets",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/select.py#L99-L112
|
10,467
|
what-studio/profiling
|
profiling/tracing/__init__.py
|
TracingProfiler.record_entering
|
def record_entering(self, time, code, frame_key, parent_stats):
"""Entered to a function call."""
stats = parent_stats.ensure_child(code, RecordingStatistics)
self._times_entered[(code, frame_key)] = time
stats.own_hits += 1
|
python
|
def record_entering(self, time, code, frame_key, parent_stats):
"""Entered to a function call."""
stats = parent_stats.ensure_child(code, RecordingStatistics)
self._times_entered[(code, frame_key)] = time
stats.own_hits += 1
|
[
"def",
"record_entering",
"(",
"self",
",",
"time",
",",
"code",
",",
"frame_key",
",",
"parent_stats",
")",
":",
"stats",
"=",
"parent_stats",
".",
"ensure_child",
"(",
"code",
",",
"RecordingStatistics",
")",
"self",
".",
"_times_entered",
"[",
"(",
"code",
",",
"frame_key",
")",
"]",
"=",
"time",
"stats",
".",
"own_hits",
"+=",
"1"
] |
Entered to a function call.
|
[
"Entered",
"to",
"a",
"function",
"call",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/tracing/__init__.py#L110-L114
|
10,468
|
what-studio/profiling
|
profiling/tracing/__init__.py
|
TracingProfiler.record_leaving
|
def record_leaving(self, time, code, frame_key, parent_stats):
"""Left from a function call."""
try:
stats = parent_stats.get_child(code)
time_entered = self._times_entered.pop((code, frame_key))
except KeyError:
return
time_elapsed = time - time_entered
stats.deep_time += max(0, time_elapsed)
|
python
|
def record_leaving(self, time, code, frame_key, parent_stats):
"""Left from a function call."""
try:
stats = parent_stats.get_child(code)
time_entered = self._times_entered.pop((code, frame_key))
except KeyError:
return
time_elapsed = time - time_entered
stats.deep_time += max(0, time_elapsed)
|
[
"def",
"record_leaving",
"(",
"self",
",",
"time",
",",
"code",
",",
"frame_key",
",",
"parent_stats",
")",
":",
"try",
":",
"stats",
"=",
"parent_stats",
".",
"get_child",
"(",
"code",
")",
"time_entered",
"=",
"self",
".",
"_times_entered",
".",
"pop",
"(",
"(",
"code",
",",
"frame_key",
")",
")",
"except",
"KeyError",
":",
"return",
"time_elapsed",
"=",
"time",
"-",
"time_entered",
"stats",
".",
"deep_time",
"+=",
"max",
"(",
"0",
",",
"time_elapsed",
")"
] |
Left from a function call.
|
[
"Left",
"from",
"a",
"function",
"call",
"."
] |
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
|
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/tracing/__init__.py#L116-L124
|
10,469
|
semiversus/python-broqer
|
broqer/op/subscribers/sink.py
|
build_sink
|
def build_sink(function: Callable[..., None] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Sink subscriber.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_sink(function: Callable[..., None]):
@wraps(function)
def _wrapper(*args, **kwargs) -> Sink:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Sink(function, *args, unpack=unpack, **kwargs)
return _wrapper
if function:
return _build_sink(function)
return _build_sink
|
python
|
def build_sink(function: Callable[..., None] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Sink subscriber.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_sink(function: Callable[..., None]):
@wraps(function)
def _wrapper(*args, **kwargs) -> Sink:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Sink(function, *args, unpack=unpack, **kwargs)
return _wrapper
if function:
return _build_sink(function)
return _build_sink
|
[
"def",
"build_sink",
"(",
"function",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
"=",
"None",
",",
"*",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"def",
"_build_sink",
"(",
"function",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Sink",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"return",
"Sink",
"(",
"function",
",",
"*",
"args",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_sink",
"(",
"function",
")",
"return",
"_build_sink"
] |
Decorator to wrap a function to return a Sink subscriber.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
|
[
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"Sink",
"subscriber",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/subscribers/sink.py#L62-L80
|
10,470
|
semiversus/python-broqer
|
broqer/op/map_.py
|
build_map
|
def build_map(function: Callable[[Any], Any] = None,
unpack: bool = False):
""" Decorator to wrap a function to return a Map operator.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_map(function: Callable[[Any], Any]):
@wraps(function)
def _wrapper(*args, **kwargs) -> Map:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Map(function, *args, unpack=unpack, **kwargs)
return _wrapper
if function:
return _build_map(function)
return _build_map
|
python
|
def build_map(function: Callable[[Any], Any] = None,
unpack: bool = False):
""" Decorator to wrap a function to return a Map operator.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_map(function: Callable[[Any], Any]):
@wraps(function)
def _wrapper(*args, **kwargs) -> Map:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Map(function, *args, unpack=unpack, **kwargs)
return _wrapper
if function:
return _build_map(function)
return _build_map
|
[
"def",
"build_map",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
"=",
"None",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"def",
"_build_map",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Map",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"return",
"Map",
"(",
"function",
",",
"*",
"args",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_map",
"(",
"function",
")",
"return",
"_build_map"
] |
Decorator to wrap a function to return a Map operator.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
|
[
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"Map",
"operator",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_.py#L92-L110
|
10,471
|
semiversus/python-broqer
|
broqer/op/subscribers/trace.py
|
Trace._trace_handler
|
def _trace_handler(publisher, value, label=None):
""" Default trace handler is printing the timestamp, the publisher name
and the emitted value
"""
line = '--- %8.3f: ' % (time() - Trace._timestamp_start)
line += repr(publisher) if label is None else label
line += ' %r' % (value,)
print(line)
|
python
|
def _trace_handler(publisher, value, label=None):
""" Default trace handler is printing the timestamp, the publisher name
and the emitted value
"""
line = '--- %8.3f: ' % (time() - Trace._timestamp_start)
line += repr(publisher) if label is None else label
line += ' %r' % (value,)
print(line)
|
[
"def",
"_trace_handler",
"(",
"publisher",
",",
"value",
",",
"label",
"=",
"None",
")",
":",
"line",
"=",
"'--- %8.3f: '",
"%",
"(",
"time",
"(",
")",
"-",
"Trace",
".",
"_timestamp_start",
")",
"line",
"+=",
"repr",
"(",
"publisher",
")",
"if",
"label",
"is",
"None",
"else",
"label",
"line",
"+=",
"' %r'",
"%",
"(",
"value",
",",
")",
"print",
"(",
"line",
")"
] |
Default trace handler is printing the timestamp, the publisher name
and the emitted value
|
[
"Default",
"trace",
"handler",
"is",
"printing",
"the",
"timestamp",
"the",
"publisher",
"name",
"and",
"the",
"emitted",
"value"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/subscribers/trace.py#L45-L52
|
10,472
|
semiversus/python-broqer
|
broqer/op/subscribers/sink_async.py
|
build_sink_async
|
def build_sink_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a SinkAsync subscriber.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_sink_async(coro):
@wraps(coro)
def _wrapper(*args, mode=None, **kwargs) -> SinkAsync:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return SinkAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
return _wrapper
if coro:
return _build_sink_async(coro)
return _build_sink_async
|
python
|
def build_sink_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a SinkAsync subscriber.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_sink_async(coro):
@wraps(coro)
def _wrapper(*args, mode=None, **kwargs) -> SinkAsync:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return SinkAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
return _wrapper
if coro:
return _build_sink_async(coro)
return _build_sink_async
|
[
"def",
"build_sink_async",
"(",
"coro",
"=",
"None",
",",
"*",
",",
"mode",
"=",
"None",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"_mode",
"=",
"mode",
"def",
"_build_sink_async",
"(",
"coro",
")",
":",
"@",
"wraps",
"(",
"coro",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"mode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"SinkAsync",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"MODE",
".",
"CONCURRENT",
"if",
"_mode",
"is",
"None",
"else",
"_mode",
"return",
"SinkAsync",
"(",
"coro",
",",
"*",
"args",
",",
"mode",
"=",
"mode",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"coro",
":",
"return",
"_build_sink_async",
"(",
"coro",
")",
"return",
"_build_sink_async"
] |
Decorator to wrap a coroutine to return a SinkAsync subscriber.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
|
[
"Decorator",
"to",
"wrap",
"a",
"coroutine",
"to",
"return",
"a",
"SinkAsync",
"subscriber",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/subscribers/sink_async.py#L60-L82
|
10,473
|
semiversus/python-broqer
|
broqer/op/accumulate.py
|
build_accumulate
|
def build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return an Accumulate operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def _build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]]):
@wraps(function)
def _wrapper(init=NONE) -> Accumulate:
init = _init if init is NONE else init
if init is NONE:
raise TypeError('"init" argument has to be defined')
return Accumulate(function, init=init)
return _wrapper
if function:
return _build_accumulate(function)
return _build_accumulate
|
python
|
def build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return an Accumulate operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def _build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]]):
@wraps(function)
def _wrapper(init=NONE) -> Accumulate:
init = _init if init is NONE else init
if init is NONE:
raise TypeError('"init" argument has to be defined')
return Accumulate(function, init=init)
return _wrapper
if function:
return _build_accumulate(function)
return _build_accumulate
|
[
"def",
"build_accumulate",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"*",
",",
"init",
":",
"Any",
"=",
"NONE",
")",
":",
"_init",
"=",
"init",
"def",
"_build_accumulate",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"init",
"=",
"NONE",
")",
"->",
"Accumulate",
":",
"init",
"=",
"_init",
"if",
"init",
"is",
"NONE",
"else",
"init",
"if",
"init",
"is",
"NONE",
":",
"raise",
"TypeError",
"(",
"'\"init\" argument has to be defined'",
")",
"return",
"Accumulate",
"(",
"function",
",",
"init",
"=",
"init",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_accumulate",
"(",
"function",
")",
"return",
"_build_accumulate"
] |
Decorator to wrap a function to return an Accumulate operator.
:param function: function to be wrapped
:param init: optional initialization for state
|
[
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"an",
"Accumulate",
"operator",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/accumulate.py#L75-L96
|
10,474
|
semiversus/python-broqer
|
broqer/hub/utils/datatype_check.py
|
resolve_meta_key
|
def resolve_meta_key(hub, key, meta):
""" Resolve a value when it's a string and starts with '>' """
if key not in meta:
return None
value = meta[key]
if isinstance(value, str) and value[0] == '>':
topic = value[1:]
if topic not in hub:
raise KeyError('topic %s not found in hub' % topic)
return hub[topic].get()
return value
|
python
|
def resolve_meta_key(hub, key, meta):
""" Resolve a value when it's a string and starts with '>' """
if key not in meta:
return None
value = meta[key]
if isinstance(value, str) and value[0] == '>':
topic = value[1:]
if topic not in hub:
raise KeyError('topic %s not found in hub' % topic)
return hub[topic].get()
return value
|
[
"def",
"resolve_meta_key",
"(",
"hub",
",",
"key",
",",
"meta",
")",
":",
"if",
"key",
"not",
"in",
"meta",
":",
"return",
"None",
"value",
"=",
"meta",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
"and",
"value",
"[",
"0",
"]",
"==",
"'>'",
":",
"topic",
"=",
"value",
"[",
"1",
":",
"]",
"if",
"topic",
"not",
"in",
"hub",
":",
"raise",
"KeyError",
"(",
"'topic %s not found in hub'",
"%",
"topic",
")",
"return",
"hub",
"[",
"topic",
"]",
".",
"get",
"(",
")",
"return",
"value"
] |
Resolve a value when it's a string and starts with '>'
|
[
"Resolve",
"a",
"value",
"when",
"it",
"s",
"a",
"string",
"and",
"starts",
"with",
">"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L10-L20
|
10,475
|
semiversus/python-broqer
|
broqer/hub/utils/datatype_check.py
|
DTTopic.checked_emit
|
def checked_emit(self, value: Any) -> asyncio.Future:
""" Casting and checking in one call """
if not isinstance(self._subject, Subscriber):
raise TypeError('Topic %r has to be a subscriber' % self._path)
value = self.cast(value)
self.check(value)
return self._subject.emit(value, who=self)
|
python
|
def checked_emit(self, value: Any) -> asyncio.Future:
""" Casting and checking in one call """
if not isinstance(self._subject, Subscriber):
raise TypeError('Topic %r has to be a subscriber' % self._path)
value = self.cast(value)
self.check(value)
return self._subject.emit(value, who=self)
|
[
"def",
"checked_emit",
"(",
"self",
",",
"value",
":",
"Any",
")",
"->",
"asyncio",
".",
"Future",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_subject",
",",
"Subscriber",
")",
":",
"raise",
"TypeError",
"(",
"'Topic %r has to be a subscriber'",
"%",
"self",
".",
"_path",
")",
"value",
"=",
"self",
".",
"cast",
"(",
"value",
")",
"self",
".",
"check",
"(",
"value",
")",
"return",
"self",
".",
"_subject",
".",
"emit",
"(",
"value",
",",
"who",
"=",
"self",
")"
] |
Casting and checking in one call
|
[
"Casting",
"and",
"checking",
"in",
"one",
"call"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L178-L186
|
10,476
|
semiversus/python-broqer
|
broqer/hub/utils/datatype_check.py
|
DTRegistry.add_datatype
|
def add_datatype(self, name: str, datatype: DT):
""" Register the datatype with it's name """
self._datatypes[name] = datatype
|
python
|
def add_datatype(self, name: str, datatype: DT):
""" Register the datatype with it's name """
self._datatypes[name] = datatype
|
[
"def",
"add_datatype",
"(",
"self",
",",
"name",
":",
"str",
",",
"datatype",
":",
"DT",
")",
":",
"self",
".",
"_datatypes",
"[",
"name",
"]",
"=",
"datatype"
] |
Register the datatype with it's name
|
[
"Register",
"the",
"datatype",
"with",
"it",
"s",
"name"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L202-L204
|
10,477
|
semiversus/python-broqer
|
broqer/hub/utils/datatype_check.py
|
DTRegistry.cast
|
def cast(self, topic, value):
""" Cast a string to the value based on the datatype """
datatype_key = topic.meta.get('datatype', 'none')
result = self._datatypes[datatype_key].cast(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
result = self._datatypes[validate_dt].cast(topic, result)
return result
|
python
|
def cast(self, topic, value):
""" Cast a string to the value based on the datatype """
datatype_key = topic.meta.get('datatype', 'none')
result = self._datatypes[datatype_key].cast(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
result = self._datatypes[validate_dt].cast(topic, result)
return result
|
[
"def",
"cast",
"(",
"self",
",",
"topic",
",",
"value",
")",
":",
"datatype_key",
"=",
"topic",
".",
"meta",
".",
"get",
"(",
"'datatype'",
",",
"'none'",
")",
"result",
"=",
"self",
".",
"_datatypes",
"[",
"datatype_key",
"]",
".",
"cast",
"(",
"topic",
",",
"value",
")",
"validate_dt",
"=",
"topic",
".",
"meta",
".",
"get",
"(",
"'validate'",
",",
"None",
")",
"if",
"validate_dt",
":",
"result",
"=",
"self",
".",
"_datatypes",
"[",
"validate_dt",
"]",
".",
"cast",
"(",
"topic",
",",
"result",
")",
"return",
"result"
] |
Cast a string to the value based on the datatype
|
[
"Cast",
"a",
"string",
"to",
"the",
"value",
"based",
"on",
"the",
"datatype"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L213-L220
|
10,478
|
semiversus/python-broqer
|
broqer/hub/utils/datatype_check.py
|
DTRegistry.check
|
def check(self, topic, value):
""" Checking the value if it fits into the given specification """
datatype_key = topic.meta.get('datatype', 'none')
self._datatypes[datatype_key].check(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
self._datatypes[validate_dt].check(topic, value)
|
python
|
def check(self, topic, value):
""" Checking the value if it fits into the given specification """
datatype_key = topic.meta.get('datatype', 'none')
self._datatypes[datatype_key].check(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
self._datatypes[validate_dt].check(topic, value)
|
[
"def",
"check",
"(",
"self",
",",
"topic",
",",
"value",
")",
":",
"datatype_key",
"=",
"topic",
".",
"meta",
".",
"get",
"(",
"'datatype'",
",",
"'none'",
")",
"self",
".",
"_datatypes",
"[",
"datatype_key",
"]",
".",
"check",
"(",
"topic",
",",
"value",
")",
"validate_dt",
"=",
"topic",
".",
"meta",
".",
"get",
"(",
"'validate'",
",",
"None",
")",
"if",
"validate_dt",
":",
"self",
".",
"_datatypes",
"[",
"validate_dt",
"]",
".",
"check",
"(",
"topic",
",",
"value",
")"
] |
Checking the value if it fits into the given specification
|
[
"Checking",
"the",
"value",
"if",
"it",
"fits",
"into",
"the",
"given",
"specification"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L222-L228
|
10,479
|
semiversus/python-broqer
|
broqer/op/partition.py
|
Partition.flush
|
def flush(self):
""" Emits the current queue and clears the queue """
self.notify(tuple(self._queue))
self._queue.clear()
|
python
|
def flush(self):
""" Emits the current queue and clears the queue """
self.notify(tuple(self._queue))
self._queue.clear()
|
[
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"notify",
"(",
"tuple",
"(",
"self",
".",
"_queue",
")",
")",
"self",
".",
"_queue",
".",
"clear",
"(",
")"
] |
Emits the current queue and clears the queue
|
[
"Emits",
"the",
"current",
"queue",
"and",
"clears",
"the",
"queue"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/partition.py#L66-L69
|
10,480
|
semiversus/python-broqer
|
broqer/op/sample.py
|
Sample._periodic_callback
|
def _periodic_callback(self):
""" Will be started on first emit """
try:
self.notify(self._state) # emit to all subscribers
except Exception: # pylint: disable=broad-except
self._error_callback(*sys.exc_info())
if self._subscriptions:
# if there are still subscriptions register next _periodic callback
self._call_later_handle = \
self._loop.call_later(self._interval, self._periodic_callback)
else:
self._state = NONE
self._call_later_handle = None
|
python
|
def _periodic_callback(self):
""" Will be started on first emit """
try:
self.notify(self._state) # emit to all subscribers
except Exception: # pylint: disable=broad-except
self._error_callback(*sys.exc_info())
if self._subscriptions:
# if there are still subscriptions register next _periodic callback
self._call_later_handle = \
self._loop.call_later(self._interval, self._periodic_callback)
else:
self._state = NONE
self._call_later_handle = None
|
[
"def",
"_periodic_callback",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"notify",
"(",
"self",
".",
"_state",
")",
"# emit to all subscribers",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"self",
".",
"_error_callback",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
"if",
"self",
".",
"_subscriptions",
":",
"# if there are still subscriptions register next _periodic callback",
"self",
".",
"_call_later_handle",
"=",
"self",
".",
"_loop",
".",
"call_later",
"(",
"self",
".",
"_interval",
",",
"self",
".",
"_periodic_callback",
")",
"else",
":",
"self",
".",
"_state",
"=",
"NONE",
"self",
".",
"_call_later_handle",
"=",
"None"
] |
Will be started on first emit
|
[
"Will",
"be",
"started",
"on",
"first",
"emit"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/sample.py#L84-L97
|
10,481
|
semiversus/python-broqer
|
broqer/op/reduce.py
|
build_reduce
|
def build_reduce(function: Callable[[Any, Any], Any] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return a Reduce operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def _build_reduce(function: Callable[[Any, Any], Any]):
@wraps(function)
def _wrapper(init=NONE) -> Reduce:
init = _init if init is NONE else init
if init is NONE:
raise TypeError('init argument has to be defined')
return Reduce(function, init=init)
return _wrapper
if function:
return _build_reduce(function)
return _build_reduce
|
python
|
def build_reduce(function: Callable[[Any, Any], Any] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return a Reduce operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def _build_reduce(function: Callable[[Any, Any], Any]):
@wraps(function)
def _wrapper(init=NONE) -> Reduce:
init = _init if init is NONE else init
if init is NONE:
raise TypeError('init argument has to be defined')
return Reduce(function, init=init)
return _wrapper
if function:
return _build_reduce(function)
return _build_reduce
|
[
"def",
"build_reduce",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Any",
"]",
"=",
"None",
",",
"*",
",",
"init",
":",
"Any",
"=",
"NONE",
")",
":",
"_init",
"=",
"init",
"def",
"_build_reduce",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Any",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"init",
"=",
"NONE",
")",
"->",
"Reduce",
":",
"init",
"=",
"_init",
"if",
"init",
"is",
"NONE",
"else",
"init",
"if",
"init",
"is",
"NONE",
":",
"raise",
"TypeError",
"(",
"'init argument has to be defined'",
")",
"return",
"Reduce",
"(",
"function",
",",
"init",
"=",
"init",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_reduce",
"(",
"function",
")",
"return",
"_build_reduce"
] |
Decorator to wrap a function to return a Reduce operator.
:param function: function to be wrapped
:param init: optional initialization for state
|
[
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"Reduce",
"operator",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/reduce.py#L54-L75
|
10,482
|
semiversus/python-broqer
|
broqer/op/sliding_window.py
|
SlidingWindow.flush
|
def flush(self):
""" Flush the queue - this will emit the current queue """
if not self._emit_partial and len(self._state) != self._state.maxlen:
self.notify(tuple(self._state))
self._state.clear()
|
python
|
def flush(self):
""" Flush the queue - this will emit the current queue """
if not self._emit_partial and len(self._state) != self._state.maxlen:
self.notify(tuple(self._state))
self._state.clear()
|
[
"def",
"flush",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_emit_partial",
"and",
"len",
"(",
"self",
".",
"_state",
")",
"!=",
"self",
".",
"_state",
".",
"maxlen",
":",
"self",
".",
"notify",
"(",
"tuple",
"(",
"self",
".",
"_state",
")",
")",
"self",
".",
"_state",
".",
"clear",
"(",
")"
] |
Flush the queue - this will emit the current queue
|
[
"Flush",
"the",
"queue",
"-",
"this",
"will",
"emit",
"the",
"current",
"queue"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/sliding_window.py#L73-L77
|
10,483
|
semiversus/python-broqer
|
broqer/op/map_async.py
|
build_map_async
|
def build_map_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a MapAsync operator.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_map_async(coro):
@wraps(coro)
def _wrapper(*args, mode=None, **kwargs) -> MapAsync:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return MapAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
return _wrapper
if coro:
return _build_map_async(coro)
return _build_map_async
|
python
|
def build_map_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a MapAsync operator.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_map_async(coro):
@wraps(coro)
def _wrapper(*args, mode=None, **kwargs) -> MapAsync:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return MapAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
return _wrapper
if coro:
return _build_map_async(coro)
return _build_map_async
|
[
"def",
"build_map_async",
"(",
"coro",
"=",
"None",
",",
"*",
",",
"mode",
"=",
"None",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"_mode",
"=",
"mode",
"def",
"_build_map_async",
"(",
"coro",
")",
":",
"@",
"wraps",
"(",
"coro",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"mode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"MapAsync",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"MODE",
".",
"CONCURRENT",
"if",
"_mode",
"is",
"None",
"else",
"_mode",
"return",
"MapAsync",
"(",
"coro",
",",
"*",
"args",
",",
"mode",
"=",
"mode",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"coro",
":",
"return",
"_build_map_async",
"(",
"coro",
")",
"return",
"_build_map_async"
] |
Decorator to wrap a coroutine to return a MapAsync operator.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
|
[
"Decorator",
"to",
"wrap",
"a",
"coroutine",
"to",
"return",
"a",
"MapAsync",
"operator",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_async.py#L234-L256
|
10,484
|
semiversus/python-broqer
|
broqer/op/map_async.py
|
MapAsync._future_done
|
def _future_done(self, future):
""" Will be called when the coroutine is done """
try:
# notify the subscribers (except result is an exception or NONE)
result = future.result() # may raise exception
if result is not NONE:
self.notify(result) # may also raise exception
except asyncio.CancelledError:
return
except Exception: # pylint: disable=broad-except
self._options.error_callback(*sys.exc_info())
# check if queue is present and something is in the queue
if self._queue:
value = self._queue.popleft()
# start the coroutine
self._run_coro(value)
else:
self._future = None
|
python
|
def _future_done(self, future):
""" Will be called when the coroutine is done """
try:
# notify the subscribers (except result is an exception or NONE)
result = future.result() # may raise exception
if result is not NONE:
self.notify(result) # may also raise exception
except asyncio.CancelledError:
return
except Exception: # pylint: disable=broad-except
self._options.error_callback(*sys.exc_info())
# check if queue is present and something is in the queue
if self._queue:
value = self._queue.popleft()
# start the coroutine
self._run_coro(value)
else:
self._future = None
|
[
"def",
"_future_done",
"(",
"self",
",",
"future",
")",
":",
"try",
":",
"# notify the subscribers (except result is an exception or NONE)",
"result",
"=",
"future",
".",
"result",
"(",
")",
"# may raise exception",
"if",
"result",
"is",
"not",
"NONE",
":",
"self",
".",
"notify",
"(",
"result",
")",
"# may also raise exception",
"except",
"asyncio",
".",
"CancelledError",
":",
"return",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"self",
".",
"_options",
".",
"error_callback",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
"# check if queue is present and something is in the queue",
"if",
"self",
".",
"_queue",
":",
"value",
"=",
"self",
".",
"_queue",
".",
"popleft",
"(",
")",
"# start the coroutine",
"self",
".",
"_run_coro",
"(",
"value",
")",
"else",
":",
"self",
".",
"_future",
"=",
"None"
] |
Will be called when the coroutine is done
|
[
"Will",
"be",
"called",
"when",
"the",
"coroutine",
"is",
"done"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_async.py#L188-L207
|
10,485
|
semiversus/python-broqer
|
broqer/op/map_async.py
|
MapAsync._run_coro
|
def _run_coro(self, value):
""" Start the coroutine as task """
# when LAST_DISTINCT is used only start coroutine when value changed
if self._options.mode is MODE.LAST_DISTINCT and \
value == self._last_emit:
self._future = None
return
# store the value to be emitted for LAST_DISTINCT
self._last_emit = value
# publish the start of the coroutine
self.scheduled.notify(value)
# build the coroutine
values = value if self._options.unpack else (value,)
coro = self._options.coro(*values, *self._options.args,
**self._options.kwargs)
# create a task out of it and add ._future_done as callback
self._future = asyncio.ensure_future(coro)
self._future.add_done_callback(self._future_done)
|
python
|
def _run_coro(self, value):
""" Start the coroutine as task """
# when LAST_DISTINCT is used only start coroutine when value changed
if self._options.mode is MODE.LAST_DISTINCT and \
value == self._last_emit:
self._future = None
return
# store the value to be emitted for LAST_DISTINCT
self._last_emit = value
# publish the start of the coroutine
self.scheduled.notify(value)
# build the coroutine
values = value if self._options.unpack else (value,)
coro = self._options.coro(*values, *self._options.args,
**self._options.kwargs)
# create a task out of it and add ._future_done as callback
self._future = asyncio.ensure_future(coro)
self._future.add_done_callback(self._future_done)
|
[
"def",
"_run_coro",
"(",
"self",
",",
"value",
")",
":",
"# when LAST_DISTINCT is used only start coroutine when value changed",
"if",
"self",
".",
"_options",
".",
"mode",
"is",
"MODE",
".",
"LAST_DISTINCT",
"and",
"value",
"==",
"self",
".",
"_last_emit",
":",
"self",
".",
"_future",
"=",
"None",
"return",
"# store the value to be emitted for LAST_DISTINCT",
"self",
".",
"_last_emit",
"=",
"value",
"# publish the start of the coroutine",
"self",
".",
"scheduled",
".",
"notify",
"(",
"value",
")",
"# build the coroutine",
"values",
"=",
"value",
"if",
"self",
".",
"_options",
".",
"unpack",
"else",
"(",
"value",
",",
")",
"coro",
"=",
"self",
".",
"_options",
".",
"coro",
"(",
"*",
"values",
",",
"*",
"self",
".",
"_options",
".",
"args",
",",
"*",
"*",
"self",
".",
"_options",
".",
"kwargs",
")",
"# create a task out of it and add ._future_done as callback",
"self",
".",
"_future",
"=",
"asyncio",
".",
"ensure_future",
"(",
"coro",
")",
"self",
".",
"_future",
".",
"add_done_callback",
"(",
"self",
".",
"_future_done",
")"
] |
Start the coroutine as task
|
[
"Start",
"the",
"coroutine",
"as",
"task"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_async.py#L209-L231
|
10,486
|
semiversus/python-broqer
|
broqer/op/filter_.py
|
build_filter
|
def build_filter(predicate: Callable[[Any], bool] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Filter operator.
:param predicate: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_filter(predicate: Callable[[Any], bool]):
@wraps(predicate)
def _wrapper(*args, **kwargs) -> Filter:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Filter(predicate, *args, unpack=unpack, **kwargs)
return _wrapper
if predicate:
return _build_filter(predicate)
return _build_filter
|
python
|
def build_filter(predicate: Callable[[Any], bool] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Filter operator.
:param predicate: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_filter(predicate: Callable[[Any], bool]):
@wraps(predicate)
def _wrapper(*args, **kwargs) -> Filter:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Filter(predicate, *args, unpack=unpack, **kwargs)
return _wrapper
if predicate:
return _build_filter(predicate)
return _build_filter
|
[
"def",
"build_filter",
"(",
"predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
"=",
"None",
",",
"*",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"def",
"_build_filter",
"(",
"predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
")",
":",
"@",
"wraps",
"(",
"predicate",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Filter",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"return",
"Filter",
"(",
"predicate",
",",
"*",
"args",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"predicate",
":",
"return",
"_build_filter",
"(",
"predicate",
")",
"return",
"_build_filter"
] |
Decorator to wrap a function to return a Filter operator.
:param predicate: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
|
[
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"Filter",
"operator",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/filter_.py#L119-L137
|
10,487
|
semiversus/python-broqer
|
broqer/op/operator_overloading.py
|
apply_operator_overloading
|
def apply_operator_overloading():
""" Function to apply operator overloading to Publisher class """
# operator overloading is (unfortunately) not working for the following
# cases:
# int, float, str - should return appropriate type instead of a Publisher
# len - should return an integer
# "x in y" - is using __bool__ which is not working with Publisher
for method in (
'__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__',
'__add__', '__and__', '__lshift__', '__mod__', '__mul__',
'__pow__', '__rshift__', '__sub__', '__xor__', '__concat__',
'__getitem__', '__floordiv__', '__truediv__'):
def _op(operand_left, operand_right, operation=method):
if isinstance(operand_right, Publisher):
return CombineLatest(operand_left, operand_right,
map_=getattr(operator, operation))
return _MapConstant(operand_left, operand_right,
getattr(operator, operation))
setattr(Publisher, method, _op)
for method, _method in (
('__radd__', '__add__'), ('__rand__', '__and__'),
('__rlshift__', '__lshift__'), ('__rmod__', '__mod__'),
('__rmul__', '__mul__'), ('__rpow__', '__pow__'),
('__rrshift__', '__rshift__'), ('__rsub__', '__sub__'),
('__rxor__', '__xor__'), ('__rfloordiv__', '__floordiv__'),
('__rtruediv__', '__truediv__')):
def _op(operand_left, operand_right, operation=_method):
return _MapConstantReverse(operand_left, operand_right,
getattr(operator, operation))
setattr(Publisher, method, _op)
for method, _method in (
('__neg__', operator.neg), ('__pos__', operator.pos),
('__abs__', operator.abs), ('__invert__', operator.invert),
('__round__', round), ('__trunc__', math.trunc),
('__floor__', math.floor), ('__ceil__', math.ceil)):
def _op_unary(operand, operation=_method):
return _MapUnary(operand, operation)
setattr(Publisher, method, _op_unary)
def _getattr(publisher, attribute_name):
if not publisher.inherited_type or \
not hasattr(publisher.inherited_type, attribute_name):
raise AttributeError('Attribute %r not found' % attribute_name)
return _GetAttr(publisher, attribute_name)
setattr(Publisher, '__getattr__', _getattr)
|
python
|
def apply_operator_overloading():
""" Function to apply operator overloading to Publisher class """
# operator overloading is (unfortunately) not working for the following
# cases:
# int, float, str - should return appropriate type instead of a Publisher
# len - should return an integer
# "x in y" - is using __bool__ which is not working with Publisher
for method in (
'__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__',
'__add__', '__and__', '__lshift__', '__mod__', '__mul__',
'__pow__', '__rshift__', '__sub__', '__xor__', '__concat__',
'__getitem__', '__floordiv__', '__truediv__'):
def _op(operand_left, operand_right, operation=method):
if isinstance(operand_right, Publisher):
return CombineLatest(operand_left, operand_right,
map_=getattr(operator, operation))
return _MapConstant(operand_left, operand_right,
getattr(operator, operation))
setattr(Publisher, method, _op)
for method, _method in (
('__radd__', '__add__'), ('__rand__', '__and__'),
('__rlshift__', '__lshift__'), ('__rmod__', '__mod__'),
('__rmul__', '__mul__'), ('__rpow__', '__pow__'),
('__rrshift__', '__rshift__'), ('__rsub__', '__sub__'),
('__rxor__', '__xor__'), ('__rfloordiv__', '__floordiv__'),
('__rtruediv__', '__truediv__')):
def _op(operand_left, operand_right, operation=_method):
return _MapConstantReverse(operand_left, operand_right,
getattr(operator, operation))
setattr(Publisher, method, _op)
for method, _method in (
('__neg__', operator.neg), ('__pos__', operator.pos),
('__abs__', operator.abs), ('__invert__', operator.invert),
('__round__', round), ('__trunc__', math.trunc),
('__floor__', math.floor), ('__ceil__', math.ceil)):
def _op_unary(operand, operation=_method):
return _MapUnary(operand, operation)
setattr(Publisher, method, _op_unary)
def _getattr(publisher, attribute_name):
if not publisher.inherited_type or \
not hasattr(publisher.inherited_type, attribute_name):
raise AttributeError('Attribute %r not found' % attribute_name)
return _GetAttr(publisher, attribute_name)
setattr(Publisher, '__getattr__', _getattr)
|
[
"def",
"apply_operator_overloading",
"(",
")",
":",
"# operator overloading is (unfortunately) not working for the following",
"# cases:",
"# int, float, str - should return appropriate type instead of a Publisher",
"# len - should return an integer",
"# \"x in y\" - is using __bool__ which is not working with Publisher",
"for",
"method",
"in",
"(",
"'__lt__'",
",",
"'__le__'",
",",
"'__eq__'",
",",
"'__ne__'",
",",
"'__ge__'",
",",
"'__gt__'",
",",
"'__add__'",
",",
"'__and__'",
",",
"'__lshift__'",
",",
"'__mod__'",
",",
"'__mul__'",
",",
"'__pow__'",
",",
"'__rshift__'",
",",
"'__sub__'",
",",
"'__xor__'",
",",
"'__concat__'",
",",
"'__getitem__'",
",",
"'__floordiv__'",
",",
"'__truediv__'",
")",
":",
"def",
"_op",
"(",
"operand_left",
",",
"operand_right",
",",
"operation",
"=",
"method",
")",
":",
"if",
"isinstance",
"(",
"operand_right",
",",
"Publisher",
")",
":",
"return",
"CombineLatest",
"(",
"operand_left",
",",
"operand_right",
",",
"map_",
"=",
"getattr",
"(",
"operator",
",",
"operation",
")",
")",
"return",
"_MapConstant",
"(",
"operand_left",
",",
"operand_right",
",",
"getattr",
"(",
"operator",
",",
"operation",
")",
")",
"setattr",
"(",
"Publisher",
",",
"method",
",",
"_op",
")",
"for",
"method",
",",
"_method",
"in",
"(",
"(",
"'__radd__'",
",",
"'__add__'",
")",
",",
"(",
"'__rand__'",
",",
"'__and__'",
")",
",",
"(",
"'__rlshift__'",
",",
"'__lshift__'",
")",
",",
"(",
"'__rmod__'",
",",
"'__mod__'",
")",
",",
"(",
"'__rmul__'",
",",
"'__mul__'",
")",
",",
"(",
"'__rpow__'",
",",
"'__pow__'",
")",
",",
"(",
"'__rrshift__'",
",",
"'__rshift__'",
")",
",",
"(",
"'__rsub__'",
",",
"'__sub__'",
")",
",",
"(",
"'__rxor__'",
",",
"'__xor__'",
")",
",",
"(",
"'__rfloordiv__'",
",",
"'__floordiv__'",
")",
",",
"(",
"'__rtruediv__'",
",",
"'__truediv__'",
")",
")",
":",
"def",
"_op",
"(",
"operand_left",
",",
"operand_right",
",",
"operation",
"=",
"_method",
")",
":",
"return",
"_MapConstantReverse",
"(",
"operand_left",
",",
"operand_right",
",",
"getattr",
"(",
"operator",
",",
"operation",
")",
")",
"setattr",
"(",
"Publisher",
",",
"method",
",",
"_op",
")",
"for",
"method",
",",
"_method",
"in",
"(",
"(",
"'__neg__'",
",",
"operator",
".",
"neg",
")",
",",
"(",
"'__pos__'",
",",
"operator",
".",
"pos",
")",
",",
"(",
"'__abs__'",
",",
"operator",
".",
"abs",
")",
",",
"(",
"'__invert__'",
",",
"operator",
".",
"invert",
")",
",",
"(",
"'__round__'",
",",
"round",
")",
",",
"(",
"'__trunc__'",
",",
"math",
".",
"trunc",
")",
",",
"(",
"'__floor__'",
",",
"math",
".",
"floor",
")",
",",
"(",
"'__ceil__'",
",",
"math",
".",
"ceil",
")",
")",
":",
"def",
"_op_unary",
"(",
"operand",
",",
"operation",
"=",
"_method",
")",
":",
"return",
"_MapUnary",
"(",
"operand",
",",
"operation",
")",
"setattr",
"(",
"Publisher",
",",
"method",
",",
"_op_unary",
")",
"def",
"_getattr",
"(",
"publisher",
",",
"attribute_name",
")",
":",
"if",
"not",
"publisher",
".",
"inherited_type",
"or",
"not",
"hasattr",
"(",
"publisher",
".",
"inherited_type",
",",
"attribute_name",
")",
":",
"raise",
"AttributeError",
"(",
"'Attribute %r not found'",
"%",
"attribute_name",
")",
"return",
"_GetAttr",
"(",
"publisher",
",",
"attribute_name",
")",
"setattr",
"(",
"Publisher",
",",
"'__getattr__'",
",",
"_getattr",
")"
] |
Function to apply operator overloading to Publisher class
|
[
"Function",
"to",
"apply",
"operator",
"overloading",
"to",
"Publisher",
"class"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/operator_overloading.py#L112-L162
|
10,488
|
semiversus/python-broqer
|
broqer/hub/hub.py
|
Topic.assign
|
def assign(self, subject):
""" Assigns the given subject to the topic """
if not isinstance(subject, (Publisher, Subscriber)):
raise TypeError('Assignee has to be Publisher or Subscriber')
# check if not already assigned
if self._subject is not None:
raise SubscriptionError('Topic %r already assigned' % self._path)
self._subject = subject
# subscribe to subject if topic has subscriptions
if self._subscriptions:
self._subject.subscribe(self)
# if topic received emits before assignment replay those emits
if self._pre_assign_emit is not None:
for value in self._pre_assign_emit:
self._subject.emit(value, who=self)
self._pre_assign_emit = None
return subject
|
python
|
def assign(self, subject):
""" Assigns the given subject to the topic """
if not isinstance(subject, (Publisher, Subscriber)):
raise TypeError('Assignee has to be Publisher or Subscriber')
# check if not already assigned
if self._subject is not None:
raise SubscriptionError('Topic %r already assigned' % self._path)
self._subject = subject
# subscribe to subject if topic has subscriptions
if self._subscriptions:
self._subject.subscribe(self)
# if topic received emits before assignment replay those emits
if self._pre_assign_emit is not None:
for value in self._pre_assign_emit:
self._subject.emit(value, who=self)
self._pre_assign_emit = None
return subject
|
[
"def",
"assign",
"(",
"self",
",",
"subject",
")",
":",
"if",
"not",
"isinstance",
"(",
"subject",
",",
"(",
"Publisher",
",",
"Subscriber",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Assignee has to be Publisher or Subscriber'",
")",
"# check if not already assigned",
"if",
"self",
".",
"_subject",
"is",
"not",
"None",
":",
"raise",
"SubscriptionError",
"(",
"'Topic %r already assigned'",
"%",
"self",
".",
"_path",
")",
"self",
".",
"_subject",
"=",
"subject",
"# subscribe to subject if topic has subscriptions",
"if",
"self",
".",
"_subscriptions",
":",
"self",
".",
"_subject",
".",
"subscribe",
"(",
"self",
")",
"# if topic received emits before assignment replay those emits",
"if",
"self",
".",
"_pre_assign_emit",
"is",
"not",
"None",
":",
"for",
"value",
"in",
"self",
".",
"_pre_assign_emit",
":",
"self",
".",
"_subject",
".",
"emit",
"(",
"value",
",",
"who",
"=",
"self",
")",
"self",
".",
"_pre_assign_emit",
"=",
"None",
"return",
"subject"
] |
Assigns the given subject to the topic
|
[
"Assigns",
"the",
"given",
"subject",
"to",
"the",
"topic"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/hub.py#L149-L170
|
10,489
|
semiversus/python-broqer
|
broqer/hub/hub.py
|
Hub.freeze
|
def freeze(self, freeze: bool = True):
""" Freezing the hub means that each topic has to be assigned and no
new topics can be created after this point.
"""
for topic in self._topics.values():
topic.freeze()
self._frozen = freeze
|
python
|
def freeze(self, freeze: bool = True):
""" Freezing the hub means that each topic has to be assigned and no
new topics can be created after this point.
"""
for topic in self._topics.values():
topic.freeze()
self._frozen = freeze
|
[
"def",
"freeze",
"(",
"self",
",",
"freeze",
":",
"bool",
"=",
"True",
")",
":",
"for",
"topic",
"in",
"self",
".",
"_topics",
".",
"values",
"(",
")",
":",
"topic",
".",
"freeze",
"(",
")",
"self",
".",
"_frozen",
"=",
"freeze"
] |
Freezing the hub means that each topic has to be assigned and no
new topics can be created after this point.
|
[
"Freezing",
"the",
"hub",
"means",
"that",
"each",
"topic",
"has",
"to",
"be",
"assigned",
"and",
"no",
"new",
"topics",
"can",
"be",
"created",
"after",
"this",
"point",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/hub.py#L247-L253
|
10,490
|
semiversus/python-broqer
|
broqer/op/throttle.py
|
Throttle.reset
|
def reset(self):
""" Reseting duration for throttling """
if self._call_later_handler is not None:
self._call_later_handler.cancel()
self._call_later_handler = None
self._wait_done_cb()
|
python
|
def reset(self):
""" Reseting duration for throttling """
if self._call_later_handler is not None:
self._call_later_handler.cancel()
self._call_later_handler = None
self._wait_done_cb()
|
[
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"_call_later_handler",
"is",
"not",
"None",
":",
"self",
".",
"_call_later_handler",
".",
"cancel",
"(",
")",
"self",
".",
"_call_later_handler",
"=",
"None",
"self",
".",
"_wait_done_cb",
"(",
")"
] |
Reseting duration for throttling
|
[
"Reseting",
"duration",
"for",
"throttling"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/throttle.py#L82-L87
|
10,491
|
semiversus/python-broqer
|
broqer/op/map_threaded.py
|
build_map_threaded
|
def build_map_threaded(function: Callable[[Any], Any] = None,
mode=MODE.CONCURRENT, unpack: bool = False):
""" Decorator to wrap a function to return a MapThreaded operator.
:param function: function to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_map_threaded(function: Callable[[Any], Any]):
@wraps(function)
def _wrapper(*args, mode=None, **kwargs) -> MapThreaded:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return MapThreaded(function, *args, mode=mode, unpack=unpack,
**kwargs)
return _wrapper
if function:
return _build_map_threaded(function)
return _build_map_threaded
|
python
|
def build_map_threaded(function: Callable[[Any], Any] = None,
mode=MODE.CONCURRENT, unpack: bool = False):
""" Decorator to wrap a function to return a MapThreaded operator.
:param function: function to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_map_threaded(function: Callable[[Any], Any]):
@wraps(function)
def _wrapper(*args, mode=None, **kwargs) -> MapThreaded:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return MapThreaded(function, *args, mode=mode, unpack=unpack,
**kwargs)
return _wrapper
if function:
return _build_map_threaded(function)
return _build_map_threaded
|
[
"def",
"build_map_threaded",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
"=",
"None",
",",
"mode",
"=",
"MODE",
".",
"CONCURRENT",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"_mode",
"=",
"mode",
"def",
"_build_map_threaded",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"mode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"MapThreaded",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"MODE",
".",
"CONCURRENT",
"if",
"_mode",
"is",
"None",
"else",
"_mode",
"return",
"MapThreaded",
"(",
"function",
",",
"*",
"args",
",",
"mode",
"=",
"mode",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_map_threaded",
"(",
"function",
")",
"return",
"_build_map_threaded"
] |
Decorator to wrap a function to return a MapThreaded operator.
:param function: function to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
|
[
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"MapThreaded",
"operator",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_threaded.py#L130-L154
|
10,492
|
semiversus/python-broqer
|
broqer/op/map_threaded.py
|
MapThreaded._thread_coro
|
async def _thread_coro(self, *args):
""" Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread """
return await self._loop.run_in_executor(
self._executor, self._function, *args)
|
python
|
async def _thread_coro(self, *args):
""" Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread """
return await self._loop.run_in_executor(
self._executor, self._function, *args)
|
[
"async",
"def",
"_thread_coro",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"await",
"self",
".",
"_loop",
".",
"run_in_executor",
"(",
"self",
".",
"_executor",
",",
"self",
".",
"_function",
",",
"*",
"args",
")"
] |
Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread
|
[
"Coroutine",
"called",
"by",
"MapAsync",
".",
"It",
"s",
"wrapping",
"the",
"call",
"of",
"run_in_executor",
"to",
"run",
"the",
"synchronous",
"function",
"as",
"thread"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_threaded.py#L123-L127
|
10,493
|
semiversus/python-broqer
|
broqer/op/debounce.py
|
Debounce.reset
|
def reset(self):
""" Reset the debounce time """
if self._retrigger_value is not NONE:
self.notify(self._retrigger_value)
self._state = self._retrigger_value
self._next_state = self._retrigger_value
if self._call_later_handler:
self._call_later_handler.cancel()
self._call_later_handler = None
|
python
|
def reset(self):
""" Reset the debounce time """
if self._retrigger_value is not NONE:
self.notify(self._retrigger_value)
self._state = self._retrigger_value
self._next_state = self._retrigger_value
if self._call_later_handler:
self._call_later_handler.cancel()
self._call_later_handler = None
|
[
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"_retrigger_value",
"is",
"not",
"NONE",
":",
"self",
".",
"notify",
"(",
"self",
".",
"_retrigger_value",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_retrigger_value",
"self",
".",
"_next_state",
"=",
"self",
".",
"_retrigger_value",
"if",
"self",
".",
"_call_later_handler",
":",
"self",
".",
"_call_later_handler",
".",
"cancel",
"(",
")",
"self",
".",
"_call_later_handler",
"=",
"None"
] |
Reset the debounce time
|
[
"Reset",
"the",
"debounce",
"time"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/debounce.py#L136-L144
|
10,494
|
semiversus/python-broqer
|
broqer/publisher.py
|
Publisher.subscribe
|
def subscribe(self, subscriber: 'Subscriber',
prepend: bool = False) -> SubscriptionDisposable:
""" Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list. When prepend is True, it will be added
in front of the list. This will habe an effect in the order the
subscribers are called.
:raises SubscriptionError: if subscriber already subscribed
"""
# `subscriber in self._subscriptions` is not working because
# tuple.__contains__ is using __eq__ which is overwritten and returns
# a new publisher - not helpful here
if any(subscriber is s for s in self._subscriptions):
raise SubscriptionError('Subscriber already registered')
if prepend:
self._subscriptions.insert(0, subscriber)
else:
self._subscriptions.append(subscriber)
return SubscriptionDisposable(self, subscriber)
|
python
|
def subscribe(self, subscriber: 'Subscriber',
prepend: bool = False) -> SubscriptionDisposable:
""" Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list. When prepend is True, it will be added
in front of the list. This will habe an effect in the order the
subscribers are called.
:raises SubscriptionError: if subscriber already subscribed
"""
# `subscriber in self._subscriptions` is not working because
# tuple.__contains__ is using __eq__ which is overwritten and returns
# a new publisher - not helpful here
if any(subscriber is s for s in self._subscriptions):
raise SubscriptionError('Subscriber already registered')
if prepend:
self._subscriptions.insert(0, subscriber)
else:
self._subscriptions.append(subscriber)
return SubscriptionDisposable(self, subscriber)
|
[
"def",
"subscribe",
"(",
"self",
",",
"subscriber",
":",
"'Subscriber'",
",",
"prepend",
":",
"bool",
"=",
"False",
")",
"->",
"SubscriptionDisposable",
":",
"# `subscriber in self._subscriptions` is not working because",
"# tuple.__contains__ is using __eq__ which is overwritten and returns",
"# a new publisher - not helpful here",
"if",
"any",
"(",
"subscriber",
"is",
"s",
"for",
"s",
"in",
"self",
".",
"_subscriptions",
")",
":",
"raise",
"SubscriptionError",
"(",
"'Subscriber already registered'",
")",
"if",
"prepend",
":",
"self",
".",
"_subscriptions",
".",
"insert",
"(",
"0",
",",
"subscriber",
")",
"else",
":",
"self",
".",
"_subscriptions",
".",
"append",
"(",
"subscriber",
")",
"return",
"SubscriptionDisposable",
"(",
"self",
",",
"subscriber",
")"
] |
Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list. When prepend is True, it will be added
in front of the list. This will habe an effect in the order the
subscribers are called.
:raises SubscriptionError: if subscriber already subscribed
|
[
"Subscribing",
"the",
"given",
"subscriber",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/publisher.py#L45-L68
|
10,495
|
semiversus/python-broqer
|
broqer/publisher.py
|
Publisher.unsubscribe
|
def unsubscribe(self, subscriber: 'Subscriber') -> None:
""" Unsubscribe the given subscriber
:param subscriber: subscriber to unsubscribe
:raises SubscriptionError: if subscriber is not subscribed (anymore)
"""
# here is a special implementation which is replacing the more
# obvious one: self._subscriptions.remove(subscriber) - this will not
# work because list.remove(x) is doing comparision for equality.
# Applied to publishers this will return another publisher instead of
# a boolean result
for i, _s in enumerate(self._subscriptions):
if _s is subscriber:
self._subscriptions.pop(i)
return
raise SubscriptionError('Subscriber is not registered')
|
python
|
def unsubscribe(self, subscriber: 'Subscriber') -> None:
""" Unsubscribe the given subscriber
:param subscriber: subscriber to unsubscribe
:raises SubscriptionError: if subscriber is not subscribed (anymore)
"""
# here is a special implementation which is replacing the more
# obvious one: self._subscriptions.remove(subscriber) - this will not
# work because list.remove(x) is doing comparision for equality.
# Applied to publishers this will return another publisher instead of
# a boolean result
for i, _s in enumerate(self._subscriptions):
if _s is subscriber:
self._subscriptions.pop(i)
return
raise SubscriptionError('Subscriber is not registered')
|
[
"def",
"unsubscribe",
"(",
"self",
",",
"subscriber",
":",
"'Subscriber'",
")",
"->",
"None",
":",
"# here is a special implementation which is replacing the more",
"# obvious one: self._subscriptions.remove(subscriber) - this will not",
"# work because list.remove(x) is doing comparision for equality.",
"# Applied to publishers this will return another publisher instead of",
"# a boolean result",
"for",
"i",
",",
"_s",
"in",
"enumerate",
"(",
"self",
".",
"_subscriptions",
")",
":",
"if",
"_s",
"is",
"subscriber",
":",
"self",
".",
"_subscriptions",
".",
"pop",
"(",
"i",
")",
"return",
"raise",
"SubscriptionError",
"(",
"'Subscriber is not registered'",
")"
] |
Unsubscribe the given subscriber
:param subscriber: subscriber to unsubscribe
:raises SubscriptionError: if subscriber is not subscribed (anymore)
|
[
"Unsubscribe",
"the",
"given",
"subscriber"
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/publisher.py#L70-L85
|
10,496
|
semiversus/python-broqer
|
broqer/publisher.py
|
Publisher.inherit_type
|
def inherit_type(self, type_cls: Type[TInherit]) \
-> Union[TInherit, 'Publisher']:
""" enables the usage of method and attribute overloading for this
publisher.
"""
self._inherited_type = type_cls
return self
|
python
|
def inherit_type(self, type_cls: Type[TInherit]) \
-> Union[TInherit, 'Publisher']:
""" enables the usage of method and attribute overloading for this
publisher.
"""
self._inherited_type = type_cls
return self
|
[
"def",
"inherit_type",
"(",
"self",
",",
"type_cls",
":",
"Type",
"[",
"TInherit",
"]",
")",
"->",
"Union",
"[",
"TInherit",
",",
"'Publisher'",
"]",
":",
"self",
".",
"_inherited_type",
"=",
"type_cls",
"return",
"self"
] |
enables the usage of method and attribute overloading for this
publisher.
|
[
"enables",
"the",
"usage",
"of",
"method",
"and",
"attribute",
"overloading",
"for",
"this",
"publisher",
"."
] |
8957110b034f982451392072d9fa16761adc9c9e
|
https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/publisher.py#L150-L156
|
10,497
|
astropy/photutils
|
photutils/extern/sigma_clipping.py
|
_move_tuple_axes_first
|
def _move_tuple_axes_first(array, axis):
"""
Bottleneck can only take integer axis, not tuple, so this function
takes all the axes to be operated on and combines them into the
first dimension of the array so that we can then use axis=0
"""
# Figure out how many axes we are operating over
naxis = len(axis)
# Add remaining axes to the axis tuple
axis += tuple(i for i in range(array.ndim) if i not in axis)
# The new position of each axis is just in order
destination = tuple(range(array.ndim))
# Reorder the array so that the axes being operated on are at the beginning
array_new = np.moveaxis(array, axis, destination)
# Figure out the size of the product of the dimensions being operated on
first = np.prod(array_new.shape[:naxis])
# Collapse the dimensions being operated on into a single dimension so that
# we can then use axis=0 with the bottleneck functions
array_new = array_new.reshape((first,) + array_new.shape[naxis:])
return array_new
|
python
|
def _move_tuple_axes_first(array, axis):
"""
Bottleneck can only take integer axis, not tuple, so this function
takes all the axes to be operated on and combines them into the
first dimension of the array so that we can then use axis=0
"""
# Figure out how many axes we are operating over
naxis = len(axis)
# Add remaining axes to the axis tuple
axis += tuple(i for i in range(array.ndim) if i not in axis)
# The new position of each axis is just in order
destination = tuple(range(array.ndim))
# Reorder the array so that the axes being operated on are at the beginning
array_new = np.moveaxis(array, axis, destination)
# Figure out the size of the product of the dimensions being operated on
first = np.prod(array_new.shape[:naxis])
# Collapse the dimensions being operated on into a single dimension so that
# we can then use axis=0 with the bottleneck functions
array_new = array_new.reshape((first,) + array_new.shape[naxis:])
return array_new
|
[
"def",
"_move_tuple_axes_first",
"(",
"array",
",",
"axis",
")",
":",
"# Figure out how many axes we are operating over",
"naxis",
"=",
"len",
"(",
"axis",
")",
"# Add remaining axes to the axis tuple",
"axis",
"+=",
"tuple",
"(",
"i",
"for",
"i",
"in",
"range",
"(",
"array",
".",
"ndim",
")",
"if",
"i",
"not",
"in",
"axis",
")",
"# The new position of each axis is just in order",
"destination",
"=",
"tuple",
"(",
"range",
"(",
"array",
".",
"ndim",
")",
")",
"# Reorder the array so that the axes being operated on are at the beginning",
"array_new",
"=",
"np",
".",
"moveaxis",
"(",
"array",
",",
"axis",
",",
"destination",
")",
"# Figure out the size of the product of the dimensions being operated on",
"first",
"=",
"np",
".",
"prod",
"(",
"array_new",
".",
"shape",
"[",
":",
"naxis",
"]",
")",
"# Collapse the dimensions being operated on into a single dimension so that",
"# we can then use axis=0 with the bottleneck functions",
"array_new",
"=",
"array_new",
".",
"reshape",
"(",
"(",
"first",
",",
")",
"+",
"array_new",
".",
"shape",
"[",
"naxis",
":",
"]",
")",
"return",
"array_new"
] |
Bottleneck can only take integer axis, not tuple, so this function
takes all the axes to be operated on and combines them into the
first dimension of the array so that we can then use axis=0
|
[
"Bottleneck",
"can",
"only",
"take",
"integer",
"axis",
"not",
"tuple",
"so",
"this",
"function",
"takes",
"all",
"the",
"axes",
"to",
"be",
"operated",
"on",
"and",
"combines",
"them",
"into",
"the",
"first",
"dimension",
"of",
"the",
"array",
"so",
"that",
"we",
"can",
"then",
"use",
"axis",
"=",
"0"
] |
cc9bb4534ab76bac98cb5f374a348a2573d10401
|
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L22-L48
|
10,498
|
astropy/photutils
|
photutils/extern/sigma_clipping.py
|
_nanmean
|
def _nanmean(array, axis=None):
"""Bottleneck nanmean function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanmean(array, axis=axis)
|
python
|
def _nanmean(array, axis=None):
"""Bottleneck nanmean function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanmean(array, axis=axis)
|
[
"def",
"_nanmean",
"(",
"array",
",",
"axis",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"axis",
",",
"tuple",
")",
":",
"array",
"=",
"_move_tuple_axes_first",
"(",
"array",
",",
"axis",
"=",
"axis",
")",
"axis",
"=",
"0",
"return",
"bottleneck",
".",
"nanmean",
"(",
"array",
",",
"axis",
"=",
"axis",
")"
] |
Bottleneck nanmean function that handle tuple axis.
|
[
"Bottleneck",
"nanmean",
"function",
"that",
"handle",
"tuple",
"axis",
"."
] |
cc9bb4534ab76bac98cb5f374a348a2573d10401
|
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L51-L57
|
10,499
|
astropy/photutils
|
photutils/extern/sigma_clipping.py
|
_nanmedian
|
def _nanmedian(array, axis=None):
"""Bottleneck nanmedian function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanmedian(array, axis=axis)
|
python
|
def _nanmedian(array, axis=None):
"""Bottleneck nanmedian function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanmedian(array, axis=axis)
|
[
"def",
"_nanmedian",
"(",
"array",
",",
"axis",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"axis",
",",
"tuple",
")",
":",
"array",
"=",
"_move_tuple_axes_first",
"(",
"array",
",",
"axis",
"=",
"axis",
")",
"axis",
"=",
"0",
"return",
"bottleneck",
".",
"nanmedian",
"(",
"array",
",",
"axis",
"=",
"axis",
")"
] |
Bottleneck nanmedian function that handle tuple axis.
|
[
"Bottleneck",
"nanmedian",
"function",
"that",
"handle",
"tuple",
"axis",
"."
] |
cc9bb4534ab76bac98cb5f374a348a2573d10401
|
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L60-L66
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.