当前位置: 首页>>代码示例>>Python>>正文


Python v4.new_markdown_cell函数代码示例

本文整理汇总了Python中nbformat.v4.new_markdown_cell函数的典型用法代码示例。如果您正苦于以下问题:Python new_markdown_cell函数的具体用法?Python new_markdown_cell怎么用?Python new_markdown_cell使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了new_markdown_cell函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_sec_label

def add_sec_label(cell: NotebookNode, nbname) -> Sequence[NotebookNode]:
    """Adds a Latex \\label{} under the chapter heading.

    This takes the first cell of a notebook, and expects it to be a Markdown
    cell starting with a level 1 heading. It inserts a label with the notebook
    name just underneath this heading.
    """
    assert cell.cell_type == 'markdown', cell.cell_type
    lines = cell.source.splitlines()
    if lines[0].startswith('# '):
        header_lines = 1
    elif len(lines) > 1 and lines[1].startswith('==='):
        header_lines = 2
    else:
        raise NoHeader

    header = '\n'.join(lines[:header_lines])
    intro_remainder = '\n'.join(lines[header_lines:]).strip()
    res = [
        new_markdown_cell(header),
        new_latex_cell('\label{sec:%s}' % nbname)
    ]
    res[0].metadata = cell.metadata
    if intro_remainder:
        res.append(new_markdown_cell(intro_remainder))
    return res
开发者ID:takluyver,项目名称:bookbook,代码行数:26,代码来源:latex.py

示例2: test_preprocessor_collapsible_headings

def test_preprocessor_collapsible_headings():
    """Test collapsible_headings preprocessor."""
    # check import shortcut
    from jupyter_contrib_nbextensions.nbconvert_support import CollapsibleHeadingsPreprocessor  # noqa
    cells = []
    for lvl in range(6, 1, -1):
        for collapsed in (True, False):
            cells.extend([
                nbf.new_markdown_cell(
                    source='{} {} heading level {}'.format(
                        '#' * lvl,
                        'Collapsed' if collapsed else 'Uncollapsed',
                        lvl),
                    metadata={'heading_collapsed': True} if collapsed else {}),
                nbf.new_markdown_cell(source='\n'.join([
                    'want hidden' if collapsed else 'want to see',
                    'what I mean',
                ])),
                nbf.new_code_cell(source='\n'.join([
                    'want hidden' if collapsed else 'want to see',
                    'what I mean',
                ])),
            ])
    notebook_node = nbf.new_notebook(cells=cells)
    body, resources = export_through_preprocessor(
        notebook_node, CollapsibleHeadingsPreprocessor, RSTExporter, 'rst')
    assert_not_in('hidden', body, 'check text hidden by collapsed headings')
    assert_in('want to see', body, 'check for text under uncollapsed headings')
开发者ID:flipphillips,项目名称:IPython-notebook-extensions,代码行数:28,代码来源:test_preprocessors.py

示例3: test_html_collapsible_headings

 def test_html_collapsible_headings(self):
     """Test exporter for inlining collapsible_headings"""
     nb = v4.new_notebook(cells=[
         v4.new_markdown_cell(source=('# level 1 heading')),
         v4.new_code_cell(source='a = range(1,10)'),
         v4.new_markdown_cell(source=('## level 2 heading')),
         v4.new_code_cell(source='a = range(1,10)'),
         v4.new_markdown_cell(source=('### level 3 heading')),
         v4.new_code_cell(source='a = range(1,10)'),
     ])
     self.check_stuff_gets_embedded(
         nb, 'html_ch', to_be_included=['collapsible_headings'])
开发者ID:hagne,项目名称:IPython-notebook-extensions,代码行数:12,代码来源:test_exporters.py

