Make images and enter them in Sphinx's output writer
433948
def env_updated(self,
                    kb_app,
                    sphinx_app: Sphinx,
                    sphinx_env: BuildEnvironment,
                    resource
                    ):
        

        docname = resource.docname
        srcdir = sphinx_app.env.srcdir
        source_imgpath = self.source_filename(docname, srcdir)

        # Copy the image to the Sphinx build directory
        build_dir = sphinx_app.outdir
        docpath = Path(docname)
        parent = docpath.parent
        target_imgpath = str(Path(build_dir, parent, self.filename))

        # Does the target dir exist yet in the build dir? Probably not. If
        # not, make it
        target_dir = Path(build_dir, parent)
        if not target_dir.exists():
            target_dir.mkdir(parents=True, exist_ok=True)

        shutil.copy(source_imgpath, target_imgpath)
515457
def setup(app):
    
    app.add_config_value('sphinxmark_enable', False, 'html')
    app.add_config_value('sphinxmark_div', 'default', 'html')
    app.add_config_value('sphinxmark_border', None, 'html')
    app.add_config_value('sphinxmark_repeat', True, 'html')
    app.add_config_value('sphinxmark_fixed', False, 'html')
    app.add_config_value('sphinxmark_image', 'default', 'html')
    app.add_config_value('sphinxmark_text', 'default', 'html')
    app.add_config_value('sphinxmark_text_color', (255, 0, 0), 'html')
    app.add_config_value('sphinxmark_text_size', 100, 'html')
    app.add_config_value('sphinxmark_text_width', 1000, 'html')
    app.add_config_value('sphinxmark_text_opacity', 20, 'html')
    app.add_config_value('sphinxmark_text_spacing', 400, 'html')
    app.add_config_value('sphinxmark_text_rotation', 0, 'html')
    app.connect('env-updated', watermark)

    return {
        'version': '0.1.18',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
388493
def _on_sphinx_thread_html_ready(self, html_text):
        """"""
        self._sphinx_thread.wait()
        self.set_rich_text_html(html_text, QUrl.fromLocalFile(self.css_path))
897338
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions):
  """"""
  # load MNIST gzip into memory
  with open(input_images, 'rb') as f:
    images = numpy.array(mnist.extract_images(f))

  with open(input_labels, 'rb') as f:
    if format == "csv2":
      labels = numpy.array(mnist.extract_labels(f, one_hot=False))
    else:
      labels = numpy.array(mnist.extract_labels(f, one_hot=True))

  shape = images.shape
  print("images.shape: {0}".format(shape))          # 60000 x 28 x 28
  print("labels.shape: {0}".format(labels.shape))   # 60000 x 10

  # create RDDs of vectors
  imageRDD = sc.parallelize(images.reshape(shape[0], shape[1] * shape[2]), num_partitions)
  labelRDD = sc.parallelize(labels, num_partitions)

  output_images = output + "/images"
  output_labels = output + "/labels"

  # save RDDs as specific format
  if format == "pickle":
    imageRDD.saveAsPickleFile(output_images)
    labelRDD.saveAsPickleFile(output_labels)
  elif format == "csv":
    imageRDD.map(toCSV).saveAsTextFile(output_images)
    labelRDD.map(toCSV).saveAsTextFile(output_labels)
  elif format == "csv2":
    imageRDD.map(toCSV).zip(labelRDD).map(lambda x: str(x[1]) + "|" + x[0]).saveAsTextFile(output)
  else:  # format == "tfr":
    tfRDD = imageRDD.zip(labelRDD).map(lambda x: (bytearray(toTFExample(x[0], x[1])), None))
    # requires: --jars tensorflow-hadoop-1.0-SNAPSHOT.jar
    tfRDD.saveAsNewAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileOutputFormat",
                                 keyClass="org.apache.hadoop.io.BytesWritable",
                                 valueClass="org.apache.hadoop.io.NullWritable")
