Best JavaScript code snippet using fast-check-monorepo
kfigure.py
Source:kfigure.py
1# -*- coding: utf-8; mode: python -*-2# pylint: disable=C0103, R0903, R0912, R09153u"""4 scalable figure and image handling5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~6 Sphinx extension which implements scalable image handling.7 :copyright: Copyright (C) 2016 Markus Heiser8 :license: GPL Version 2, June 1991 see Linux/COPYING for details.9 The build for image formats depend on image's source format and output's10 destination format. This extension implement methods to simplify image11 handling from the author's POV. Directives like ``kernel-figure`` implement12 methods *to* always get the best output-format even if some tools are not13 installed. For more details take a look at ``convert_image(...)`` which is14 the core of all conversions.15 * ``.. kernel-image``: for image handling / a ``.. image::`` replacement16 * ``.. kernel-figure``: for figure handling / a ``.. figure::`` replacement17 * ``.. kernel-render``: for render markup / a concept to embed *render*18 markups (or languages). Supported markups (see ``RENDER_MARKUP_EXT``)19 - ``DOT``: render embedded Graphviz's **DOC**20 - ``SVG``: render embedded Scalable Vector Graphics (**SVG**)21 - ... *developable*22 Used tools:23 * ``dot(1)``: Graphviz (http://www.graphviz.org). If Graphviz is not24 available, the DOT language is inserted as literal-block.25 * SVG to PDF: To generate PDF, you need at least one of this tools:26 - ``convert(1)``: ImageMagick (https://www.imagemagick.org)27 List of customizations:28 * generate PDF from SVG / used by PDF (LaTeX) builder29 * generate SVG (html-builder) and PDF (latex-builder) from DOT files.30 DOT: see http://www.graphviz.org/content/dot-language31 """32import os33from os import path34import subprocess35from hashlib import sha136import sys37from docutils import nodes38from docutils.statemachine import ViewList39from docutils.parsers.rst import directives40from docutils.parsers.rst.directives import images41import sphinx42from sphinx.util.nodes import clean_astext43from six import iteritems44import kernellog45PY3 = sys.version_info[0] == 346if PY3:47 _unicode = str48else:49 _unicode = unicode50# Get Sphinx version51major, minor, patch = sphinx.version_info[:3]52if major == 1 and minor > 3:53 # patches.Figure only landed in Sphinx 1.454 from sphinx.directives.patches import Figure # pylint: disable=C041355else:56 Figure = images.Figure57__version__ = '1.0.0'58# simple helper59# -------------60def which(cmd):61 """Searches the ``cmd`` in the ``PATH`` environment.62 This *which* searches the PATH for executable ``cmd`` . First match is63 returned, if nothing is found, ``None` is returned.64 """65 envpath = os.environ.get('PATH', None) or os.defpath66 for folder in envpath.split(os.pathsep):67 fname = folder + os.sep + cmd68 if path.isfile(fname):69 return fname70def mkdir(folder, mode=0o775):71 if not path.isdir(folder):72 os.makedirs(folder, mode)73def file2literal(fname):74 with open(fname, "r") as src:75 data = src.read()76 node = nodes.literal_block(data, data)77 return node78def isNewer(path1, path2):79 """Returns True if ``path1`` is newer than ``path2``80 If ``path1`` exists and is newer than ``path2`` the function returns81 ``True`` is returned otherwise ``False``82 """83 return (path.exists(path1)84 and os.stat(path1).st_ctime > os.stat(path2).st_ctime)85def pass_handle(self, node): # pylint: disable=W061386 pass87# setup conversion tools and sphinx extension88# -------------------------------------------89# Graphviz's dot(1) support90dot_cmd = None91# ImageMagick' convert(1) support92convert_cmd = None93def setup(app):94 # check toolchain first95 app.connect('builder-inited', setupTools)96 # image handling97 app.add_directive("kernel-image", KernelImage)98 app.add_node(kernel_image,99 html = (visit_kernel_image, pass_handle),100 latex = (visit_kernel_image, pass_handle),101 texinfo = (visit_kernel_image, pass_handle),102 text = (visit_kernel_image, pass_handle),103 man = (visit_kernel_image, pass_handle), )104 # figure handling105 app.add_directive("kernel-figure", KernelFigure)106 app.add_node(kernel_figure,107 html = (visit_kernel_figure, pass_handle),108 latex = (visit_kernel_figure, pass_handle),109 texinfo = (visit_kernel_figure, pass_handle),110 text = (visit_kernel_figure, pass_handle),111 man = (visit_kernel_figure, pass_handle), )112 # render handling113 app.add_directive('kernel-render', KernelRender)114 app.add_node(kernel_render,115 html = (visit_kernel_render, pass_handle),116 latex = (visit_kernel_render, pass_handle),117 texinfo = (visit_kernel_render, pass_handle),118 text = (visit_kernel_render, pass_handle),119 man = (visit_kernel_render, pass_handle), )120 app.connect('doctree-read', add_kernel_figure_to_std_domain)121 return dict(122 version = __version__,123 parallel_read_safe = True,124 parallel_write_safe = True125 )126def setupTools(app):127 u"""128 Check available build tools and log some *verbose* messages.129 This function is called once, when the builder is initiated.130 """131 global dot_cmd, convert_cmd # pylint: disable=W0603132 kernellog.verbose(app, "kfigure: check installed tools ...")133 dot_cmd = which('dot')134 convert_cmd = which('convert')135 if dot_cmd:136 kernellog.verbose(app, "use dot(1) from: " + dot_cmd)137 else:138 kernellog.warn(app, "dot(1) not found, for better output quality install "139 "graphviz from http://www.graphviz.org")140 if convert_cmd:141 kernellog.verbose(app, "use convert(1) from: " + convert_cmd)142 else:143 kernellog.warn(app,144 "convert(1) not found, for SVG to PDF conversion install "145 "ImageMagick (https://www.imagemagick.org)")146# integrate conversion tools147# --------------------------148RENDER_MARKUP_EXT = {149 # The '.ext' must be handled by convert_image(..) function's *in_ext* input.150 # <name> : <.ext>151 'DOT' : '.dot',152 'SVG' : '.svg'153}154def convert_image(img_node, translator, src_fname=None):155 """Convert a image node for the builder.156 Different builder prefer different image formats, e.g. *latex* builder157 prefer PDF while *html* builder prefer SVG format for images.158 This function handles output image formats in dependence of source the159 format (of the image) and the translator's output format.160 """161 app = translator.builder.app162 fname, in_ext = path.splitext(path.basename(img_node['uri']))163 if src_fname is None:164 src_fname = path.join(translator.builder.srcdir, img_node['uri'])165 if not path.exists(src_fname):166 src_fname = path.join(translator.builder.outdir, img_node['uri'])167 dst_fname = None168 # in kernel builds, use 'make SPHINXOPTS=-v' to see verbose messages169 kernellog.verbose(app, 'assert best format for: ' + img_node['uri'])170 if in_ext == '.dot':171 if not dot_cmd:172 kernellog.verbose(app,173 "dot from graphviz not available / include DOT raw.")174 img_node.replace_self(file2literal(src_fname))175 elif translator.builder.format == 'latex':176 dst_fname = path.join(translator.builder.outdir, fname + '.pdf')177 img_node['uri'] = fname + '.pdf'178 img_node['candidates'] = {'*': fname + '.pdf'}179 elif translator.builder.format == 'html':180 dst_fname = path.join(181 translator.builder.outdir,182 translator.builder.imagedir,183 fname + '.svg')184 img_node['uri'] = path.join(185 translator.builder.imgpath, fname + '.svg')186 img_node['candidates'] = {187 '*': path.join(translator.builder.imgpath, fname + '.svg')}188 else:189 # all other builder formats will include DOT as raw190 img_node.replace_self(file2literal(src_fname))191 elif in_ext == '.svg':192 if translator.builder.format == 'latex':193 if convert_cmd is None:194 kernellog.verbose(app,195 "no SVG to PDF conversion available / include SVG raw.")196 img_node.replace_self(file2literal(src_fname))197 else:198 dst_fname = path.join(translator.builder.outdir, fname + '.pdf')199 img_node['uri'] = fname + '.pdf'200 img_node['candidates'] = {'*': fname + '.pdf'}201 if dst_fname:202 # the builder needs not to copy one more time, so pop it if exists.203 translator.builder.images.pop(img_node['uri'], None)204 _name = dst_fname[len(translator.builder.outdir) + 1:]205 if isNewer(dst_fname, src_fname):206 kernellog.verbose(app,207 "convert: {out}/%s already exists and is newer" % _name)208 else:209 ok = False210 mkdir(path.dirname(dst_fname))211 if in_ext == '.dot':212 kernellog.verbose(app, 'convert DOT to: {out}/' + _name)213 ok = dot2format(app, src_fname, dst_fname)214 elif in_ext == '.svg':215 kernellog.verbose(app, 'convert SVG to: {out}/' + _name)216 ok = svg2pdf(app, src_fname, dst_fname)217 if not ok:218 img_node.replace_self(file2literal(src_fname))219def dot2format(app, dot_fname, out_fname):220 """Converts DOT file to ``out_fname`` using ``dot(1)``.221 * ``dot_fname`` pathname of the input DOT file, including extension ``.dot``222 * ``out_fname`` pathname of the output file, including format extension223 The *format extension* depends on the ``dot`` command (see ``man dot``224 option ``-Txxx``). Normally you will use one of the following extensions:225 - ``.ps`` for PostScript,226 - ``.svg`` or ``svgz`` for Structured Vector Graphics,227 - ``.fig`` for XFIG graphics and228 - ``.png`` or ``gif`` for common bitmap graphics.229 """230 out_format = path.splitext(out_fname)[1][1:]231 cmd = [dot_cmd, '-T%s' % out_format, dot_fname]232 exit_code = 42233 with open(out_fname, "w") as out:234 exit_code = subprocess.call(cmd, stdout = out)235 if exit_code != 0:236 kernellog.warn(app,237 "Error #%d when calling: %s" % (exit_code, " ".join(cmd)))238 return bool(exit_code == 0)239def svg2pdf(app, svg_fname, pdf_fname):240 """Converts SVG to PDF with ``convert(1)`` command.241 Uses ``convert(1)`` from ImageMagick (https://www.imagemagick.org) for242 conversion. Returns ``True`` on success and ``False`` if an error occurred.243 * ``svg_fname`` pathname of the input SVG file with extension (``.svg``)244 * ``pdf_name`` pathname of the output PDF file with extension (``.pdf``)245 """246 cmd = [convert_cmd, svg_fname, pdf_fname]247 # use stdout and stderr from parent248 exit_code = subprocess.call(cmd)249 if exit_code != 0:250 kernellog.warn(app, "Error #%d when calling: %s" % (exit_code, " ".join(cmd)))251 return bool(exit_code == 0)252# image handling253# ---------------------254def visit_kernel_image(self, node): # pylint: disable=W0613255 """Visitor of the ``kernel_image`` Node.256 Handles the ``image`` child-node with the ``convert_image(...)``.257 """258 img_node = node[0]259 convert_image(img_node, self)260class kernel_image(nodes.image):261 """Node for ``kernel-image`` directive."""262 pass263class KernelImage(images.Image):264 u"""KernelImage directive265 Earns everything from ``.. image::`` directive, except *remote URI* and266 *glob* pattern. The KernelImage wraps a image node into a267 kernel_image node. See ``visit_kernel_image``.268 """269 def run(self):270 uri = self.arguments[0]271 if uri.endswith('.*') or uri.find('://') != -1:272 raise self.severe(273 'Error in "%s: %s": glob pattern and remote images are not allowed'274 % (self.name, uri))275 result = images.Image.run(self)276 if len(result) == 2 or isinstance(result[0], nodes.system_message):277 return result278 (image_node,) = result279 # wrap image node into a kernel_image node / see visitors280 node = kernel_image('', image_node)281 return [node]282# figure handling283# ---------------------284def visit_kernel_figure(self, node): # pylint: disable=W0613285 """Visitor of the ``kernel_figure`` Node.286 Handles the ``image`` child-node with the ``convert_image(...)``.287 """288 img_node = node[0][0]289 convert_image(img_node, self)290class kernel_figure(nodes.figure):291 """Node for ``kernel-figure`` directive."""292class KernelFigure(Figure):293 u"""KernelImage directive294 Earns everything from ``.. figure::`` directive, except *remote URI* and295 *glob* pattern. The KernelFigure wraps a figure node into a kernel_figure296 node. See ``visit_kernel_figure``.297 """298 def run(self):299 uri = self.arguments[0]300 if uri.endswith('.*') or uri.find('://') != -1:301 raise self.severe(302 'Error in "%s: %s":'303 ' glob pattern and remote images are not allowed'304 % (self.name, uri))305 result = Figure.run(self)306 if len(result) == 2 or isinstance(result[0], nodes.system_message):307 return result308 (figure_node,) = result309 # wrap figure node into a kernel_figure node / see visitors310 node = kernel_figure('', figure_node)311 return [node]312# render handling313# ---------------------314def visit_kernel_render(self, node):315 """Visitor of the ``kernel_render`` Node.316 If rendering tools available, save the markup of the ``literal_block`` child317 node into a file and replace the ``literal_block`` node with a new created318 ``image`` node, pointing to the saved markup file. Afterwards, handle the319 image child-node with the ``convert_image(...)``.320 """321 app = self.builder.app322 srclang = node.get('srclang')323 kernellog.verbose(app, 'visit kernel-render node lang: "%s"' % (srclang))324 tmp_ext = RENDER_MARKUP_EXT.get(srclang, None)325 if tmp_ext is None:326 kernellog.warn(app, 'kernel-render: "%s" unknown / include raw.' % (srclang))327 return328 if not dot_cmd and tmp_ext == '.dot':329 kernellog.verbose(app, "dot from graphviz not available / include raw.")330 return331 literal_block = node[0]332 code = literal_block.astext()333 hashobj = code.encode('utf-8') # str(node.attributes)334 fname = path.join('%s-%s' % (srclang, sha1(hashobj).hexdigest()))335 tmp_fname = path.join(336 self.builder.outdir, self.builder.imagedir, fname + tmp_ext)337 if not path.isfile(tmp_fname):338 mkdir(path.dirname(tmp_fname))339 with open(tmp_fname, "w") as out:340 out.write(code)341 img_node = nodes.image(node.rawsource, **node.attributes)342 img_node['uri'] = path.join(self.builder.imgpath, fname + tmp_ext)343 img_node['candidates'] = {344 '*': path.join(self.builder.imgpath, fname + tmp_ext)}345 literal_block.replace_self(img_node)346 convert_image(img_node, self, tmp_fname)347class kernel_render(nodes.General, nodes.Inline, nodes.Element):348 """Node for ``kernel-render`` directive."""349 pass350class KernelRender(Figure):351 u"""KernelRender directive352 Render content by external tool. Has all the options known from the353 *figure* directive, plus option ``caption``. If ``caption`` has a354 value, a figure node with the *caption* is inserted. If not, a image node is355 inserted.356 The KernelRender directive wraps the text of the directive into a357 literal_block node and wraps it into a kernel_render node. See358 ``visit_kernel_render``.359 """360 has_content = True361 required_arguments = 1362 optional_arguments = 0363 final_argument_whitespace = False364 # earn options from 'figure'365 option_spec = Figure.option_spec.copy()366 option_spec['caption'] = directives.unchanged367 def run(self):368 return [self.build_node()]369 def build_node(self):370 srclang = self.arguments[0].strip()371 if srclang not in RENDER_MARKUP_EXT.keys():372 return [self.state_machine.reporter.warning(373 'Unknown source language "%s", use one of: %s.' % (374 srclang, ",".join(RENDER_MARKUP_EXT.keys())),375 line=self.lineno)]376 code = '\n'.join(self.content)377 if not code.strip():378 return [self.state_machine.reporter.warning(379 'Ignoring "%s" directive without content.' % (380 self.name),381 line=self.lineno)]382 node = kernel_render()383 node['alt'] = self.options.get('alt','')384 node['srclang'] = srclang385 literal_node = nodes.literal_block(code, code)386 node += literal_node387 caption = self.options.get('caption')388 if caption:389 # parse caption's content390 parsed = nodes.Element()391 self.state.nested_parse(392 ViewList([caption], source=''), self.content_offset, parsed)393 caption_node = nodes.caption(394 parsed[0].rawsource, '', *parsed[0].children)395 caption_node.source = parsed[0].source396 caption_node.line = parsed[0].line397 figure_node = nodes.figure('', node)398 for k,v in self.options.items():399 figure_node[k] = v400 figure_node += caption_node401 node = figure_node402 return node403def add_kernel_figure_to_std_domain(app, doctree):404 """Add kernel-figure anchors to 'std' domain.405 The ``StandardDomain.process_doc(..)`` method does not know how to resolve406 the caption (label) of ``kernel-figure`` directive (it only knows about407 standard nodes, e.g. table, figure etc.). Without any additional handling408 this will result in a 'undefined label' for kernel-figures.409 This handle adds labels of kernel-figure to the 'std' domain labels.410 """411 std = app.env.domains["std"]412 docname = app.env.docname413 labels = std.data["labels"]414 for name, explicit in iteritems(doctree.nametypes):415 if not explicit:416 continue417 labelid = doctree.nameids[name]418 if labelid is None:419 continue420 node = doctree.ids[labelid]421 if node.tagname == 'kernel_figure':422 for n in node.next_node():423 if n.tagname == 'caption':424 sectname = clean_astext(n)425 # add label to std domain426 labels[name] = docname, labelid, sectname...
kernel_include.py
Source:kernel_include.py
1#!/usr/bin/env python32# -*- coding: utf-8; mode: python -*-3# pylint: disable=R0903, C0330, R0914, R0912, E04014u"""5 kernel-include6 ~~~~~~~~~~~~~~7 Implementation of the ``kernel-include`` reST-directive.8 :copyright: Copyright (C) 2016 Markus Heiser9 :license: GPL Version 2, June 1991 see linux/COPYING for details.10 The ``kernel-include`` reST-directive is a replacement for the ``include``11 directive. The ``kernel-include`` directive expand environment variables in12 the path name and allows to include files from arbitrary locations.13 .. hint::14 Including files from arbitrary locations (e.g. from ``/etc``) is a15 security risk for builders. This is why the ``include`` directive from16 docutils *prohibit* pathnames pointing to locations *above* the filesystem17 tree where the reST document with the include directive is placed.18 Substrings of the form $name or ${name} are replaced by the value of19 environment variable name. Malformed variable names and references to20 non-existing variables are left unchanged.21"""22# ==============================================================================23# imports24# ==============================================================================25import os.path26from docutils import io, nodes, statemachine27from docutils.utils.error_reporting import SafeString, ErrorString28from docutils.parsers.rst import directives29from docutils.parsers.rst.directives.body import CodeBlock, NumberLines30from docutils.parsers.rst.directives.misc import Include31__version__ = '1.0'32# ==============================================================================33def setup(app):34# ==============================================================================35 app.add_directive("kernel-include", KernelInclude)36 return dict(37 version = __version__,38 parallel_read_safe = True,39 parallel_write_safe = True40 )41# ==============================================================================42class KernelInclude(Include):43# ==============================================================================44 u"""KernelInclude (``kernel-include``) directive"""45 def run(self):46 path = os.path.realpath(47 os.path.expandvars(self.arguments[0]))48 # to get a bit security back, prohibit /etc:49 if path.startswith(os.sep + "etc"):50 raise self.severe(51 'Problems with "%s" directive, prohibited path: %s'52 % (self.name, path))53 self.arguments[0] = path54 #return super(KernelInclude, self).run() # won't work, see HINTs in _run()55 return self._run()56 def _run(self):57 """Include a file as part of the content of this reST file."""58 # HINT: I had to copy&paste the whole Include.run method. I'am not happy59 # with this, but due to security reasons, the Include.run method does60 # not allow absolute or relative pathnames pointing to locations *above*61 # the filesystem tree where the reST document is placed.62 if not self.state.document.settings.file_insertion_enabled:63 raise self.warning('"%s" directive disabled.' % self.name)64 source = self.state_machine.input_lines.source(65 self.lineno - self.state_machine.input_offset - 1)66 source_dir = os.path.dirname(os.path.abspath(source))67 path = directives.path(self.arguments[0])68 if path.startswith('<') and path.endswith('>'):69 path = os.path.join(self.standard_include_path, path[1:-1])70 path = os.path.normpath(os.path.join(source_dir, path))71 # HINT: this is the only line I had to change / commented out:72 #path = utils.relative_path(None, path)73 path = nodes.reprunicode(path)74 encoding = self.options.get(75 'encoding', self.state.document.settings.input_encoding)76 e_handler=self.state.document.settings.input_encoding_error_handler77 tab_width = self.options.get(78 'tab-width', self.state.document.settings.tab_width)79 try:80 self.state.document.settings.record_dependencies.add(path)81 include_file = io.FileInput(source_path=path,82 encoding=encoding,83 error_handler=e_handler)84 except UnicodeEncodeError as error:85 raise self.severe('Problems with "%s" directive path:\n'86 'Cannot encode input file path "%s" '87 '(wrong locale?).' %88 (self.name, SafeString(path)))89 except IOError as error:90 raise self.severe('Problems with "%s" directive path:\n%s.' %91 (self.name, ErrorString(error)))92 startline = self.options.get('start-line', None)93 endline = self.options.get('end-line', None)94 try:95 if startline or (endline is not None):96 lines = include_file.readlines()97 rawtext = ''.join(lines[startline:endline])98 else:99 rawtext = include_file.read()100 except UnicodeError as error:101 raise self.severe('Problem with "%s" directive:\n%s' %102 (self.name, ErrorString(error)))103 # start-after/end-before: no restrictions on newlines in match-text,104 # and no restrictions on matching inside lines vs. line boundaries105 after_text = self.options.get('start-after', None)106 if after_text:107 # skip content in rawtext before *and incl.* a matching text108 after_index = rawtext.find(after_text)109 if after_index < 0:110 raise self.severe('Problem with "start-after" option of "%s" '111 'directive:\nText not found.' % self.name)112 rawtext = rawtext[after_index + len(after_text):]113 before_text = self.options.get('end-before', None)114 if before_text:115 # skip content in rawtext after *and incl.* a matching text116 before_index = rawtext.find(before_text)117 if before_index < 0:118 raise self.severe('Problem with "end-before" option of "%s" '119 'directive:\nText not found.' % self.name)120 rawtext = rawtext[:before_index]121 include_lines = statemachine.string2lines(rawtext, tab_width,122 convert_whitespace=True)123 if 'literal' in self.options:124 # Convert tabs to spaces, if `tab_width` is positive.125 if tab_width >= 0:126 text = rawtext.expandtabs(tab_width)127 else:128 text = rawtext129 literal_block = nodes.literal_block(rawtext, source=path,130 classes=self.options.get('class', []))131 literal_block.line = 1132 self.add_name(literal_block)133 if 'number-lines' in self.options:134 try:135 startline = int(self.options['number-lines'] or 1)136 except ValueError:137 raise self.error(':number-lines: with non-integer '138 'start value')139 endline = startline + len(include_lines)140 if text.endswith('\n'):141 text = text[:-1]142 tokens = NumberLines([([], text)], startline, endline)143 for classes, value in tokens:144 if classes:145 literal_block += nodes.inline(value, value,146 classes=classes)147 else:148 literal_block += nodes.Text(value, value)149 else:150 literal_block += nodes.Text(text, text)151 return [literal_block]152 if 'code' in self.options:153 self.options['source'] = path154 codeblock = CodeBlock(self.name,155 [self.options.pop('code')], # arguments156 self.options,157 include_lines, # content158 self.lineno,159 self.content_offset,160 self.block_text,161 self.state,162 self.state_machine)163 return codeblock.run()164 self.state_machine.insert_input(include_lines, path)...
cdomain.py
Source:cdomain.py
1# -*- coding: utf-8; mode: python -*-2# pylint: disable=W0141,C0113,C0103,C03253u"""4 cdomain5 ~~~~~~~6 Replacement for the sphinx c-domain.7 :copyright: Copyright (C) 2016 Markus Heiser8 :license: GPL Version 2, June 1991 see Linux/COPYING for details.9 List of customizations:10 * Moved the *duplicate C object description* warnings for function11 declarations in the nitpicky mode. See Sphinx documentation for12 the config values for ``nitpick`` and ``nitpick_ignore``.13 * Add option 'name' to the "c:function:" directive. With option 'name' the14 ref-name of a function can be modified. E.g.::15 .. c:function:: int ioctl( int fd, int request )16 :name: VIDIOC_LOG_STATUS17 The func-name (e.g. ioctl) remains in the output but the ref-name changed18 from 'ioctl' to 'VIDIOC_LOG_STATUS'. The function is referenced by::19 * :c:func:`VIDIOC_LOG_STATUS` or20 * :any:`VIDIOC_LOG_STATUS` (``:any:`` needs sphinx 1.3)21 * Handle signatures of function-like macros well. Don't try to deduce22 arguments types of function-like macros.23"""24from docutils import nodes25from docutils.parsers.rst import directives26import sphinx27from sphinx import addnodes28from sphinx.domains.c import c_funcptr_sig_re, c_sig_re29from sphinx.domains.c import CObject as Base_CObject30from sphinx.domains.c import CDomain as Base_CDomain31__version__ = '1.0'32# Get Sphinx version33major, minor, patch = sphinx.version_info[:3]34def setup(app):35 app.override_domain(CDomain)36 return dict(37 version = __version__,38 parallel_read_safe = True,39 parallel_write_safe = True40 )41class CObject(Base_CObject):42 """43 Description of a C language object.44 """45 option_spec = {46 "name" : directives.unchanged47 }48 def handle_func_like_macro(self, sig, signode):49 u"""Handles signatures of function-like macros.50 If the objtype is 'function' and the the signature ``sig`` is a51 function-like macro, the name of the macro is returned. Otherwise52 ``False`` is returned. """53 if not self.objtype == 'function':54 return False55 m = c_funcptr_sig_re.match(sig)56 if m is None:57 m = c_sig_re.match(sig)58 if m is None:59 raise ValueError('no match')60 rettype, fullname, arglist, _const = m.groups()61 arglist = arglist.strip()62 if rettype or not arglist:63 return False64 arglist = arglist.replace('`', '').replace('\\ ', '') # remove markup65 arglist = [a.strip() for a in arglist.split(",")]66 # has the first argument a type?67 if len(arglist[0].split(" ")) > 1:68 return False69 # This is a function-like macro, it's arguments are typeless!70 signode += addnodes.desc_name(fullname, fullname)71 paramlist = addnodes.desc_parameterlist()72 signode += paramlist73 for argname in arglist:74 param = addnodes.desc_parameter('', '', noemph=True)75 # separate by non-breaking space in the output76 param += nodes.emphasis(argname, argname)77 paramlist += param78 return fullname79 def handle_signature(self, sig, signode):80 """Transform a C signature into RST nodes."""81 fullname = self.handle_func_like_macro(sig, signode)82 if not fullname:83 fullname = super(CObject, self).handle_signature(sig, signode)84 if "name" in self.options:85 if self.objtype == 'function':86 fullname = self.options["name"]87 else:88 # FIXME: handle :name: value of other declaration types?89 pass90 return fullname91 def add_target_and_index(self, name, sig, signode):92 # for C API items we add a prefix since names are usually not qualified93 # by a module name and so easily clash with e.g. section titles94 targetname = 'c.' + name95 if targetname not in self.state.document.ids:96 signode['names'].append(targetname)97 signode['ids'].append(targetname)98 signode['first'] = (not self.names)99 self.state.document.note_explicit_target(signode)100 inv = self.env.domaindata['c']['objects']101 if (name in inv and self.env.config.nitpicky):102 if self.objtype == 'function':103 if ('c:func', name) not in self.env.config.nitpick_ignore:104 self.state_machine.reporter.warning(105 'duplicate C object description of %s, ' % name +106 'other instance in ' + self.env.doc2path(inv[name][0]),107 line=self.lineno)108 inv[name] = (self.env.docname, self.objtype)109 indextext = self.get_index_text(name)110 if indextext:111 if major == 1 and minor < 4:112 # indexnode's tuple changed in 1.4113 # https://github.com/sphinx-doc/sphinx/commit/e6a5a3a92e938fcd75866b4227db9e0524d58f7c114 self.indexnode['entries'].append(115 ('single', indextext, targetname, ''))116 else:117 self.indexnode['entries'].append(118 ('single', indextext, targetname, '', None))119class CDomain(Base_CDomain):120 """C language domain."""121 name = 'c'122 label = 'C'123 directives = {124 'function': CObject,125 'member': CObject,126 'macro': CObject,127 'type': CObject,128 'var': CObject,...
unwcheck.py
Source:unwcheck.py
1#!/usr/bin/python2# SPDX-License-Identifier: GPL-2.03#4# Usage: unwcheck.py FILE5#6# This script checks the unwind info of each function in file FILE7# and verifies that the sum of the region-lengths matches the total8# length of the function.9#10# Based on a shell/awk script originally written by Harish Patil,11# which was converted to Perl by Matthew Chapman, which was converted12# to Python by David Mosberger.13#14import os15import re16import sys17if len(sys.argv) != 2:18 print("Usage: %s FILE" % sys.argv[0])19 sys.exit(2)20readelf = os.getenv("READELF", "readelf")21start_pattern = re.compile("<([^>]*)>: \[0x([0-9a-f]+)-0x([0-9a-f]+)\]")22rlen_pattern = re.compile(".*rlen=([0-9]+)")23def check_func (func, slots, rlen_sum):24 if slots != rlen_sum:25 global num_errors26 num_errors += 127 if not func: func = "[%#x-%#x]" % (start, end)28 print("ERROR: %s: %lu slots, total region length = %lu" % (func, slots, rlen_sum))29 return30num_funcs = 031num_errors = 032func = False33slots = 034rlen_sum = 035for line in os.popen("%s -u %s" % (readelf, sys.argv[1])):36 m = start_pattern.match(line)37 if m:38 check_func(func, slots, rlen_sum)39 func = m.group(1)40 start = int(m.group(2), 16)41 end = int(m.group(3), 16)42 slots = 3 * (end - start) / 1643 rlen_sum = 044 num_funcs += 145 else:46 m = rlen_pattern.match(line)47 if m:48 rlen_sum += int(m.group(1))49check_func(func, slots, rlen_sum)50if num_errors == 0:51 print("No errors detected in %u functions." % num_funcs)52else:53 if num_errors > 1:54 err="errors"55 else:56 err="error"57 print("%u %s detected in %u functions." % (num_errors, err, num_funcs))...
cxacru-cf.py
Source:cxacru-cf.py
1#!/usr/bin/env python2# Copyright 2009 Simon Arlott3#4# This program is free software; you can redistribute it and/or modify it5# under the terms of the GNU General Public License as published by the Free6# Software Foundation; either version 2 of the License, or (at your option)7# any later version.8#9# This program is distributed in the hope that it will be useful, but WITHOUT10# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for12# more details.13#14# You should have received a copy of the GNU General Public License along with15# this program; if not, write to the Free Software Foundation, Inc., 5916# Temple Place - Suite 330, Boston, MA 02111-1307, USA.17#18# Usage: cxacru-cf.py < cxacru-cf.bin19# Output: values string suitable for the sysfs adsl_config attribute20#21# Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f11770211022# contains mis-aligned values which will stop the modem from being able23# to make a connection. If the first and last two bytes are removed then24# the values become valid, but the modulation will be forced to ANSI25# T1.413 only which may not be appropriate.26#27# The original binary format is a packed list of le32 values.28import sys29import struct30i = 031while True:32 buf = sys.stdin.read(4)33 if len(buf) == 0:34 break35 elif len(buf) != 4:36 sys.stdout.write("\n")37 sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf)))38 sys.exit(1)39 if i > 0:40 sys.stdout.write(" ")41 sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0]))42 i += 1...
load_config.py
Source:load_config.py
1# -*- coding: utf-8; mode: python -*-2# pylint: disable=R0903, C0330, R0914, R0912, E04013import os4import sys5from sphinx.util.pycompat import execfile_6# ------------------------------------------------------------------------------7def loadConfig(namespace):8# ------------------------------------------------------------------------------9 u"""Load an additional configuration file into *namespace*.10 The name of the configuration file is taken from the environment11 ``SPHINX_CONF``. The external configuration file extends (or overwrites) the12 configuration values from the origin ``conf.py``. With this you are able to13 maintain *build themes*. """14 config_file = os.environ.get("SPHINX_CONF", None)15 if (config_file is not None16 and os.path.normpath(namespace["__file__"]) != os.path.normpath(config_file) ):17 config_file = os.path.abspath(config_file)18 if os.path.isfile(config_file):19 sys.stdout.write("load additional sphinx-config: %s\n" % config_file)20 config = namespace.copy()21 config['__file__'] = config_file22 execfile_(config_file, config)23 del config['__file__']24 namespace.update(config)25 else:...
kernellog.py
Source:kernellog.py
1# SPDX-License-Identifier: GPL-2.02#3# Sphinx has deprecated its older logging interface, but the replacement4# only goes back to 1.6. So here's a wrapper layer to keep around for5# as long as we support 1.4.6#7import sphinx8if sphinx.__version__[:3] >= '1.6':9 UseLogging = True10 from sphinx.util import logging11 logger = logging.getLogger('kerneldoc')12else:13 UseLogging = False14def warn(app, message):15 if UseLogging:16 logger.warning(message)17 else:18 app.warn(message)19def verbose(app, message):20 if UseLogging:21 logger.verbose(message)22 else:...
conf.py
Source:conf.py
1# -*- coding: utf-8; mode: python -*-2project = "Linux Networking Documentation"3tags.add("subproject")4latex_documents = [5 ('index', 'networking.tex', project,6 'The kernel development community', 'manual'),...
Using AI Code Generation
1const { b } = require('fast-check');2console.log(b());3const { c } = require('fast-check');4console.log(c());5const { d } = require('fast-check');6console.log(d());7const { e } = require('fast-check');8console.log(e());9const { f } = require('fast-check');10console.log(f());11const { g } = require('fast-check');12console.log(g());13const { h } = require('fast-check');14console.log(h());15const { i } = require('fast-check');16console.log(i());17const { j } = require('fast-check');18console.log(j());19const { k } = require('fast-check');20console.log(k());21const { l } = require('fast-check');22console.log(l());23const { m } = require('fast-check');24console.log(m());25const { n } = require('fast-check');26console.log(n());27const { o } = require('fast-check');28console.log(o());29const { p } = require('fast-check');30console.log(p());
Using AI Code Generation
1const { b } = require('fast-check-monorepo');2console.log('b: ', b());3const { c } = require('fast-check-monorepo');4console.log('c: ', c());5const { d } = require('fast-check-monorepo');6console.log('d: ', d());7const { e } = require('fast-check-monorepo');8console.log('e: ', e());9const { f } = require('fast-check-monorepo');10console.log('f: ', f());11const { g } = require('fast-check-monorepo');12console.log('g: ', g());13const { h } = require('fast-check-monorepo');14console.log('h: ', h());15const { i } = require('fast-check-monorepo');16console.log('i: ', i());17const { j } = require('fast-check-monorepo');18console.log('j: ', j());19const { k } = require('fast-check-monorepo');20console.log('k: ', k());21const { l } = require('fast-check-monorepo');22console.log('l: ', l());23const { m } = require('fast-check-monorepo');24console.log('m: ', m());25const { n } = require
Using AI Code Generation
1const b = require('fast-check-monorepo/b.js');2console.log(b);3const c = require('fast-check-monorepo/c.js');4console.log(c);5const d = require('fast-check-monorepo/d.js');6console.log(d);7const e = require('fast-check-monorepo/e.js');8console.log(e);9const f = require('fast-check-monorepo/f.js');10console.log(f);11const g = require('fast-check-monorepo/g.js');12console.log(g);13const h = require('fast-check-monorepo/h.js');14console.log(h);15const i = require('fast-check-monorepo/i.js');16console.log(i);17const j = require('fast-check-monorepo/j.js');18console.log(j);19const k = require('fast-check-monorepo/k.js');20console.log(k);21const l = require('fast-check-monorepo/l.js');22console.log(l);23const m = require('fast-check-monorepo/m.js');24console.log(m);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!