示例4: test_html_collapsible_headings

    def test_html_collapsible_headings(self):
        """Test exporter for inlining collapsible_headings"""
        nb = v4.new_notebook(cells=[
            v4.new_markdown_cell(source=('# level 1 heading')),
            v4.new_code_cell(source='a = range(1,10)'),
            v4.new_markdown_cell(source=('## level 2 heading')),
            v4.new_code_cell(source='a = range(1,10)'),
            v4.new_markdown_cell(source=('### level 3 heading')),
            v4.new_code_cell(source='a = range(1,10)'),
        ])

        def check(byte_string, root_node):
            assert b'collapsible_headings' in byte_string

        self.check_html(nb, 'html_ch', check_func=check)
开发者ID:codegenerator-tools,项目名称:jupyter_contrib_nbextensions,代码行数:15,代码来源:test_exporters.py

示例5: build_notebook

    def build_notebook(self):
        """Build a reveal slides notebook in memory for use with tests.
        Overrides base in PreprocessorTestsBase"""

        outputs = [nbformat.new_output(output_type="stream", name="stdout", text="a")]

        slide_metadata = {'slideshow' : {'slide_type': 'slide'}}
        subslide_metadata = {'slideshow' : {'slide_type': 'subslide'}}

        cells=[nbformat.new_code_cell(source="", execution_count=1, outputs=outputs),
               nbformat.new_markdown_cell(source="", metadata=slide_metadata),
               nbformat.new_code_cell(source="", execution_count=2, outputs=outputs),
               nbformat.new_markdown_cell(source="", metadata=slide_metadata),
               nbformat.new_markdown_cell(source="", metadata=subslide_metadata)]

        return nbformat.new_notebook(cells=cells)
开发者ID:alope107,项目名称:nbconvert,代码行数:16,代码来源:test_revealhelp.py

示例6: test_very_long_cells

    def test_very_long_cells(self):
        """
        Torture test that long cells do not cause issues
        """
        lorem_ipsum_text = textwrap.dedent("""\
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec
          dignissim, ipsum non facilisis tempus, dui felis tincidunt metus,
          nec pulvinar neque odio eget risus. Nulla nisi lectus, cursus
          suscipit interdum at, ultrices sit amet orci. Mauris facilisis
          imperdiet elit, vitae scelerisque ipsum dignissim non. Integer
          consequat malesuada neque sit amet pulvinar. Curabitur pretium
          ut turpis eget aliquet. Maecenas sagittis lacus sed lectus
          volutpat, eu adipiscing purus pulvinar. Maecenas consequat
          luctus urna, eget cursus quam mollis a. Aliquam vitae ornare
          erat, non hendrerit urna. Sed eu diam nec massa egestas pharetra
          at nec tellus. Fusce feugiat lacus quis urna sollicitudin volutpat.
          Quisque at sapien non nibh feugiat tempus ac ultricies purus.
           """)
        lorem_ipsum_text = lorem_ipsum_text.replace("\n"," ") + "\n\n"
        large_lorem_ipsum_text = "".join([lorem_ipsum_text]*3000)

        notebook_name = "lorem_ipsum_long.ipynb"
        nb = v4.new_notebook(
            cells=[
                    v4.new_markdown_cell(source=large_lorem_ipsum_text)
            ]
        )

        with TemporaryDirectory() as td:
            nbfile = os.path.join(td, notebook_name)
            with open(nbfile, 'w') as f:
                write(nb, f, 4)

            (output, resources) = LatexExporter(template_file='article').from_filename(nbfile)
            assert len(output) > 0
开发者ID:jhamrick,项目名称:nbconvert,代码行数:35,代码来源:test_latex.py

