Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from docutils.parsers.rst import directives
from six import string_types
from six.moves import cStringIO as StringIO
from types import ModuleType
def setup(app):
app.add_directive('phil', PhilDirective)
return {"parallel_read_safe": True}
class PhilDirective(Directive):
# this disables content in the directive
has_content = False
required_arguments = 1
option_spec = {'expert-level': directives.nonnegative_int,
'attributes-level': directives.nonnegative_int}
def run(self):
phil_include = self.arguments[0]
expert_level = self.options.get('expert-level', None)
attributes_level = self.options.get('attributes-level', 0)
self.master_params = self._find_phil_scope(phil_include)
s = StringIO()
self.master_params.show(
s, expert_level=expert_level, attributes_level=attributes_level)
text = s.getvalue()
node = docutils.nodes.literal_block(text, text)
self.add_name(node)
return [node]
urlParse = urllib.parse.quote_plus
class Needsequence(nodes.General, nodes.Element):
pass
class NeedsequenceDirective(FilterBase, DiagramBase):
"""
Directive to get sequence diagrams.
"""
optional_arguments = 1
final_argument_whitespace = True
option_spec = {
'start': directives.unchanged,
'link_types': directives.unchanged,
}
# Update the options_spec with values defined in the FilterBase class
option_spec.update(FilterBase.base_option_spec)
option_spec.update(DiagramBase.base_option_spec)
def run(self):
env = self.state.document.settings.env
# Creates env.need_all_needsequences safely and other vars
self.prepare_env('needsequences')
id, targetid, targetnode = self.create_target('needsequence')
start = self.options.get('start', None)
if start is None or len(start.strip()) == 0:
raise NeedSequenceException('No valid start option given for needsequence. '
def add_directive(self, name, obj, content=None, arguments=None, **options):
self.debug('[app] adding directive: %r',
(name, obj, content, arguments, options))
if name in directives._directives:
self.warn('while setting up extension %s: directive %r is '
'already registered, it will be overridden' %
(self._setting_up_extension[-1], name),
type='app', subtype='add_directive')
directives.register_directive(
name, self._directive_helper(obj, content, arguments, **options))
-------
id : str
An identifier for *this kernel instance*. Used to name any output
files generated when executing the Jupyter cells (e.g. images
produced by cells, or a script containing the cell inputs).
Content
-------
None
"""
optional_arguments = 1
final_argument_whitespace = False
has_content = False
option_spec = {"id": directives.unchanged}
def run(self):
return [
JupyterKernelNode(
"",
kernel_name=self.arguments[0].strip() if self.arguments else "",
kernel_id=self.options.get("id", "").strip(),
)
]
### Doctree transformations
class ExecuteJupyterCells(SphinxTransform):
"""Execute code cells in Jupyter kernels.
Traverses the doctree to find JupyterKernel and JupyterCell nodes,
import sys
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives
from docutils.parsers.rst.roles import set_classes
from docutils.utils.code_analyzer import Lexer, LexerError, NumberLines
class BasePseudoSection(Directive):
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'class': directives.class_option,
'name': directives.unchanged}
has_content = True
node_class = None
"""Node class to be used (must be set in subclasses)."""
def run(self):
if not (self.state_machine.match_titles
or isinstance(self.state_machine.node, nodes.sidebar)):
raise self.error('The "%s" directive may not be used within '
'topics or body elements.' % self.name)
self.assert_has_content()
title_text = self.arguments[0]
textnodes, messages = self.state.inline_text(title_text, self.lineno)
titles = [nodes.title(title_text, '', *textnodes)]
# Sidebar uses this code.
if 'subtitle' in self.options:
JSONCALL_TEMPLATE = '''
**Test Request**
.. jsoncall:: %(path)s
%(argd_json)s
'''
class TGJSONAutodoc(Directive):
required_arguments = 0
optional_arguments = 0
has_content = False
option_spec = {'skip-urls': directives.unchanged}
def _retrieve_root(self):
env = self.state.document.settings.env
tgapp = env.config.tgjsonautodoc_app
app = loadapp('config:'+tgapp, name='main', relative_to=os.getcwd())
return TGApp().find_controller('root')()
def _filter_controllers(self, obj):
if isinstance(obj, DecoratedController):
return True
elif inspect.ismethod(obj) and hasattr(obj, 'decoration'):
return True
return False
def _gather_controller_json_methods(self, root_controller):
self.body.append("")
def depart_youtube_node(self, node):
pass
class YouTube(Directive):
ALIGN_KEYS = ['left', 'right', 'center', 'centre']
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
option_spec = {
"width": directives.unchanged,
"height": directives.unchanged,
"aspect": directives.unchanged,
"align": directives.unchanged,
}
def run(self):
if "aspect" in self.options:
aspect = self.options.get("aspect")
m = re.match("(\d+):(\d+)", aspect)
if m is None:
raise ValueError("invalid aspect ratio %r" % aspect)
aspect = tuple(int(x) for x in m.groups())
else:
aspect = None
width = get_size(self.options, "width")
height = get_size(self.options, "height")
if "align" in self.options and self.options.get("align") in self.ALIGN_KEYS:
align = self.options.get("align")
else:
finishCoords()
finishLine()
finishPlot()
This plotter accepts the following options:
:term:`as-lines`: do not plot symbols
:term:`yerror`: every second data track is a y error
'''
nlevels = 2
options = BokehPlotter.options +\
(('as-lines', directives.flag),
('yerror', directives.flag),
)
def __init__(self, *args, **kwargs):
Renderer.__init__(self, *args, **kwargs)
BokehPlotter.__init__(self, *args, **kwargs)
self.as_lines = "as-lines" in kwargs
# data to use for Y error bars
self.yerror = "yerror" in kwargs
# do not plot more than ten tracks in one plot
self.split_at = 10
# self.format_colors = bk.brewer["Spectral"][10]
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
# Class name gives the DOM element name
class book(nodes.Admonition, nodes.Element):
pass
class Book(Directive):
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = True
option_spec = {'cover': directives.uri,
'template': directives.unchanged,
'ignore-missing-pages': yesno,
'toc-depth': directives.positive_int,
'title': directives.unchanged,
'comments': directives.unchanged,
'subject': directives.unchanged,
'language': language,
'keywords': directives.unchanged,
'filename': directives.unchanged}
has_content = True
def run(self):
self.assert_has_content()
# Default values
options = self.options
from sphinx.util.compat import Directive
class TikzExtError(SphinxError):
category = 'Tikz extension error'
class tikz(nodes.General, nodes.Element):
pass
class TikzDirective(Directive):
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = True
option_spec = {'libs': directives.unchanged,
'filename': directives.unchanged,
}
def run(self):
node = tikz()
node['tikz'] = '\n'.join(self.content)
node['caption'] = '\n'.join(self.arguments)
node['libs'] = self.options.get('libs', '')
node['fname'] = self.options.get('filename', '')
return [node]
DOC_HEAD = r'''
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}