372922
def write(models, out=None, base=None, propertybase=None, shorteners=None, logger=logging):
    '''
    
    '''
    assert out is not None #Output stream required
    if not isinstance(models, list): models = [models]
    shorteners = shorteners or {}

    all_propertybase = [propertybase] if propertybase else []
    all_propertybase.append(VERSA_BASEIRI)

    if any((base, propertybase, shorteners)):
        out.write('# @docheader\n\n* @iri:\n')
    if base:
        out.write('    * @base: {0}'.format(base))
    #for k, v in shorteners:
    #    out.write('    * @base: {0}'.format(base))

    out.write('\n\n')

    origin_space = set()
    #base_out = models[0].base
    for m in models:
        origin_space.update(all_origins(m))

    for o in origin_space:
        out.write('# {0}\n\n'.format(o))
        for o_, r, t, a in m.match(o):
            abbr_r = abbreviate(r, all_propertybase)
            value_format(t)
            out.write('* {0}: {1}\n'.format(abbr_r, value_format(t)))
            for k, v in a.items():
                abbr_k = abbreviate(k, all_propertybase)
                out.write('    * {0}: {1}\n'.format(k, value_format(v)))

        out.write('\n')
    return
40317
def tobinary(images, path, prefix="image", overwrite=False, credentials=None):
    
    from thunder.writers import get_parallel_writer

    def tobuffer(kv):
        key, img = kv
        fname = prefix + "-" + "%05d.bin" % int(key)
        return fname, img.copy()

    writer = get_parallel_writer(path)(path, overwrite=overwrite, credentials=credentials)
    images.foreach(lambda x: writer.write(tobuffer(x)))
    config(path, list(images.value_shape), images.dtype, overwrite=overwrite)
141343
def write(self)->None:
        ""
        orig_images, gen_images, real_images = self._get_image_tensors()
        self._write_images(name='orig images', images=orig_images)
        self._write_images(name='gen images',  images=gen_images)
        self._write_images(name='real images', images=real_images)
1038643
def sphinx_extension(app, exception):
    ""
    if not app.builder.name in ("html", "dirhtml"):
        return

    if not app.config.sphinx_to_github:
        if app.config.sphinx_to_github_verbose:
            print("Sphinx-to-github: Disabled, doing nothing.")
        return

    if exception:
        if app.config.sphinx_to_github_verbose:
            print("Sphinx-to-github: Exception raised in main build, doing nothing.")
        return

    dir_helper = DirHelper(
            os.path.isdir,
            os.listdir,
            os.walk,
            shutil.rmtree
            )

    file_helper = FileSystemHelper(
            open,
            os.path.join,
            shutil.move,
            os.path.exists
            )

    operations_factory = OperationsFactory()
    handler_factory = HandlerFactory()

    layout_factory = LayoutFactory(
            operations_factory,
            handler_factory,
            file_helper,
            dir_helper,
            app.config.sphinx_to_github_verbose,
            sys.stdout,
            force=True
            )

    layout = layout_factory.create_layout(app.outdir)
    layout.process()
1014324
def write(output, opts = {})
      output_path = parse_input(output, false)

      FileUtils.copy_file(path, output_path) unless requires_output_file?

      command = build_command(output_path)
      run(command, opts)
      GraphicsMagick::Image.new(output_path)
    end
981576
def latex2png(snippet, outfile):
    """"""
    pngimage = os.path.join(IMAGEDIR, outfile + '.png')
    texdocument = os.path.join(IMAGEDIR, 'tmp.tex')
    with open(texdocument, 'w') as doc:
        doc.write(LATEX_DOC % (snippet))
    environment = os.environ
    environment['shell_escape_commands'] = \
        "bibtex,bibtex8,kpsewhich,makeindex,mpost,repstopdf," + \
        ','.join(
            os.path.basename(n) for n in chain.from_iterable(
                iglob(os.path.join(chemin, 'gregorio*'))
                for chemin in os.environ["PATH"].split(os.pathsep)
            )
        )
    proc = Popen(
        ["lualatex", '-output-directory=' + IMAGEDIR, texdocument],
        stdin=PIPE,
        stdout=STDERR,
        env=environment
    )
    proc.communicate()
    proc.stdin.close()
    call(["pdfcrop", os.path.join(IMAGEDIR, "tmp.pdf")], stdout=STDERR)
    call(
        [
            "gs",
            "-sDEVICE=pngalpha",
            "-r144",
            "-sOutputFile=" + pngimage,
            os.path.join(IMAGEDIR, "tmp-crop.pdf"),
        ],
        stdout=STDERR,
    )