示例7: test_checkpoints_follow_file

    def test_checkpoints_follow_file(self):

        # Read initial file state
        orig = self.api.read('foo/a.ipynb')

        # Create a checkpoint of initial state
        r = self.api.new_checkpoint('foo/a.ipynb')
        cp1 = r.json()

        # Modify file and save
        nbcontent = json.loads(orig.text)['content']
        nb = from_dict(nbcontent)
        hcell = new_markdown_cell('Created by test')
        nb.cells.append(hcell)
        nbmodel = {'content': nb, 'type': 'notebook'}
        self.api.save('foo/a.ipynb', body=json.dumps(nbmodel))

        # Rename the file.
        self.api.rename('foo/a.ipynb', 'foo/z.ipynb')

        # Looking for checkpoints in the old location should yield no results.
        self.assertEqual(self.api.get_checkpoints('foo/a.ipynb').json(), [])

        # Looking for checkpoints in the new location should work.
        cps = self.api.get_checkpoints('foo/z.ipynb').json()
        self.assertEqual(cps, [cp1])

        # Delete the file.  The checkpoint should be deleted as well.
        self.api.delete('foo/z.ipynb')
        cps = self.api.get_checkpoints('foo/z.ipynb').json()
        self.assertEqual(cps, [])
开发者ID:drastorguev,项目名称:pythondojo,代码行数:31,代码来源:test_contents_api.py

示例8: add_statistics

def add_statistics(plan, file):
    cells = [nbf.new_markdown_cell('# Viajes correctos vs Incidencias\n## Se reportaron viajes para el plan: {}'.format(plan)),
             nbf.new_code_cell('show(f)'),
             nbf.new_code_cell('msj_estadisticaplan(\'{}\', viajes)'.format(plan)),
             nbf.new_markdown_cell('# Plan {} de distribución (Sin Modificaciones)'.format(plan)),
             nbf.new_code_cell('an.getkm(\'plan\', \'{}\')'.format(plan)),
             nbf.new_code_cell('geojsonio.embed(an.gettrips(\'plan\', \'{}\').to_geojson())'.format(plan)),
             nbf.new_markdown_cell('# Plan {} Modificado'.format(plan)),
             nbf.new_code_cell('an.getkm(\'planm\', \'{}\')'.format(plan)),
             nbf.new_code_cell('geojsonio.embed(an.gettrips(\'planm\', \'{}\').to_geojson())'.format(plan)),
            ]
    noto = json.load(open(file))
    noto['cells'] = noto['cells'] + cells

    with open(file, 'w') as f:
        json.dump(noto, f)
开发者ID:aretesw,项目名称:slides-viernes,代码行数:16,代码来源:misc.py

示例9: setUp

    def setUp(self):
        nbdir = self.notebook_dir
        
        if not os.path.isdir(pjoin(nbdir, 'foo')):
            subdir = pjoin(nbdir, 'foo')

            os.mkdir(subdir)

            # Make sure that we clean this up when we're done.
            # By using addCleanup this will happen correctly even if we fail
            # later in setUp.
            @self.addCleanup
            def cleanup_dir():
                shutil.rmtree(subdir, ignore_errors=True)

        nb = new_notebook()
        
        nb.cells.append(new_markdown_cell(u'Created by test ³'))
        cc1 = new_code_cell(source=u'print(2*6)')
        cc1.outputs.append(new_output(output_type="stream", text=u'12'))
        cc1.outputs.append(new_output(output_type="execute_result",
            data={'image/png' : png_green_pixel},
            execution_count=1,
        ))
        nb.cells.append(cc1)
        
        with io.open(pjoin(nbdir, 'foo', 'testnb.ipynb'), 'w',
                     encoding='utf-8') as f:
            write(nb, f, version=4)

        self.nbconvert_api = NbconvertAPI(self.request)
开发者ID:BarnetteME1,项目名称:DnD-stuff,代码行数:31,代码来源:test_nbconvert_handlers.py

