Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _set_available_styles(self):
options_tagstyle = {'keys': ['param', 'type', 'returns', 'return', 'rtype', 'raise'],
'styles': {'javadoc': ('@', ':'), # tuple: key prefix, separator
'reST... | [
"Set the internal styles list and available options in a structure as following:\n\n param: javadoc: name = '@param'\n sep = ':'\n reST: name = ':param'\n sep = ':'\n ...\n type: javadoc: name = '@t... |
Please provide a description of the function: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'])
f... | [
"Determine the style of a docstring,\n and sets it as the default input one for the instance.\n\n :param data: the docstring's data to recognize.\n :type data: str\n :returns: the style detected else 'unknown'\n :rtype: str\n\n "
] |
Please provide a description of the function: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\n\n :param style: the style that the keywords are wanted\n\n "
] |
Please provide a description of the function:def get_key(self, key, target='in'):
target = 'out' if target == 'out' else 'in'
return self.opt[key][self.style[target]]['name'] | [
"Get the name of a key in current style.\n e.g.: in javadoc style, the returned key for 'param' is '@param'\n\n :param key: the key wanted (param, type, return, rtype,..)\n :param target: the target docstring is 'in' for the input or\n 'out' for the output to generate. (Default value =... |
Please provide a description of the function:def get_sep(self, key='param', target='in'):
target = 'out' if target == 'out' else 'in'
if self.style[target] in ['numpydoc', 'google']:
return ''
return self.opt[key][self.style[target]]['sep'] | [
"Get the separator of current style.\n e.g.: in reST and javadoc style, it is \":\"\n\n :param key: the key which separator is wanted (param, type, return, rtype,..) (Default value = 'param')\n :param target: the target docstring is 'in' for the input or\n 'out' for the output to gener... |
Please provide a description of the function: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.\n\n :param data: string to parse\n :param key: the key category\n :returns: the found line number else -1\n\n "
] |
Please provide a description of the function: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\n\n :param data: string to parse\n :param key: the key category\n :returns: the index if found else -1\n\n "
] |
Please provide a description of the function: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.\n\n :param data: the data to proceed\n :returns: the line number\n\n "
] |
Please provide a description of the function: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\n\n :param data: string to parse\n :returns: the index if found else -1\n\n "
] |
Please provide a description of the function: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
lo... | [
"Get from a docstring the next option with a given key.\n\n :param data: string to parse\n :param starting: does the key element must start the line (Default value = True)\n :type starting: boolean\n :param key: the key category. Can be 'param', 'type', 'return', ...\n :returns: i... |
Please provide a description of the function:def get_elem_index(self, data, starting=True):
idx = len(data)
for opt in self.opt.keys():
i = self.get_key_index(data, opt, starting)
if i < idx and i != -1:
idx = i
if idx == len(data):
id... | [
"Get from a docstring the next option.\n In javadoc style it could be @param, @return, @type,...\n\n :param data: string to parse\n :param starting: does the key element must start the line (Default value = True)\n :type starting: boolean\n :returns: index of found element else -1... |
Please provide a description of the function:def get_raise_indexes(self, data):
start, end = -1, -1
stl_param = self.opt['raise'][self.style['in']]['name']
if self.style['in'] in self.tagstyles + ['unknown']:
idx_p = self.get_key_index(data, 'raise')
if idx_p >= ... | [
"Get from a docstring the next raise name indexes.\n In javadoc style it is after @raise.\n\n :param data: string to parse\n :returns: start and end indexes of found element else (-1, -1)\n or else (-2, -2) if try to use params style but no parameters were provided.\n Note: th... |
Please provide a description of the function:def get_raise_description_indexes(self, data, prev=None):
start, end = -1, -1
if not prev:
_, prev = self.get_raise_indexes(data)
if prev < 0:
return -1, -1
m = re.match(r'\W*(\w+)', data[prev:])
if m:
... | [
"Get from a docstring the next raise's description.\n In javadoc style it is after @param.\n\n :param data: string to parse\n :param prev: index after the param element name (Default value = None)\n :returns: start and end indexes of found element else (-1, -1)\n :rtype: tuple\n\n... |
Please provide a description of the function:def get_param_indexes(self, data):
# TODO: new method to extract an element's name so will be available for @param and @types and other styles (:param, \param)
start, end = -1, -1
stl_param = self.opt['param'][self.style['in']]['name']
... | [
"Get from a docstring the next parameter name indexes.\n In javadoc style it is after @param.\n\n :param data: string to parse\n :returns: start and end indexes of found element else (-1, -1)\n or else (-2, -2) if try to use params style but no parameters were provided.\n Note... |
Please provide a description of the function:def get_param_type_indexes(self, data, name=None, prev=None):
start, end = -1, -1
stl_type = self.opt['type'][self.style['in']]['name']
if not prev:
_, prev = self.get_param_description_indexes(data)
if prev >= 0:
... | [
"Get from a docstring a parameter type indexes.\n In javadoc style it is after @type.\n\n :param data: string to parse\n :param name: the name of the parameter (Default value = None)\n :param prev: index after the previous element (param or param's description) (Default value = None)\n ... |
Please provide a description of the function:def get_return_description_indexes(self, data):
start, end = -1, -1
stl_return = self.opt['return'][self.style['in']]['name']
if self.style['in'] in self.tagstyles + ['unknown']:
idx = self.get_key_index(data, 'return')
... | [
"Get from a docstring the return parameter description indexes.\n In javadoc style it is after @return.\n\n :param data: string to parse\n :returns: start and end indexes of found element else (-1, -1)\n Note: the end index is the index after the last included character or -1 if\n ... |
Please provide a description of the function:def get_return_type_indexes(self, data):
start, end = -1, -1
stl_rtype = self.opt['rtype'][self.style['in']]['name']
if self.style['in'] in self.tagstyles + ['unknown']:
dstart, dend = self.get_return_description_indexes(data)
... | [
"Get from a docstring the return parameter type indexes.\n In javadoc style it is after @rtype.\n\n :param data: string to parse\n :returns: start and end indexes of found element else (-1, -1)\n Note: the end index is the index after the last included character or -1 if\n rea... |
Please provide a description of the function:def parse_element(self, raw=None):
# TODO: retrieve return from element external code (in parameter)
if raw is None:
l = self.element['raw'].strip()
else:
l = raw.strip()
is_class = False
if l.startswit... | [
"Parses the element's elements (type, name and parameters) :)\n e.g.: def methode(param1, param2='default')\n def -> type\n methode -> name\n param1, param2='default' -> parameters\n\n :param raw: raw data of the element (def or class). (Defau... |
Please provide a description of the function: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':
... | [
"Extract main description from docstring"
] |
Please provide a description of the function: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 =... | [
"Extract group style parameters"
] |
Please provide a description of the function:def _extract_docs_params(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']['params'] += self.dst.numpyd... | [
"Extract parameters description and type from docstring. The internal computed parameters list is\n composed by tuples (parameter, description, type).\n\n "
] |
Please provide a description of the function:def _extract_docs_raises(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']['raises'] += self.dst.numpyd... | [
"Extract raises description from docstring. The internal computed raises list is\n composed by tuples (raise, description).\n\n "
] |
Please provide a description of the function: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.numpydo... | [
"Extract return description and type"
] |
Please provide a description of the function: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, 'a... | [
"Extract other specific sections"
] |
Please provide a description of the function:def parse_docs(self, raw=None):
if raw is not None:
raw = raw.strip()
if raw.startswith('') or raw.endswith("'''"):
raw = raw[:-3]
self.docs['in']['raw'] = raw
self.dst.autodetect_style(raw)
... | [
"Parses the docstring\n\n :param raw: the data to parse if not internally provided (Default value = None)\n\n ",
"') or raw.startswith(\"'''\"):\n raw = raw[3:]\n if raw.endswith('"
] |
Please provide a description of the function: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"
] |
Please provide a description of the function: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 ... | [
"Sets the parameters with types, descriptions and default value if any"
] |
Please provide a description of the function: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 \... | [
"Sets the raises and descriptions"
] |
Please provide a description of the function: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']:
... | [
"Sets the return parameter with description and rtype if any"
] |
Please provide a description of the function: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... | [
"Sets other specific sections"
] |
Please provide a description of the function:def _set_raw_params(self, sep):
raw = '\n'
if self.dst.style['out'] == 'numpydoc':
spaces = ' ' * 4
with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + spaces +\
l... | [
"Set the output raw parameters section\n\n :param sep: the separator of current style\n\n "
] |
Please provide a description of the function:def _set_raw_raise(self, sep):
raw = ''
if self.dst.style['out'] == 'numpydoc':
if 'raise' not in self.dst.numpydoc.get_excluded_sections():
raw += '\n'
if 'raise' in self.dst.numpydoc.get_mandatory_section... | [
"Set the output raw exception section\n\n :param sep: the separator of current style\n\n "
] |
Please provide a description of the function:def _set_raw_return(self, sep):
raw = ''
if self.dst.style['out'] == 'numpydoc':
raw += '\n'
spaces = ' ' * 4
with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + spaces + l.lstrip() if i > 0 else l for i... | [
"Set the output raw return section\n\n :param sep: the separator of current style\n\n "
] |
Please provide a description of the function: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 descr... | [
"Sets the output raw docstring"
] |
Please provide a description of the function: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()
se... | [
"Generates the output docstring"
] |
Please provide a description of the function: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.isd... | [
"Retrieve the list of files from a folder.\n\n @param path: file or directory where to search files\n @param recursive: if True will search also sub-directories\n @param depth: if explore recursively, the depth of sub directories to follow\n @param file_ext: the files extension to get. Default is '.py'\... |
Please provide a description of the function: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_... | [
"Get the configuration from a file.\n\n @param config_file: the configuration file\n @return: the configuration\n @rtype: dict\n\n "
] |
Please provide a description of the function:def _parse(self):
#TODO manage decorators
#TODO manage default params with strings escaping chars as (, ), ', ', #, ...
#TODO manage elements ending with comments like: def func(param): # blabla
elem_list = []
reading_element ... | [
"Parses the input file's content and generates a list of its elements/docstrings.\n\n :returns: the list of elements\n\n ",
"' in l or \"'''\" in l):\n # start of docstring bloc\n if not reading_docs:\n start = i\n #... |
Please provide a description of the function:def docs_init_to_class(self):
result = False
if not self.parsed:
self._parse()
einit = []
eclass = []
for e in self.docs_list:
if len(eclass) == len(einit) + 1 and e['docs'].element['name'] == '__init__... | [
"If found a __init__ method's docstring and the class\n without any docstring, so set the class docstring with __init__one,\n and let __init__ without docstring.\n\n :returns: True if done\n :rtype: boolean\n\n "
] |
Please provide a description of the function: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\n\n :returns: the formatted docstrings\n :rtype: list\n\n "
] |
Please provide a description of the function: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:
... | [
"Compute the list of lines before and after the proposed docstring changes.\n\n :return: tuple of before,after where each is a list of lines of python code.\n "
] |
Please provide a description of the function: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):
... | [
"Build the diff between original docstring and proposed docstring.\n\n :type which: int\n -> -1 means all the dosctrings of the file\n -> >=0 means the index of the docstring to proceed (Default value = -1)\n :param source_path: (Default value = '')\n :param target_path: (De... |
Please provide a description of the function: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\n\n :param source_path: name of the original file (Default value = '')\n :param target_path: name of the final file (Default value = '')\n\n :return: the diff as a list of \\n terminated lines\n :rtype: List[str]\n "
] |
Please provide a description of the function: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\n\n :param patch_file: file name of the patch to generate\n :param lines_to_write: lines to write to the file - they should be \\n terminated\n :type lines_to_write: list[str]\n\n :return: None\n "
] |
Please provide a description of the function: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
... | [
"overwrite the file with line_to_write\n\n :param lines_to_write: lines to write to the file - they should be \\n terminated\n :type lines_to_write: List[str]\n\n :return: None\n "
] |
Please provide a description of the function:def _windows_rename(self, tmp_filename):
os.remove(self.input_file) if os.path.isfile(self.input_file) else None
os.rename(tmp_filename, self.input_file) | [
" Workaround the fact that os.rename raises an OSError on Windows\n \n :param tmp_filename: The file to rename\n \n "
] |
Please provide a description of the function:def proceed(self):
self._parse()
for e in self.docs_list:
e['docs'].generate_docs()
return self.docs_list | [
"Parses the input file and generates/converts the docstrings.\n\n :return: the list of docstrings\n :rtype: list of dictionaries\n\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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,... | [
"Gets the frozen statistics to serialize by Pickle."
] |
Please provide a description of the function: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\n\n :param dump_filename: path to a file\n :type dump_filename: str\n\n :param pickle_protocol: version of pickle protocol\n :type pickle_protocol: int\n "
] |
Please provide a description of the function: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)
vie... | [
"Makes a statistics viewer from the profiling result.\n "
] |
Please provide a description of the function:def run_viewer(self, title=None, at=None, mono=False,
*loop_args, **loop_kwargs):
viewer = self.make_viewer(title, at=at)
loop = viewer.loop(*loop_args, **loop_kwargs)
if mono:
loop.screen.set_terminal_propertie... | [
"A shorter form of:\n\n ::\n\n viewer = profiler.make_viewer()\n loop = viewer.loop()\n loop.run()\n\n "
] |
Please provide a description of the function: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.getval... | [
"Packs a method and message."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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, ... | [
"Receives a method and message from the socket. This function blocks the\n current thread.\n "
] |
Please provide a description of the function:def profiling(self):
self._log_profiler_started()
while self.clients:
try:
self.profiler.start()
except RuntimeError:
pass
# should sleep.
yield
self.profiler... | [
"A generator which profiles then broadcasts the result. Implement\n sleeping loop using this::\n\n def profile_periodically(self):\n for __ in self.profiling():\n time.sleep(self.interval)\n\n "
] |
Please provide a description of the function: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)
profil... | [
"Call this method when a client connected."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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\n statistics object.\n "
] |
Please provide a description of the function: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.... | [
"Finds a node by the given path from the given node."
] |
Please provide a description of the function:def update_result(self):
try:
if self.paused:
result = self._paused_result
else:
result = self._final_result
except AttributeError:
self.table.update_frame()
return
... | [
"Updates the result on the table."
] |
Please provide a description of the function:def option_getter(type):
option_getters = {None: ConfigParser.get,
int: ConfigParser.getint,
float: ConfigParser.getfloat,
bool: ConfigParser.getboolean}
return option_getters.get(type, option_get... | [
"Gets an unbound method to get a configuration option as the given type.\n "
] |
Please provide a description of the function: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.
... | [
"Guesses a default value of a CLI option from the configuration.\n\n ::\n\n @click.option('--locale', default=config_default('locale'))\n\n "
] |
Please provide a description of the function: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... | [
"Guesses whether a CLI flag should be turned on or off from the\n configuration. If the configuration option value is same with the given\n value, it returns ``True``.\n\n ::\n\n @click.option('--ko-kr', 'locale', is_flag=True,\n default=config_flag('locale', 'ko_KR'))\n\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def make_viewer(mono=False, *loop_args, **loop_kwargs):
viewer = StatisticsViewer()
loop = viewer.loop(*loop_args, **loop_kwargs)
if mono:
loop.screen.set_terminal_properties(1)
return (viewer, loop) | [
"Makes a :class:`profiling.viewer.StatisticsViewer` with common options.\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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 ... | [
"Spawns a thread-like object which runs the given function concurrently.\n\n Available modes:\n\n - `threading`\n - `greenlet`\n - `eventlet`\n\n "
] |
Please provide a description of the function:def import_(module_name, name):
module = importlib.import_module(module_name, __package__)
return getattr(module, name) | [
"Imports an object by a relative module path::\n\n Profiler = import_('profiling.profiler', 'Profiler')\n\n "
] |
Please provide a description of the function: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=pic... | [
"Profile a Python script."
] |
Please provide a description of the function: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... | [
"Profile a Python script continuously."
] |
Please provide a description of the function:def remote_profile(script, argv, profiler_factory, interval, spawn, signum,
pickle_protocol, endpoint, verbose):
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
# create listener.
listener = socket.socket(socket... | [
"Launch a server to profile continuously. The default endpoint is\n 127.0.0.1:8912.\n "
] |
Please provide a description of the function: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:
... | [
"Inspect statistics by TUI view."
] |
Please provide a description of the function: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 ... | [
"Profile a Python statement like timeit."
] |
Please provide a description of the function:def command(self, *args, **kwargs):
aliases = kwargs.pop('aliases', None)
decorator = super(ProfilingCLI, self).command(*args, **kwargs)
if aliases is None:
return decorator
def _decorator(f):
cmd = decorator(f... | [
"Usage::\n\n @cli.command(aliases=['ci'])\n def commit():\n ...\n\n "
] |
Please provide a description of the function:def collect_usage_pieces(self, ctx):
pieces = super(ProfilingCommand, self).collect_usage_pieces(ctx)
assert pieces[-1] == '[ARGV]...'
pieces.insert(-1, 'SCRIPT')
pieces.insert(-1, '[--]')
return pieces | [
"Prepend \"[--]\" before \"[ARGV]...\"."
] |
Please provide a description of the function: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
e... | [
"Iterates all descendant statistics under the given root statistics.\n\n When ``spreader=True``, each iteration yields a descendant statistics and\n `spread()` function together. You should call `spread()` if you want to\n spread the yielded statistics also.\n\n "
] |
Please provide a description of the function:def make_frozen_stats_tree(stats):
tree, stats_tree = [], [(None, stats)]
for x in itertools.count():
try:
parent_offset, _stats = stats_tree[x]
except IndexError:
break
stats_tree.extend((x, s) for s in _stats)
... | [
"Makes a flat members tree of the given statistics. The statistics can\n be restored by :func:`frozen_stats_from_tree`.\n "
] |
Please provide a description of the function:def frozen_stats_from_tree(tree):
if not tree:
raise ValueError('Empty tree')
stats_index = []
for parent_offset, members in tree:
stats = FrozenStatistics(*members)
stats_index.append(stats)
if parent_offset is not None:
... | [
"Restores a statistics from the given flat members tree.\n :func:`make_frozen_stats_tree` makes a tree for this function.\n "
] |
Please provide a description of the function:def deep_hits(self):
hits = [self.own_hits]
hits.extend(stats.own_hits for stats in spread_stats(self))
return sum(hits) | [
"The inclusive calling/sampling number.\n\n Calculates as sum of the own hits and deep hits of the children.\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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... | [
"Makes a flat statistics from the given statistics."
] |
Please provide a description of the function:def requirements(filename):
with open(filename) as f:
return [x.strip() for x in f.readlines() if x.strip()] | [
"Reads requirements from a file."
] |
Please provide a description of the function: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... | [
"Samples the given frame."
] |
Please provide a description of the function: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.\n\n ::\n\n with deferral() as defer:\n sys.setprofile(f)\n defer(sys.setprofile, None)\n # do something.\n\n "
] |
Please provide a description of the function: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... | [
"Starts the instance.\n\n :raises RuntimeError: has been already started.\n :raises TypeError: :meth:`run` is not canonical.\n\n "
] |
Please provide a description of the function: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
... | [
"Stops the instance.\n\n :raises RuntimeError: has not been started.\n :raises TypeError: :meth:`run` is not canonical.\n\n "
] |
Please provide a description of the function:def sockets(self):
if self.listener is None:
return self.clients
else:
return self.clients.union([self.listener]) | [
"Returns the set of the sockets."
] |
Please provide a description of the function: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:
# t... | [
"EINTR safe version of `select`. It focuses on just incoming\n sockets.\n "
] |
Please provide a description of the function: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)
... | [
"Dispatches incoming sockets."
] |
Please provide a description of the function:def _profile(self, frame, event, arg):
# c = event.startswith('c_')
if event.startswith('c_'):
return
time1 = self.timer()
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats =... | [
"The callback function to register by :func:`sys.setprofile`."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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... | [
"Left from a function call."
] |
Please provide a description of the function: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:
r... | [
" Decorator to wrap a function to return a Sink subscriber.\n\n :param function: function to be wrapped\n :param unpack: value from emits will be unpacked (*value)\n "
] |
Please provide a description of the function: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 ... | [
" Decorator to wrap a function to return a Map operator.\n\n :param function: function to be wrapped\n :param unpack: value from emits will be unpacked (*value)\n "
] |
Please provide a description of the function: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\n and the emitted value\n "
] |
Please provide a description of the function: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... | [
" Decorator to wrap a coroutine to return a SinkAsync subscriber.\n\n :param coro: coroutine to be wrapped\n :param mode: behavior when a value is currently processed\n :param unpack: value from emits will be unpacked (*value)\n "
] |
Please provide a description of the function: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)... | [
" Decorator to wrap a function to return an Accumulate operator.\n\n :param function: function to be wrapped\n :param init: optional initialization for state\n "
] |
Please provide a description of the function: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' % top... | [
" Resolve a value when it's a string and starts with '>' "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.