1086512
def python_to_jupyter_cli(args=None, namespace=None):
    
    from . import gen_gallery  # To avoid circular import
    parser = argparse.ArgumentParser(
        description='Sphinx-Gallery Notebook converter')
    parser.add_argument('python_src_file', nargs='+',
                        help='Input Python file script to convert. '
                        'Supports multiple files and shell wildcards'
                        ' (e.g. *.py)')
    args = parser.parse_args(args, namespace)

    for src_file in args.python_src_file:
        file_conf, blocks = split_code_and_text_blocks(src_file)
        print('Converting {0}'.format(src_file))
        gallery_conf = copy.deepcopy(gen_gallery.DEFAULT_GALLERY_CONF)
        example_nb = jupyter_notebook(blocks, gallery_conf)
        save_notebook(example_nb, replace_py_ipynb(src_file))
1126262
def write!(opts = {})
      if requires_output_file?
        raise NoMethodError, "You cannot use Image#write(output) with "\
                             "the #{current_utility} command"
      end

      command = build_command(path)
      run(command, opts)
      self
    end
886399
def write_notebook_rst(txt, res, fnm, pth):
    

    # Extended filename used for output images
    extfnm = fnm + '_files'
    # Directory into which output images are written
    extpth = os.path.join(pth, extfnm)
    # Make output image directory if it doesn't exist
    mkdir(extpth)
    # Iterate over output images in resources dict
    for r in res['outputs'].keys():
        # New name for current output image
        rnew = re.sub('output', fnm, r)
        # Partial path for current output image
        rpth = os.path.join(extfnm, rnew)
        # In RST text, replace old output name with the new one
        txt = re.sub('\.\. image:: ' + r, '.. image:: ' + rpth, txt, re.M)
        # Full path of the current output image
        fullrpth = os.path.join(pth, rpth)
        # Write the current output image to disk
        with open(fullrpth, 'wb') as fo:
            fo.write(res['outputs'][r])

    # Remove trailing whitespace in RST text
    txt = re.sub(r'[ \t]+$', '', txt, flags=re.M)

    # Write RST text to disk
    with open(os.path.join(pth, fnm + '.rst'), 'wt') as fo:
        fo.write(txt)
325097
def docs(context, builder='html'):
    ""
    cmdline = 'python -msphinx -M {} {} {} {}'.format(builder, DOCS_SRCDIR, DOCS_BUILDDIR, SPHINX_OPTS)
    context.run(cmdline)
833043
def build(
    c,
    clean=False,
    browse=False,
    nitpick=False,
    opts=None,
    source=None,
    target=None,
):
    
    if clean:
        _clean(c)
    if opts is None:
        opts = ""
    if nitpick:
        opts += " -n -W -T"
    cmd = "sphinx-build{0} {1} {2}".format(
        (" " + opts) if opts else "",
        source or c.sphinx.source,
        target or c.sphinx.target,
    )
    c.run(cmd, pty=True)
    if browse:
        _browse(c)
983739
def _write_images(self, name:str, images:[Tensor])->None:
        ""
        tag = self.ds_type.name + ' ' + name
        self.tbwriter.add_image(tag=tag, img_tensor=vutils.make_grid(images, normalize=True), global_step=self.iteration)
351692
def build(ctx, builder="html", options=""):
    """"""
    sourcedir = ctx.config.sphinx.sourcedir
    destdir = Path(ctx.config.sphinx.destdir or "build")/builder
    destdir = destdir.abspath()
    with cd(sourcedir):
        destdir_relative = Path(".").relpathto(destdir)
        command = "sphinx-build {opts} -b {builder} {sourcedir} {destdir}" \
                    .format(builder=builder, sourcedir=".",
                            destdir=destdir_relative, opts=options)
        ctx.run(command)