示例10: build_notebook

    def build_notebook(self, with_json_outputs=False):
        """Build a notebook in memory for use with preprocessor tests"""

        outputs = [
            nbformat.new_output("stream", name="stdout", text="a"),
            nbformat.new_output("display_data", data={'text/plain': 'b'}),
            nbformat.new_output("stream", name="stdout", text="c"),
            nbformat.new_output("stream", name="stdout", text="d"),
            nbformat.new_output("stream", name="stderr", text="e"),
            nbformat.new_output("stream", name="stderr", text="f"),
            nbformat.new_output("display_data", data={'image/png': 'Zw=='}), # g
            nbformat.new_output("display_data", data={'application/pdf': 'aA=='}), # h
        ]
        if with_json_outputs:
            outputs.extend([
                nbformat.new_output(
                    "display_data", data={'application/json': [1, 2, 3]}
                ), # j
                nbformat.new_output(
                    "display_data", data={'application/json': {'a': 1, 'c': {'b': 2}}}
                ), # k
                nbformat.new_output(
                    "display_data", data={'application/json': 'abc'}
                ), # l
                nbformat.new_output(
                    "display_data", data={'application/json': 15.03}
                ), # m
            ])

        cells=[nbformat.new_code_cell(source="$ e $", execution_count=1, outputs=outputs),
               nbformat.new_markdown_cell(source="$ e $")]

        return nbformat.new_notebook(cells=cells)
开发者ID:jupyter,项目名称:nbconvert,代码行数:33,代码来源:base.py

示例11: test_htmltoc2

 def test_htmltoc2(self):
     """Test exporter for adding table of contents"""
     nb = v4.new_notebook(cells=[
         v4.new_code_cell(source="a = 'world'"),
         v4.new_markdown_cell(source="# Heading"),
     ])
     self.check_stuff_gets_embedded(
         nb, 'html_toc', to_be_included=['toc2'])
开发者ID:hagne,项目名称:IPython-notebook-extensions,代码行数:8,代码来源:test_exporters.py

示例12: add_markdown_cell

    def add_markdown_cell(self, path):
        # Load and update
        model = self.contents.get(path=path)
        model['content'].cells.append(
            new_markdown_cell('Created by test: ' + path)
        )

        # Save and checkpoint again.
        self.contents.save(model, path=path)
        return model
开发者ID:pl31,项目名称:pgcontents,代码行数:10,代码来源:test_synchronization.py

示例13: test_embedhtml

 def test_embedhtml(self):
     """Test exporter for embedding images into HTML"""
     nb = v4.new_notebook(cells=[
         v4.new_code_cell(source="a = 'world'"),
         v4.new_markdown_cell(
             source="![testimage]({})".format(path_in_data('icon.png'))
         ),
     ])
     self.check_stuff_gets_embedded(
         nb, 'html_embed', to_be_included=['base64'])
开发者ID:hagne,项目名称:IPython-notebook-extensions,代码行数:10,代码来源:test_exporters.py

示例14: test_htmltoc2

    def test_htmltoc2(self):
        """Test exporter for adding table of contents"""
        with self.create_temp_cwd():
            nb = v4.new_notebook(
                cells=[v4.new_code_cell(source="a = 'world'"), v4.new_markdown_cell(source="# Heading")]
            )
            with io.open("notebook2.ipynb", "w", encoding="utf-8") as f:
                write(nb, f, 4)

            self.nbconvert("--to html_toc" ' "notebook2"')
            assert os.path.isfile("notebook2.html")
开发者ID:juhasch,项目名称:IPython-notebook-extensions,代码行数:11,代码来源:test_exporters.py

示例15: build_notebook

    def build_notebook(self):
        notebook = super(TestRegexRemove, self).build_notebook()
        # Add a few empty cells
        notebook.cells.extend([
            nbformat.new_code_cell(''),
            nbformat.new_markdown_cell(' '),
            nbformat.new_raw_cell('\n'),
            nbformat.new_raw_cell('\t'),
        ])

        return notebook
开发者ID:BarnetteME1,项目名称:DnD-stuff,代码行数:11,代码来源:test_regexremove.py


注:本文中的nbformat.v4.new_markdown_cell函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。