desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Search the ExploitDB archive.
Arguments:
query -- Search terms
Optional arguments:
author -- Name of the exploit submitter
platform -- Target platform (e.g. windows, linux, hardware etc.)
port -- Service port number
type -- Any, dos, local, papers, remote, shellcode and webapps
Returns:
A dictionary ... | def search(self, query, **kwargs):
| return self.parent._request('exploitdb/search', dict(q=query, **kwargs))
|
'Download a metasploit module given the fullname (id) of it.
Arguments:
id -- fullname of the module (ex. auxiliary/admin/backupexec/dump)
Returns:
A dictionary with the following fields:
filename -- Name of the file
content-type -- Mimetype
data -- File content'
| def download(self, id):
| return self.parent._request('msf/download', {'id': id})
|
'Search for a Metasploit module.'
| def search(self, query, **kwargs):
| return self.parent._request('msf/search', dict(q=query, **kwargs))
|
'Initializes the API object.
Arguments:
key -- your API key'
| def __init__(self, key):
| self.api_key = key
self.base_url = 'http://www.shodanhq.com/api/'
self.dataloss = self.DatalossDb(self)
self.exploits = self.Exploits(self)
self.exploitdb = self.ExploitDb(self)
self.msf = self.Msf(self)
|
'General-purpose function to create web requests to SHODAN.
Arguments:
function -- name of the function you want to execute
params -- dictionary of parameters for the function
Returns
A JSON string containing the function\'s results.'
| def _request(self, function, params):
| params['key'] = self.api_key
data = urlopen((((self.base_url + function) + '?') + urlencode(params))).read()
data = loads(data)
if data.get('error', None):
raise WebAPIError(data['error'])
return data
|
'Determine the software based on the banner.
Arguments:
banner - HTTP banner
Returns:
A list of software that matched the given banner.'
| def fingerprint(self, banner):
| return self._request('fingerprint', {'banner': banner})
|
'Get all available information on an IP.
Arguments:
ip -- IP of the computer
Returns:
All available information SHODAN has on the given IP,
subject to API key restrictions.'
| def host(self, ip):
| return self._request('host', {'ip': ip})
|
'Search the SHODAN database.
Arguments:
query -- search query; identical syntax to the website
Returns:
A dictionary with 3 main items: matches, countries and total.
Visit the website for more detailed information.'
| def search(self, query):
| return self._request('search', {'q': query})
|
'set graph styles'
| def set_styles(self):
| if self.graphBGColor:
self.__cssGRAPH += (('background-color:' + self.graphBGColor) + ';')
if self.graphBorder:
self.__cssGRAPH += (('border:' + self.graphBorder) + ';')
if self.barBorder:
self.__cssBAR += (('border:' + self.barBorder) + ';')
if self.barBGColor:
self.__cs... |
'return bar color for each level'
| def level_color(self, value, color):
| if self.barLevelColors:
for i in range(0, len(self.barLevelColors), 2):
try:
if (((self.barLevelColors[i] > 0) and (value >= self.barLevelColors[i])) or ((self.barLevelColors[i] < 0) and (value <= self.barLevelColors[i]))):
color = self.barLevelColors[(i + 1)]... |
'return a single bar'
| def build_bar(self, value, width, height, color):
| title = ((self.absValuesPrefix + str(value)) + self.absValuesSuffix)
bg = ((self.__img_pattern.search(color) and 'background') or 'bgcolor')
bar = '<table border=0 cellspacing=0 cellpadding=0><tr>'
bar += (((((('<td style="' + self.__cssBAR) + '" ') + bg) + '="') + color) + '"')
bar +... |
'return a single fader'
| def build_fader(self, value, width, height, x, color):
| fader = '<table border=0 cellspacing=0 cellpadding=0><tr>'
x -= int(round((width / 2)))
if (x > 0):
fader += (('<td width=' + str(x)) + '></td>')
fader += (('<td>' + self.build_bar(value, width, height, color)) + '</td>')
fader += '</tr></table>'
return fader
|
'return a single bar/fader value'
| def build_value(self, val, max_dec, sum=0, align=''):
| val = _number_format(val, max_dec)
if sum:
sum = _number_format(sum, max_dec)
value = (('<td style="' + self.__cssABSVALUES) + '"')
if align:
value += (' align=' + align)
value += ' nowrap>'
value += (((' ' + self.absValuesPrefix) + str(val)) + self.absValuesSuffix)... |
'return the legend'
| def build_legend(self, barColors):
| if hasattr(self.legend, 'split'):
self.legend = self.legend.split(',')
legend = '<table border=0 cellspacing=0 cellpadding=0><tr>'
legend += (('<td style="' + self.__cssLEGENDBG) + '">')
legend += '<table border=0 cellspacing=4 cellpadding=0>'
i = 0
for color in barC... |
'return horizontal titles'
| def build_hTitle(self, titleLabel, titleValue, titleBar):
| title = '<tr>'
title += (((('<td style="' + self.__cssTITLE) + '">') + titleLabel) + '</td>')
if (titleValue != ''):
title += (((('<td style="' + self.__cssTITLE) + '">') + titleValue) + '</td>')
title += (((('<td style="' + self.__cssTITLE) + '">') + titleBar) + '</td>')
title += '... |
'return a single horizontal bar with label and values (abs./perc.)'
| def create_hBar(self, value, percent, mPerc, mPerc_neg, max_neg, mul, valSpace, bColor, border, spacer, spacer_neg):
| bar = '<table border=0 cellspacing=0 cellpadding=0 height=100%><tr>'
if (percent < 0):
percent *= (-1)
bar += (((((('<td style="' + self.__cssLABELBG) + '" height=') + str(self.barWidth)) + ' width=') + str(int(round((((mPerc_neg - percent) * mul) + valSpace))))) + ' alig... |
'return a single vertical bar with label and values (abs./perc.)'
| def create_vBar(self, value, percent, mPerc, mPerc_neg, max_neg, mul, valSpace, bColor, border, spacer, spacer_neg):
| bar = '<table border=0 cellspacing=0 cellpadding=0 width=100%><tr align=center>'
if (percent < 0):
percent *= (-1)
bar += (((('<td height=' + str(spacer)) + '></td></tr><tr align=center valign=top><td style="') + self.__cssLABELBG) + '">')
bar += self.build_bar... |
'create a complete bar graph (horizontal, vertical, progress, or fader)'
| def create(self):
| self.type = self.type.lower()
d = self.values
t = ((hasattr(self.titles, 'split') and self.titles.split(',')) or self.titles)
r = ((hasattr(self.labels, 'split') and self.labels.split(',')) or self.labels)
drc = ((hasattr(self.barColors, 'split') and self.barColors.split(',')) or self.barColors)
... |
'Append the actual tags to content.'
| def render(self, tag, single, between, kwargs):
| out = ('<%s' % tag)
for (key, value) in kwargs.iteritems():
if (value is not None):
key = key.strip('_')
if (key == 'http_equiv'):
key = 'http-equiv'
elif (key == 'accept_charset'):
key = 'accept-charset'
out = ('%s %s="%... |
'Append a closing tag unless element has only opening tag.'
| def close(self):
| if (self.tag in self.parent.twotags):
self.parent.content.append(('</%s>' % self.tag))
elif (self.tag in self.parent.onetags):
raise ClosingError(self.tag)
elif ((self.parent.mode == 'strict_html') and (self.tag in self.parent.deptags)):
raise DeprecationError(self.tag)
|
'Append an opening tag.'
| def open(self, **kwargs):
| if ((self.tag in self.parent.twotags) or (self.tag in self.parent.onetags)):
self.render(self.tag, False, None, kwargs)
elif ((self.mode == 'strict_html') and (self.tag in self.parent.deptags)):
raise DeprecationError(self.tag)
|
'Stuff that effects the whole document.
mode -- \'strict_html\' for HTML 4.01 (default)
\'html\' alias for \'strict_html\'
\'loose_html\' to allow some deprecated elements
\'xml\' to allow arbitrary elements
case -- \'lower\' element names will be printed in lower case (default)
\'upper\... | def __init__(self, mode='strict_html', case='lower', onetags=None, twotags=None, separator='\n', class_=None):
| valid_onetags = ['AREA', 'BASE', 'BR', 'COL', 'FRAME', 'HR', 'IMG', 'INPUT', 'LINK', 'META', 'PARAM']
valid_twotags = ['A', 'ABBR', 'ACRONYM', 'ADDRESS', 'B', 'BDO', 'BIG', 'BLOCKQUOTE', 'BODY', 'BUTTON', 'CAPTION', 'CITE', 'CODE', 'COLGROUP', 'DD', 'DEL', 'DFN', 'DIV', 'DL', 'DT', 'EM', 'FIELDSET', 'FORM', 'FR... |
'Return the document as a string.
escape -- False print normally
True replace < and > by < and >
the default escape sequences in most browsers'
| def __call__(self, escape=False):
| if escape:
return _escape(self.__str__())
else:
return self.__str__()
|
'This is an alias to addcontent.'
| def add(self, text):
| self.addcontent(text)
|
'Add some text to the bottom of the document'
| def addfooter(self, text):
| self.footer.append(text)
|
'Add some text to the top of the document'
| def addheader(self, text):
| self.header.append(text)
|
'Add some text to the main part of the document'
| def addcontent(self, text):
| self.content.append(text)
|
'This method is used for complete documents with appropriate
doctype, encoding, title, etc information. For an HTML/XML snippet
omit this method.
lang -- language, usually a two character string, will appear
as <html lang=\'en\'> in html mode (ignored in xml mode)
css -- Cascading Style Sheet filename as a str... | def init(self, lang='en', css=None, metainfo=None, title=None, header=None, footer=None, charset=None, encoding=None, doctype=None, bodyattrs=None, script=None):
| self._full = True
if ((self.mode == 'strict_html') or (self.mode == 'loose_html')):
if (doctype is None):
doctype = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"
self.header.append(doctype)
self.html(lang=lang)
self.head()
... |
'This convenience function is only useful for html.
It adds css stylesheet(s) to the document via the <link> element.'
| def css(self, filelist):
| if isinstance(filelist, basestring):
self.link(href=filelist, rel='stylesheet', type='text/css', media='all')
else:
for file in filelist:
self.link(href=file, rel='stylesheet', type='text/css', media='all')
|
'This convenience function is only useful for html.
It adds meta information via the <meta> element, the argument is
a dictionary of the form { \'name\':\'content\' }.'
| def metainfo(self, mydict):
| if isinstance(mydict, dict):
for (name, content) in mydict.iteritems():
self.meta(name=name, content=content)
else:
raise TypeError('Metainfo should be called with a dictionary argument of name:content pairs.')
|
'Only useful in html, mydict is dictionary of src:type pairs will
be rendered as <script type=\'text/type\' src=src></script>'
| def scripts(self, mydict):
| if isinstance(mydict, dict):
for (src, type) in mydict.iteritems():
self.script('', src=src, type=('text/%s' % type))
else:
raise TypeError('Script should be given a dictionary of src:type pairs.')
|
'Describe additional keys that may be present in given JSON value
If called with some keyword arguments implies that described value is
a dictionary. If called without keyword parameters it is no-op.
:return: self.'
| def update(self, **keys):
| for (k, v) in keys.items():
self.keys[k] = len(self.specs)
self.specs.append(v)
if (self.keys and (not self.did_type)):
self.type(dict)
self.did_type = True
return self
|
'Deep copy the spec
:param dict copied:
Internal dictionary used for storing already copied values. This
parameter should not be used.
:return: New :py:class:`Spec` object that is a deep copy of ``self``.'
| def copy(self, copied=None):
| copied = (copied or {})
try:
return copied[id(self)]
except KeyError:
instance = self.__class__()
copied[id(self)] = instance
return self.__class__()._update(self.__dict__, copied)
|
'Helper for the :py:meth:`Spec.copy` function
Populates new instance with values taken from the old one.
:param dict d:
``__dict__`` of the old instance.
:param dict copied:
Storage for already copied values.'
| def _update(self, d, copied):
| self.__dict__.update(d)
self.keys = copy(self.keys)
self.checks = copy(self.checks)
self.uspecs = copy(self.uspecs)
self.specs = [spec.copy(copied) for spec in self.specs]
return self
|
'Define specification for non-static keys
This method should be used if key names cannot be determined at runtime
or if a number of keys share identical spec (in order to not repeat it).
:py:meth:`Spec.match` method processes dictionary in the given order:
* First it tries to use specifications provided at the initiali... | def unknown_spec(self, keyfunc, spec):
| if isinstance(keyfunc, Spec):
self.specs.append(keyfunc)
keyfunc = (len(self.specs) - 1)
self.specs.append(spec)
self.uspecs.append((keyfunc, (len(self.specs) - 1)))
return self
|
'Initialize the scanner.'
| def __init__(self):
| self.done = False
self.flow_level = 0
self.tokens = []
self.fetch_stream_start()
self.tokens_taken = 0
self.allow_simple_key = False
self.possible_simple_keys = {}
|
'Do actual initialization.
__init__ function only stores the arguments and runs this function. This
function exists for powerline to be able to reload itself: it is easier
to make ``__init__`` store arguments and call overriddable ``init`` than
tell developers that each time they override Powerline.__init__ in
subclass... | def init(self, ext, renderer_module=None, run_once=False, logger=None, use_daemon_threads=True, shutdown_event=None, config_loader=None):
| self.ext = ext
self.run_once = run_once
self.logger = logger
self.had_logger = bool(self.logger)
self.use_daemon_threads = use_daemon_threads
if (not renderer_module):
self.renderer_module = (u'powerline.renderers.' + ext)
elif (u'.' not in renderer_module):
self.renderer_mod... |
'Create logger
This function is used to create logger unless it was already specified
at initialization.
:return: Three objects:
#. :py:class:`logging.Logger` instance.
#. :py:class:`PowerlineLogger` instance.
#. Function, output of :py:func:`gen_module_attr_getter`.'
| def create_logger(self):
| return create_logger(common_config=self.common_config, use_daemon_threads=self.use_daemon_threads, ext=self.ext, imported_modules=self.imported_modules, stream=self.default_log_stream)
|
'List arguments which should be omitted
Returns a tuple with indexes of omitted arguments.
.. note::``segment_info``, ``create_watcher`` and ``pl`` will be omitted
regardless of the below return (for ``segment_info`` and
``create_watcher``: only if object was marked to require segment
info or filesystem watcher).'
| def omitted_args(self, name, method):
| if isinstance(self.__call__, MethodType):
return (0,)
else:
return ()
|
'Returns a list of (additional argument name[, default value]) tuples.'
| @staticmethod
def additional_args():
| return ()
|
'Add local themes at runtime (during vim session).
:param str key:
Matcher name (in format ``{matcher_module}.{module_attribute}`` or
``{module_attribute}`` if ``{matcher_module}`` is
``powerline.matchers.vim``). Function pointed by
``{module_attribute}`` should be hashable and accept a dictionary
with information abou... | def add_local_theme(self, key, config):
| self.update_renderer()
matcher = self.get_matcher(key)
theme_config = {}
for cfg_path in self.theme_levels:
try:
lvl_config = self.load_config(cfg_path, u'theme')
except IOError:
pass
else:
mergedicts(theme_config, lvl_config)
mergedicts(th... |
'Evaluate python string passed to PowerlinePyeval
Is here to reduce the number of requirements to __main__ globals to just
one powerline object (previously it required as well vim and json).'
| @staticmethod
def do_pyeval():
| import __main__
vim.command((u'return ' + json.dumps(eval(vim.eval(u'a:e'), __main__.__dict__))))
|
'Output highlighted chunk.
This implementation outputs a list containing a single pair
(:py:class:`pygments.token.Token`,
:py:class:`powerline.lib.unicode.unicode`).'
| def hl(self, contents, fg=None, bg=None, attrs=None):
| guifg = None
guibg = None
attrs = []
if ((fg is not None) and (fg is not False)):
guifg = fg[1]
if ((bg is not None) and (bg is not False)):
guibg = bg[1]
if attrs:
attrs = []
if (attrs & ATTR_BOLD):
attrs.append(u'bold')
if (attrs & ATTR_ITALI... |
'Highlight a segment.'
| def hlstyle(self, fg=None, bg=None, attrs=None):
| if ((not attrs) and (not bg) and (not fg)):
return u''
tmux_attrs = []
if (fg is not None):
if ((fg is False) or (fg[0] is False)):
tmux_attrs += [u'fg=default']
else:
tmux_attrs += [(u'fg=colour' + str(fg[0]))]
if (bg is not None):
if ((bg is Fals... |
'Get client ID given segment info
This is used by daemon to correctly cache widths for different clients
using a single renderer instance.
:param dict segment_info:
:ref:`Segment info dictionary <dev-segments-info>`. Out of it only
``client_id`` key is used. It is OK for this dictionary to not
contain this key.
:return... | def get_client_id(self, segment_info):
| return (segment_info.get(u'client_id') if isinstance(segment_info, dict) else None)
|
'Render all segments.'
| def render(self, window=None, window_id=None, winnr=None, is_tabline=False):
| segment_info = self.segment_info.copy()
if (window is vim.current.window):
mode = vim_mode()
mode = mode_translations.get(mode, mode)
else:
mode = u'nc'
segment_info.update(window=window, mode=mode, window_id=window_id, winnr=winnr, buffer=window.buffer, tabpage=current_tabpage()... |
'Highlight a segment.'
| def hl(self, contents, fg=None, bg=None, attrs=None):
| awesome_attr = []
if (fg is not None):
if ((fg is not False) and (fg[1] is not False)):
awesome_attr += [u'foreground="#{0:06x}"'.format(fg[1])]
if (bg is not None):
if ((bg is not False) and (bg[1] is not False)):
awesome_attr += [u'background="#{0:06x}"'.format(bg[1... |
'Record currently used :py:class:`pdb.Pdb` instance
Must be called before first calling :py:meth:`render` method.
:param pdb.Pdb pdb:
Used :py:class:`pdb.Pdb` instance. This instance will later be used
by :py:meth:`get_segment_info` for patching :ref:`segment_info
<dev-segments-info>` dictionary.'
| def set_pdb(self, pdb):
| self.pdb = pdb
|
'Register function that will be run when file changes.
:param function function:
Function that will be called when file at the given path changes.
:param str path:
Path that will be watched for.'
| def register(self, function, path):
| with self.lock:
self.watched[path].add(function)
self.watcher.watch(path)
|
'Register any function that will be called with given key each
interval seconds (interval is defined at __init__). Its result is then
passed to ``function``, but only if the result is true.
:param function condition_function:
Function which will be called each ``interval`` seconds. All
exceptions from it will be logged... | def register_missing(self, condition_function, function, key):
| with self.lock:
self.missing[key].add((condition_function, function))
|
'Unregister files handled by these functions.
:param set removed_functions:
Set of functions previously passed to ``.register()`` method.'
| def unregister_functions(self, removed_functions):
| with self.lock:
for (path, functions) in list(self.watched.items()):
functions -= removed_functions
if (not functions):
self.watched.pop(path)
self.loaded.pop(path, None)
|
'Unregister files handled by these functions.
:param set removed_functions:
Set of pairs (2-tuples) representing ``(condition_function,
function)`` function pairs previously passed as an arguments to
``.register_missing()`` method.'
| def unregister_missing(self, removed_functions):
| with self.lock:
for (key, functions) in list(self.missing.items()):
functions -= removed_functions
if (not functions):
self.missing.pop(key)
|
'Return status of repository or file.
Without file argument: returns status of the repository:
:\'D?\': dirty (tracked modified files: added, removed, deleted, modified),
:\'?U\': untracked-dirty (added, but not tracked files)
:None: clean (status is empty)
With file argument: returns status of this file: `M`odified, `... | def status(self, path=None):
| if path:
return get_file_status(directory=self.directory, dirstate_file=join(self.directory, u'.hg', u'dirstate'), file_path=path, ignore_file_name=u'.hgignore', get_func=self.do_status, create_watcher=self.create_watcher)
return self.do_status(self.directory, path)
|
'Return status of repository or file.
Without file argument: returns status of the repository:
:\'D?\': dirty (tracked modified files: added, removed, deleted, modified),
:\'?U\': untracked-dirty (added, but not tracked files)
:None: clean (status is empty)
With file argument: returns status of this file: The status co... | def status(self, path=None):
| if (path is not None):
return get_file_status(directory=self.directory, dirstate_file=join(self.directory, u'.bzr', u'checkout', u'dirstate'), file_path=path, ignore_file_name=u'.bzrignore', get_func=self.do_status, create_watcher=self.create_watcher)
return self.do_status(self.directory, path)
|
'Return status of repository or file.
Without file argument: returns status of the repository:
:First column: working directory status (D: dirty / space)
:Second column: index status (I: index dirty / space)
:Third column: presence of untracked files (U: untracked files / space)
:None: repository clean
With file argume... | def status(self, path=None):
| if path:
gitd = git_directory(self.directory)
return get_file_status(directory=self.directory, dirstate_file=join(gitd, u'index'), file_path=path, ignore_file_name=u'.gitignore', get_func=self.do_status, create_watcher=self.create_watcher, extra_ignore_files=tuple((join(gitd, x) for x in (u'logs/HEA... |
'Remove the watch for path. Raises an OSError if removing the watch
fails for some reason.'
| def unwatch(self, path):
| path = realpath(path)
with self.lock:
self.modified.pop(path, None)
self.last_query.pop(path, None)
wd = self.watches.pop(path, None)
if (wd is not None):
if (self._rm_watch(self._inotify_fd, wd) != 0):
self.handle_error()
|
'Register a watch for the file/directory named path. Raises an OSError if path
does not exist.'
| def watch(self, path):
| path = realpath(path)
with self.lock:
if (path not in self.watches):
bpath = (path if isinstance(path, bytes) else path.encode(self.fenc))
flags = (self.MOVE_SELF | self.DELETE_SELF)
buf = ctypes.c_char_p(bpath)
wd = self._add_watch(self._inotify_fd, buf, ... |
'Return True if path has been modified since the last call. Can
raise OSError if the path does not exist.'
| def __call__(self, path):
| path = realpath(path)
with self.lock:
self.last_query[path] = monotonic()
self.expire_watches()
if (path not in self.watches):
self.watch(path)
return True
self.read(get_name=False)
if (path not in self.modified):
return True
an... |
'Add watches for this directory and all its descendant directories,
recursively.'
| def add_watches(self, base, top_level=True):
| base = realpath(base)
if ((not top_level) and (base in self.watched_dirs)):
return
try:
is_dir = self.add_watch(base)
except OSError as e:
if (e.errno == errno.ENOENT):
if top_level:
raise NoSuchDir(u'The dir {0} does not exist'.format(b... |
'Initialize a colorscheme.'
| def __init__(self, colorscheme_config, colors_config):
| self.colors = {}
self.gradients = {}
self.groups = colorscheme_config[u'groups']
self.translations = colorscheme_config.get(u'mode_translations', {})
for (color_name, color) in colors_config[u'colors'].items():
try:
self.colors[color_name] = (color[0], int(color[1], 16))
... |
'Get Theme object.
Is to be overridden by subclasses to support local themes, this variant
only returns ``.theme`` attribute.
:param matcher_info:
Parameter ``matcher_info`` that ``.render()`` method received.
Unused.'
| def get_theme(self, matcher_info):
| return self.theme
|
'Prepare for interpreter shutdown. The only job it is supposed to do
is calling ``.shutdown()`` method for all theme objects. Should be
overridden by subclasses in case they support local themes.'
| def shutdown(self):
| self.theme.shutdown()
|
'Get segment information.
Must return a dictionary containing at least ``home``, ``environ`` and
``getcwd`` keys (see documentation for ``segment_info`` attribute). This
implementation merges ``segment_info`` dictionary passed to
``.render()`` method with ``.segment_info`` attribute, preferring keys
from the former. It... | def get_segment_info(self, segment_info, mode):
| r = self.segment_info.copy()
r[u'mode'] = mode
if segment_info:
r.update(segment_info)
if (u'PWD' in r[u'environ']):
r[u'getcwd'] = (lambda : r[u'environ'][u'PWD'])
return r
|
'Render all segments in the {theme}/segments/above list
Rendering happens in the reversed order. Parameters are the same as in
.render() method.
:yield: rendered line.'
| def render_above_lines(self, **kwargs):
| theme = self.get_theme(kwargs.get(u'matcher_info', None))
for line in range((theme.get_line_number() - 1), 0, (-1)):
(yield self.render(side=None, line=line, **kwargs))
|
'Render all segments.
When a width is provided, low-priority segments are dropped one at
a time until the line is shorter than the width, or only segments
with a negative priority are left. If one or more segments with
``"width": "auto"`` are provided they will fill the remaining space
until the desired width is reache... | def render(self, mode=None, width=None, side=None, line=0, output_raw=False, output_width=False, segment_info=None, matcher_info=None):
| theme = self.get_theme(matcher_info)
return self.do_render(mode=mode, width=width, side=side, line=line, output_raw=output_raw, output_width=output_width, segment_info=self.get_segment_info(segment_info, mode), theme=theme)
|
'Like Renderer.render(), but accept theme in place of matcher_info'
| def do_render(self, mode, width, side, line, output_raw, output_width, segment_info, theme):
| segments = list(theme.get_segments(side, line, segment_info, mode))
current_width = 0
self._prepare_segments(segments, (output_width or width))
if (not width):
if output_width:
current_width = self._render_length(theme, segments, self.compute_divider_widths(theme))
return con... |
'Translate non-printable characters and calculate segment width'
| def _prepare_segments(self, segments, calculate_contents_len):
| for segment in segments:
segment[u'contents'] = translate_np(segment[u'contents'])
if calculate_contents_len:
for segment in segments:
if segment[u'literal_contents'][1]:
segment[u'_contents_len'] = segment[u'literal_contents'][0]
else:
seg... |
'Update segments lengths and return them'
| def _render_length(self, theme, segments, divider_widths):
| segments_len = len(segments)
ret = 0
divider_spaces = theme.get_spaces()
prev_segment = theme.EMPTY_SEGMENT
try:
first_segment = next(iter((segment for segment in segments if (not segment[u'literal_contents'][1]))))
except StopIteration:
first_segment = None
try:
last... |
'Internal segment rendering method.
This method loops through the segment array and compares the
foreground/background colors and divider properties and returns the
rendered statusline as a string.
The method always renders the raw segment contents (i.e. without
highlighting strings added), and only renders the highlig... | def _render_segments(self, theme, segments, render_highlighted=True):
| segments_len = len(segments)
divider_spaces = theme.get_spaces()
prev_segment = theme.EMPTY_SEGMENT
try:
first_segment = next(iter((segment for segment in segments if (not segment[u'literal_contents'][1]))))
except StopIteration:
first_segment = None
try:
last_segment = n... |
'Method that escapes segment contents.'
| def escape(self, string):
| return string.translate(self.character_translations)
|
'Output highlight style string.
Assuming highlighted string looks like ``{style}{contents}`` this method
should output ``{style}``. If it is called without arguments this method
is supposed to reset style to its default.'
| def hlstyle(fg=None, bg=None, attrs=None):
| raise NotImplementedError
|
'Output highlighted chunk.
This implementation just outputs :py:meth:`hlstyle` joined with
``contents``.'
| def hl(self, contents, fg=None, bg=None, attrs=None):
| return (self.hlstyle(fg, bg, attrs) + (contents or u''))
|
'Return segment divider.'
| def get_divider(self, side=u'left', type=u'soft'):
| return self.dividers[side][type]
|
'Return all segments.
Function segments are called, and all segments get their before/after
and ljust/rjust properties applied.
:param int line:
Line number for which segments should be obtained. Is counted from
zero (botmost line).'
| def get_segments(self, side=None, line=0, segment_info=None, mode=None):
| for side in ([side] if side else [u'left', u'right']):
parsed_segments = []
for segment in self.segments[line][side]:
if segment[u'display_condition'](self.pl, segment_info, mode):
process_segment(self.pl, side, segment_info, parsed_segments, segment, mode, self.colorsche... |
'Specify which python packages need to be installed to use this component, e.g. `["spacy", "numpy"]`.
This list of requirements allows us to fail early during training if a required package is not installed.'
| @classmethod
def required_packages(cls):
| return []
|
'Load this component from file.
After a component got trained, it will be persisted by calling `persist`. When the pipeline gets loaded again,
this component needs to be able to restore itself. Components can rely on any context attributes that are
created by `pipeline_init` calls to components previous to this one.'
| @classmethod
def load(cls, model_dir=None, model_metadata=None, cached_component=None, **kwargs):
| return (cached_component if cached_component else cls())
|
'Creates this component (e.g. before a training is started).
Method can access all configuration parameters.'
| @classmethod
def create(cls, config):
| return cls()
|
'Initialize this component for a new pipeline
This function will be called before the training is started and before the first message is processed using
the interpreter. The component gets the opportunity to add information to the context that is passed through
the pipeline during training and message parsing. Most co... | def provide_context(self):
| pass
|
'Train this component.
This is the components chance to train itself provided with the training data. The component can rely on
any context attribute to be present, that gets created by a call to `pipeline_init` of ANY component and
on any context attributes created by a call to `train` of components previous to this o... | def train(self, training_data, config, **kwargs):
| pass
|
'Process an incomming message.
This is the components chance to process an incommng message. The component can rely on
any context attribute to be present, that gets created by a call to `pipeline_init` of ANY component and
on any context attributes created by a call to `process` of components previous to this one.'
| def process(self, message, **kwargs):
| pass
|
'Persist this component to disk for future loading.'
| def persist(self, model_dir):
| pass
|
'This key is used to cache components.
If a component is unique to a model it should return None. Otherwise, an instantiation of the
component will be reused for all models where the metadata creates the same key.'
| @classmethod
def cache_key(cls, model_metadata):
| from rasa_nlu.model import Metadata
return None
|
'Sets the pipeline and context used for partial processing.
The pipeline should be a list of components that are previous to this one in the pipeline and
have already finished their training (and can therefore be safely used to process messages).'
| def prepare_partial_processing(self, pipeline, context):
| self.partial_processing_pipeline = pipeline
self.partial_processing_context = context
|
'Allows the component to process messages during training (e.g. external training data).
The passed message will be processed by all components previous to this one in the pipeline.'
| def partially_process(self, message):
| if (self.partial_processing_context is not None):
for component in self.partial_processing_pipeline:
component.process(message, **self.partial_processing_context)
else:
logger.info(u'Failed to run partial processing due to missing pipeline.')
return messag... |
'Load a component from the cache, if it exists. Returns the component, if found, and the cache key.'
| def __get_cached_component(self, component_name, model_metadata):
| from rasa_nlu import registry
from rasa_nlu.model import Metadata
component_class = registry.get_component_class(component_name)
cache_key = component_class.cache_key(model_metadata)
if ((cache_key is not None) and self.use_cache and (cache_key in self.component_cache)):
return (self.compone... |
'Add a component to the cache.'
| def __add_to_cache(self, component, cache_key):
| if ((cache_key is not None) and self.use_cache):
self.component_cache[cache_key] = component
logger.info(u"Added '{}' to component cache. Key '{}'.".format(component.name, cache_key))
|
'Tries to retrieve a component from the cache, calls `load` to create a new component.'
| def load_component(self, component_name, model_dir, model_metadata, **context):
| from rasa_nlu import registry
from rasa_nlu.model import Metadata
try:
(cached_component, cache_key) = self.__get_cached_component(component_name, model_metadata)
component = registry.load_component_by_name(component_name, model_dir, model_metadata, cached_component, **context)
if (n... |
'Tries to retrieve a component from the cache, calls `create` to create a new component.'
| def create_component(self, component_name, config):
| from rasa_nlu import registry
from rasa_nlu.model import Metadata
try:
(component, cache_key) = self.__get_cached_component(component_name, Metadata(config.as_dict(), None))
if (component is None):
component = registry.create_component_by_name(component_name, config)
... |
'Uploads a model persisted in the `target_dir` to cloud storage.'
| def save_tar(self, target_dir):
| raise NotImplementedError(u'')
|
'Downloads a model that has previously been persisted to cloud storage.'
| def fetch_and_extract(self, filename):
| raise NotImplementedError(u'')
|
'Uploads a model persisted in the `target_dir` to s3.'
| def save_tar(self, target_dir):
| if (not os.path.isdir(target_dir)):
raise ValueError(u"Target directory '{}' not found.".format(target_dir))
base_name = os.path.basename(target_dir)
base_dir = os.path.dirname(target_dir)
tarname = shutil.make_archive(base_name, u'gztar', root_dir=base_dir, base_dir=base_name)
f... |
'Downloads a model that has previously been persisted to s3.'
| def fetch_and_extract(self, filename):
| with io.open(filename, u'wb') as f:
self.bucket.download_fileobj(filename, f)
with tarfile.open(filename, u'r:gz') as tar:
tar.extractall(self.data_dir)
|
'Uploads a model persisted in the `target_dir` to GCS.'
| def save_tar(self, target_dir):
| if (not os.path.isdir(target_dir)):
raise ValueError((u'target_dir %r not found.' % target_dir))
base_name = os.path.basename(target_dir)
base_dir = os.path.dirname(target_dir)
tarname = shutil.make_archive(base_name, u'gztar', root_dir=base_dir, base_dir=base_name)
filekey = os.pat... |
'Downloads a model that has previously been persisted to GCS.'
| def fetch_and_extract(self, filename):
| blob = self.bucket.blob(filename)
blob.download_to_filename(filename)
with tarfile.open(filename, u'r:gz') as tar:
tar.extractall(self.data_dir)
|
'Construct a new intent classifier using the sklearn framework.'
| def __init__(self, clf=None, le=None):
| from sklearn.preprocessing import LabelEncoder
if (le is not None):
self.le = le
else:
self.le = LabelEncoder()
self.clf = clf
|
'Transforms a list of strings into numeric label representation.
:param labels: List of labels to convert to numeric representation'
| def transform_labels_str2num(self, labels):
| return self.le.fit_transform(labels)
|
'Transforms a list of strings into numeric label representation.
:param y: List of labels to convert to numeric representation'
| def transform_labels_num2str(self, y):
| return self.le.inverse_transform(y)
|
'Train the intent classifier on a data set.
:param num_threads: number of threads used during training time'
| def train(self, training_data, config, **kwargs):
| from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
import numpy as np
labels = [e.get(u'intent') for e in training_data.intent_examples]
if (len(set(labels)) < 2):
logger.warn((u'Can not train an intent classifier. Need at least 2 diffe... |
'Returns the most likely intent and its probability for the input text.'
| def process(self, message, **kwargs):
| if (not self.clf):
intent = None
intent_ranking = []
else:
X = message.get(u'text_features').reshape(1, (-1))
(intent_ids, probabilities) = self.predict(X)
intents = self.transform_labels_num2str(intent_ids)
(intents, probabilities) = (intents.flatten(), probabili... |
'Given a bow vector of an input text, predict the intent label. Returns probabilities for all labels.
:param X: bow of input text
:return: vector of probabilities containing one entry for each label'
| def predict_prob(self, X):
| return self.clf.predict_proba(X)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.