コード例 #1
0
def test_write_reload_simple_notebook():
    nb1 = new_notebook(cells=[
        new_markdown_cell('A markdown cell', metadata={'md': 'value'}),
        new_code_cell('1 + 1'),
        new_markdown_cell('A markdown cell', metadata={'md': 'value'}),
        new_code_cell("""def f(x):
    return x""", metadata={'md': 'value'}),
        new_markdown_cell('A markdown cell', metadata={'md': 'value'}),
        new_code_cell("""def g(x):
    return x


def h(x):
    return x
""",
                      metadata={'md': 'value'})
    ])

    text = writes(nb1, 'py:bare')
    nb2 = reads(text, 'py:bare')
    combine_inputs_with_outputs(nb2, nb1, 'py:bare')
    nb2.metadata.pop('jupytext')

    assert len(nb2.cells) == 7
    nb1.cells = nb1.cells[:5]
    nb2.cells = nb2.cells[:5]
    compare(nb1, nb2)
コード例 #2
0
def test_ipython_help_are_commented_297(text="""# This is a markdown cell
# that ends with a question: float?

# The next cell is also a markdown cell,
# because it has no code marker:

# float?

# +
# float?

# +
# float??

# +
# Finally a question in a code
# # cell?
""", nb=new_notebook(
    cells=[
        new_markdown_cell('This is a markdown cell\nthat ends with a question: float?'),
        new_markdown_cell('The next cell is also a markdown cell,\nbecause it has no code marker:'),
        new_markdown_cell('float?'),
        new_code_cell('float?'),
        new_code_cell('float??'),
        new_code_cell('# Finally a question in a code\n# cell?')])):
    nb2 = jupytext.reads(text, 'py')
    compare_notebooks(nb2, nb)

    text2 = jupytext.writes(nb2, 'py')
    compare(text2, text)
コード例 #3
0
ファイル: test_compare.py プロジェクト: zshxie/jupytext
def notebook_expected():
    return new_notebook(metadata=notebook_metadata(),
                        cells=[
                            new_markdown_cell('First markdown cell'),
                            new_code_cell('1 + 1'),
                            new_markdown_cell('Second markdown cell')
                        ])
コード例 #4
0
def test_combine_reorder():
    nb_source = new_notebook(
        cells=[
            new_markdown_cell("Markdown text"),
            new_code_cell("1+1"),
            new_code_cell("2+2"),
            new_code_cell("3+3"),
            new_markdown_cell("Markdown text"),
            new_code_cell("4+4"),
        ]
    )

    nb_outputs = new_notebook(
        cells=[
            new_markdown_cell("Markdown text"),
            new_code_cell("2+2"),
            new_code_cell("4+4"),
            new_code_cell("1+1"),
            new_code_cell("3+3"),
            new_markdown_cell("Markdown text"),
        ]
    )

    nb_outputs.cells[1].outputs = ["4"]
    nb_outputs.cells[2].outputs = ["8"]
    nb_outputs.cells[3].outputs = ["2"]
    nb_outputs.cells[4].outputs = ["6"]

    nb_source = combine_inputs_with_outputs(nb_source, nb_outputs)

    assert nb_source.cells[1].outputs == ["2"]
    assert nb_source.cells[2].outputs == ["4"]
    assert nb_source.cells[3].outputs == ["6"]
    assert nb_source.cells[5].outputs == ["8"]
コード例 #5
0
def test_rst2md(tmpdir):
    tmp_py = str(tmpdir.join("notebook.py"))
    tmp_ipynb = str(tmpdir.join("notebook.ipynb"))

    # Write notebook in sphinx format
    nb = new_notebook(cells=[
        new_markdown_cell("A short sphinx notebook"),
        new_markdown_cell(":math:`1+1`"),
    ])
    write(nb, tmp_py, fmt="py:sphinx")

    jupytext([
        tmp_py,
        "--from",
        "py:sphinx",
        "--to",
        "ipynb",
        "--opt",
        "rst2md=True",
        "--opt",
        "cell_metadata_filter=-all",
    ])

    assert os.path.isfile(tmp_ipynb)
    nb = read(tmp_ipynb)

    assert nb.metadata["jupytext"]["cell_metadata_filter"] == "-all"
    assert nb.metadata["jupytext"]["rst2md"] is False

    # Was rst to md conversion effective?
    assert nb.cells[2].source == "$1+1$"
コード例 #6
0
def test_raise_on_different_cell_content():
    ref = new_notebook(cells=[new_markdown_cell('Cell one'),
                              new_code_cell('Cell two')])
    test = new_notebook(cells=[new_markdown_cell('Cell one'),
                               new_code_cell('Modified cell two')])
    with pytest.raises(AssertionError):
        compare_notebooks(ref, test)
コード例 #7
0
def test_combine():
    nb_source = new_notebook(
        cells=[
            new_markdown_cell("Markdown text"),
            new_code_cell("a=3"),
            new_code_cell("a+1"),
            new_code_cell("a+1"),
            new_markdown_cell("Markdown text"),
            new_code_cell("a+2"),
        ]
    )

    nb_outputs = new_notebook(
        cells=[
            new_markdown_cell("Markdown text"),
            new_code_cell("a=3"),
            new_code_cell("a+1"),
            new_code_cell("a+2"),
            new_markdown_cell("Markdown text"),
        ]
    )

    nb_outputs.cells[2].outputs = ["4"]
    nb_outputs.cells[3].outputs = ["5"]

    nb_source = combine_inputs_with_outputs(nb_source, nb_outputs)

    assert nb_source.cells[2].outputs == ["4"]
    assert nb_source.cells[3].outputs == []
    assert nb_source.cells[5].outputs == ["5"]
コード例 #8
0
def add_badges(path_to_notes: str = None,
               badges: list = None) -> None:
    """Adds badges to each notebook in the collection.

    Adds a badge cell with one or more badges to each notebook in the
    collection of indexed notebooks in the folder `path_to_notes`.
    The information for creating each badge is in the list `badges`.

    Parameters
    ----------
    path_to_notes : str
        The path to the directory that contains the notebooks, either
        absolute or relative to the script that calls `nbbinder.bind()`.

    badges: list of dict
        A list of dictionaries with the necessary information
        to add the badges.

        Each item in the list is a dictionary which should have
        the keys `alt` (str), `title` (str), `url` (str), an optional
        `extension` (str), and either `src` or the three keys
        `label` (str), `message` (str), and `color` (str).

        The key `url` is used for building link address, with the `href`
        argument being composed of the given `url` appended by the nam
        of the corresponding notebook.

        The keys `label`, `message`, and `color` are used to build
        the badge image via the `shields.io` constructor, which will then
        become the argument `src` of the badge image. Alternatively,
        one can provide a direct `src` link to the badge image.
        The keys `alt` and `title` complement the information of the image.

        The key `extension` is used in case there is a need to replace
        the `.ipynb` extension of each notebook to the appropriate
        extension, e.g `.md`, `.slides.html`, `.pdf`, `.py`, `.tex`,
        and so on. If `extension` is omitted, no replacement occurs.
    """
    cleanup_marker_cells(path_to_notes, BADGES_MARKER, 'remove')

    for nb_filename, this_nb_badge_links \
            in get_badge_entries(path_to_notes, badges):
        nb = nbformat.read(nb_filename, as_version=4)
        nb_name = os.path.basename(nb_filename)

        badges_top = BADGES_MARKER + "\n"

        for badge_link in this_nb_badge_links:
            badges_top += badge_link + " "

        if not nb.cells or not nb.cells[0].source.startswith(HEADER_MARKER):
            LOGGER.info("- inserting badges for %s", nb_name)
            nb.cells.insert(0, new_markdown_cell(source=badges_top,
                                                 metadata=SLIDE_SKIP))
        else:
            LOGGER.info("- inserting badges for %s", nb_name)
            nb.cells.insert(1, new_markdown_cell(source=badges_top,
                                                 metadata=SLIDE_SKIP))

        nbformat.write(nb, nb_filename)
コード例 #9
0
def test_combine():
    nb_source = new_notebook(cells=[
        new_markdown_cell('Markdown text'),
        new_code_cell('a=3'),
        new_code_cell('a+1'),
        new_code_cell('a+1'),
        new_markdown_cell('Markdown text'),
        new_code_cell('a+2')
    ])

    nb_outputs = new_notebook(cells=[
        new_markdown_cell('Markdown text'),
        new_code_cell('a=3'),
        new_code_cell('a+1'),
        new_code_cell('a+2'),
        new_markdown_cell('Markdown text')
    ])

    nb_outputs.cells[2].outputs = ['4']
    nb_outputs.cells[3].outputs = ['5']

    combine_inputs_with_outputs(nb_source, nb_outputs)

    assert nb_source.cells[2].outputs == ['4']
    assert nb_source.cells[3].outputs == []
    assert nb_source.cells[5].outputs == ['5']
コード例 #10
0
def test_raise_on_different_metadata():
    ref = new_notebook(metadata={'main_language': 'python'},
                       cells=[new_markdown_cell('Cell one')])
    test = new_notebook(metadata={'main_language': 'R'},
                        cells=[new_markdown_cell('Cell one')])
    with pytest.raises(AssertionError):
        compare_notebooks(ref, test)
コード例 #11
0
def test_alert_inconsistent_versions(tmpdir, cwd_tmpdir, tmp_repo, capsys):
    """Jupytext refuses to sync two inconsistent notebooks"""
    write(new_notebook(cells=[new_markdown_cell("A short py notebook")]),
          "test.py")
    write(
        new_notebook(
            cells=[new_markdown_cell("Another ipynb notebook")],
            metadata={"jupytext": {
                "formats": "ipynb,py"
            }},
        ),
        "test.ipynb",
    )

    # Add them both
    tmp_repo.git.add("test.py")
    tmp_repo.git.add("test.ipynb")

    # Run jupytext
    status = jupytext(["--sync", "--pre-commit-mode", "test.ipynb"])

    # The diff should be visible
    assert status == 1
    out = capsys.readouterr()
    assert ("""--- test.py
+++ test.ipynb""" in out.err)
    assert """-# A short py notebook
+# Another ipynb notebook
"""
    assert "Error: test.ipynb and test.py are inconsistent" in out.err
    assert "git reset test.py && git checkout -- test.py" in out.err
    assert "git reset test.ipynb && git checkout -- test.ipynb" in out.err
コード例 #12
0
def test_raise_on_different_metadata():
    ref = new_notebook(metadata={'kernelspec': {'language': 'python', 'name': 'python', 'display_name': 'Python'}},
                       cells=[new_markdown_cell('Cell one')])
    test = new_notebook(metadata={'kernelspec': {'language': 'R', 'name': 'R', 'display_name': 'R'}},
                        cells=[new_markdown_cell('Cell one')])
    with pytest.raises(NotebookDifference):
        compare_notebooks(test, ref, 'md')
コード例 #13
0
def test_does_not_raise_on_split_markdown_cell():
    ref = new_notebook(cells=[new_markdown_cell('Cell one\n\n\nsecond line')])
    test = new_notebook(cells=[
        new_markdown_cell('Cell one'),
        new_markdown_cell('second line')
    ])
    compare_notebooks(ref, test, ext='.md')
コード例 #14
0
def test_raise_on_different_cell_count():
    ref = new_notebook(
        cells=[new_markdown_cell('Cell one'),
               new_code_cell('Cell two')])
    test = new_notebook(cells=[new_markdown_cell('Cell one')])
    with pytest.raises(NotebookDifference):
        compare_notebooks(ref, test, ext='.md')
コード例 #15
0
def test_does_raise_on_split_markdown_cell():
    ref = new_notebook(cells=[new_markdown_cell('Cell one\n\n\nsecond line')])
    test = new_notebook(cells=[
        new_markdown_cell('Cell one'),
        new_markdown_cell('second line')
    ])
    with pytest.raises(NotebookDifference):
        compare_notebooks(ref, test, 'md')
コード例 #16
0
def notebook_2():
    metadata = notebook_metadata()
    metadata['language_info']['version'] = '3.6.8'
    return new_notebook(
        metadata=metadata,
        cells=[new_markdown_cell('First markdown cell'),
               new_code_cell('1 + 1'),
               new_markdown_cell('Modified markdown cell')])
コード例 #17
0
ファイル: test_compare.py プロジェクト: zhixd83/jupytext
def test_does_raise_on_split_markdown_cell():
    ref = new_notebook(cells=[new_markdown_cell("Cell one\n\n\nsecond line")])
    test = new_notebook(cells=[
        new_markdown_cell("Cell one"),
        new_markdown_cell("second line")
    ])
    with pytest.raises(NotebookDifference):
        compare_notebooks(test, ref, "md")
コード例 #18
0
ファイル: test_compare.py プロジェクト: kozo2/jupytext
def test_raise_on_split_markdown_cell():
    ref = new_notebook(cells=[new_markdown_cell('Cell one\n\n\nsecond line')])
    test = new_notebook(cells=[
        new_markdown_cell('Cell one'),
        new_markdown_cell('second line')
    ])
    with pytest.raises(AssertionError):
        compare_notebooks(ref, test)
コード例 #19
0
def test_pre_commit_hook_ipynb_to_py(tmpdir, cwd_tmpdir, tmp_repo,
                                     jupytext_repo_root, jupytext_repo_rev):
    """Here we document and test the expected behavior of the pre-commit hook in the
    directional (--to) mode. Note that here, the ipynb file is always the source for
    updates - i.e. changes on the .py file will not trigger the hook.
    """
    # set up the tmpdir repo with pre-commit
    pre_commit_config_yaml = f"""
repos:
- repo: {jupytext_repo_root}
  rev: {jupytext_repo_rev}
  hooks:
  - id: jupytext
    args: [--from, ipynb, --to, "py:percent"]
"""

    tmpdir.join(".pre-commit-config.yaml").write(pre_commit_config_yaml)
    tmp_repo.git.add(".pre-commit-config.yaml")
    pre_commit(["install", "--install-hooks"])

    # write test notebook and output file
    nb = new_notebook(cells=[new_markdown_cell("A short notebook")])
    write(nb, "test.ipynb")
    jupytext(["--from", "ipynb", "--to", "py:percent", "test.ipynb"])

    tmp_repo.git.add(".")
    tmp_repo.index.commit("test")

    # make a change to the notebook
    nb = new_notebook(cells=[new_markdown_cell("Some other text")])
    write(nb, "test.ipynb")

    tmp_repo.git.add("test.ipynb")
    # now a commit will fail, and keep failing until we add the new
    # changes made to the existing output to the index ourselves
    with pytest.raises(HookExecutionError,
                       match="files were modified by this hook"):
        tmp_repo.index.commit("fails")

    with pytest.raises(HookExecutionError, match="git add test.py"):
        tmp_repo.index.commit("fails again")

    # once we add the changes, it will pass
    tmp_repo.git.add("test.py")
    tmp_repo.index.commit("succeeds")

    assert "test.ipynb" in tmp_repo.tree()
    assert "test.py" in tmp_repo.tree()

    # Updating the .py file is possible
    nb = new_notebook(cells=[new_markdown_cell("Some updated text")])
    write(nb, "test.py", fmt="py:percent")
    tmp_repo.index.commit("update py version")

    # But it won't change the ipynb file (if you want that, use the --sync mode)
    nb = read("test.ipynb")
    compare_cells(nb.cells, [new_markdown_cell("Some other text")],
                  compare_ids=False)
コード例 #20
0
def write_index(notebook_directory, index_dict, kernel='python3'):
    index_listing = '\n'.join('- ' + entry
                              for key, entry in sorted(index_dict.items()))

    cells = [new_markdown_cell(INDEX_TEXT),
             new_markdown_cell(index_listing)]

    write_notebook(cells, os.path.join(notebook_directory, 'Index.ipynb'),
                   execute=False, kernel=kernel)
コード例 #21
0
def notebook_expected():
    return new_notebook(
        metadata=notebook_metadata(),
        cells=[
            new_markdown_cell("First markdown cell"),
            new_code_cell("1 + 1"),
            new_markdown_cell("Second markdown cell"),
        ],
    )
コード例 #22
0
ファイル: test_compare.py プロジェクト: zhixd83/jupytext
def notebook_expected():
    return new_notebook(
        metadata=notebook_metadata(),
        cells=[
            new_markdown_cell("First markdown cell", id="markdown-cell-one"),
            new_code_cell("1 + 1", id="code-cell-one"),
            new_markdown_cell("Second markdown cell", id="markdown-cell-two"),
        ],
    )
コード例 #23
0
def test_read_simple_file(script="""# ---
# title: Simple file
# ---

# %% [markdown]
# This is a markdown cell

# %% [md]
# This is also a markdown cell

# %% [raw]
# This is a raw cell

# %%% sub-cell title
# This is a sub-cell

# %%%% sub-sub-cell title
# This is a sub-sub-cell

# %% And now a code cell
1 + 2 + 3 + 4
5
6
# %%magic # this is a commented magic, not a cell

7
"""):
    nb = jupytext.reads(script, 'py:percent')
    compare_notebooks(
        new_notebook(cells=[
            new_raw_cell('---\ntitle: Simple file\n---'),
            new_markdown_cell('This is a markdown cell'),
            new_markdown_cell('This is also a markdown cell',
                              metadata={'region_name': 'md'}),
            new_raw_cell('This is a raw cell'),
            new_code_cell('# This is a sub-cell',
                          metadata={
                              'title': 'sub-cell title',
                              'cell_depth': 1
                          }),
            new_code_cell('# This is a sub-sub-cell',
                          metadata={
                              'title': 'sub-sub-cell title',
                              'cell_depth': 2
                          }),
            new_code_cell('''1 + 2 + 3 + 4
5
6
%%magic # this is a commented magic, not a cell

7''',
                          metadata={'title': 'And now a code cell'})
        ]), nb)

    script2 = jupytext.writes(nb, 'py:percent')
    compare(script2, script)
コード例 #24
0
def test_two_markdown_cell_with_no_language_code_works(nb=new_notebook(cells=[
    new_markdown_cell("""```
1 + 1
```"""),
    new_markdown_cell("""```
2 + 2
```""")
])):
    text = jupytext.writes(nb, 'md')
    nb2 = jupytext.reads(text, 'md')
    compare_notebooks(nb2, nb)
コード例 #25
0
def test_does_raise_on_split_markdown_cell():
    ref = new_notebook(cells=[new_markdown_cell('Cell one\n\n\nsecond line')])
    test = new_notebook(cells=[
        new_markdown_cell('Cell one'),
        new_markdown_cell('second line')
    ])
    with pytest.raises(NotebookDifference):
        compare_notebooks(ref,
                          test,
                          ext='.md',
                          allow_expected_differences=False)
コード例 #26
0
def write_navbars():
    for nb_name, navbar in iter_navbars():
        nb = nbformat.read(nb_name, as_version=4)
        nb_file = os.path.basename(nb_name)
        is_comment = lambda cell: cell.source.startswith(NAV_COMMENT)

        exercises = get_notebook_exercises(nb)
        n = len(exercises)
        if n > 0:
            exercise_links = [
                "[%s](<#%s>)" % (e, to_github(e)) for e in exercises
            ]
            longest_field = max(len(e) for e in exercise_links)
            print(exercise_links)
            print("%i exercises" % n)
            columns = 3
            if n < columns:
                columns = n
            table = []
            empty = " " * (longest_field + 2)
            column_title = "-".center(longest_field + 2)
            dash = "-" * (longest_field + 2)
            table.append("|%s\n" %
                         (("%s|" % column_title) * columns))  # No column title
            table.append("|%s\n" %
                         (("%s|" % dash) * columns))  # separator line
            for i, e in enumerate(exercise_links):
                if i % columns == 0:  # Start a new row
                    table.append("|")
                table.append(" %s |" % e.center(longest_field))
                if i % columns == (columns - 1):  # Row is full
                    table.append("\n")
            remainder = n % columns
            if remainder > 0:
                table.append("%s\n" % (("%s|" % empty) *
                                       (columns - remainder)))

            table = "".join(table)
            print(table)
            header = "%s\n%s\n" % (navbar, table)
        else:
            header = "%s\n" % (navbar)  # no exercises
        if is_comment(nb.cells[0]):
            print("- amending navbar for {0}".format(nb_file))
            nb.cells[0].source = header
        else:
            print("- inserting navbar for {0}".format(nb_file))
            nb.cells.insert(0, new_markdown_cell(source=header))

        if is_comment(nb.cells[-1]):
            nb.cells[-1].source = navbar
        else:
            nb.cells.append(new_markdown_cell(source=navbar))
        nbformat.write(nb, nb_name)
コード例 #27
0
def notebook_actual():
    metadata = notebook_metadata()
    metadata["language_info"]["version"] = "3.6.8"
    return new_notebook(
        metadata=metadata,
        cells=[
            new_markdown_cell("First markdown cell"),
            new_code_cell("1 + 1"),
            new_markdown_cell("Modified markdown cell"),
        ],
    )
コード例 #28
0
def test_two_markdown_cell_with_code_works(nb=new_notebook(cells=[
    new_markdown_cell("""```python
1 + 1
```"""),
    new_markdown_cell("""```python
2 + 2
```"""),
])):
    text = jupytext.writes(nb, "Rmd")
    nb2 = jupytext.reads(text, "Rmd")
    compare_notebooks(nb2, nb)
コード例 #29
0
def test_notebook_with_empty_cells(blank_cells):
    notebook = new_notebook(cells=[new_markdown_cell('markdown cell one')] +
                            [new_code_cell('')] * blank_cells +
                            [new_markdown_cell('markdown cell two')] +
                            [new_code_cell('')] * blank_cells,
                            metadata={'main_language': 'python'})

    script = jupytext.writes(notebook, ext='.py')
    notebook2 = jupytext.reads(script, ext='.py')

    compare(notebook, notebook2)
コード例 #30
0
def test_raise_on_different_metadata():
    ref = new_notebook(metadata={'language_info': {
        'name': 'python'
    }},
                       cells=[new_markdown_cell('Cell one')])
    test = new_notebook(metadata={'language_info': {
        'name': 'R'
    }},
                        cells=[new_markdown_cell('Cell one')])
    with pytest.raises(NotebookDifference):
        compare_notebooks(ref, test, ext='.md')
コード例 #31
0
ファイル: __main__.py プロジェクト: scidash/sciunit
def make_nb(config, path=None, stop_on_error=True, just_tests=False):
    """Create a Jupyter notebook sciunit tests for the given configuration."""
    root, nb_name = nb_name_from_path(config, path)
    clean = lambda varStr: re.sub('\W|^(?=\d)', '_', varStr)
    name = clean(nb_name)

    mpl_style = config.get('misc', 'matplotlib', fallback='inline')
    cells = [new_markdown_cell('## Sciunit Testing Notebook for %s' % nb_name)]
    add_code_cell(cells, (
        "%%matplotlib %s\n"
        "from IPython.display import display\n"
        "from importlib.machinery import SourceFileLoader\n"
        "%s = SourceFileLoader('scidash', '%s/__init__.py').load_module()") %
        (mpl_style, name, root))
    if just_tests:
        add_code_cell(cells, (
            "for test in %s.tests.tests:\n"
            "  score_array = test.judge(%s.models.models, stop_on_error=%r)\n"
            "  display(score_array)") % (name, name, stop_on_error))
    else:
        add_code_cell(cells, (
            "for suite in %s.suites.suites:\n"
            "  score_matrix = suite.judge("
            "%s.models.models, stop_on_error=%r)\n"
            "  display(score_matrix)") % (name, name, stop_on_error))
    write_nb(root, nb_name, cells)
コード例 #32
0
ファイル: __main__.py プロジェクト: jckantor/CBE20255
 def write_header(self):
     if self.content.cells[0].source.startswith(NOTEBOOK_HEADER_TAG):
         print('- amending header for {0}'.format(self.filename))
         self.content.cells[0].source = NOTEBOOK_HEADER
     else:
         print('- inserting header for {0}'.format(self.filename))
         self.content.cells.insert(0, new_markdown_cell(NOTEBOOK_HEADER))
     nbformat.write(self.content, self.path)
コード例 #33
0
ファイル: __main__.py プロジェクト: jckantor/CBE20255
 def write_navbar(self):
     for cell in [self.content.cells[1], self.content.cells[-1]]:
         if cell.source.startswith(NAVBAR_TAG):
             print(f"- amending navbar for {self.filename}")
             cell.source = self.navbar
         else:
             print(f"- inserting navbar for {self.filename}")
             self.content.cells.insert(1, new_markdown_cell(source=self.navbar))
     nbformat.write(self.content, self.path)
コード例 #34
0
def write_navbars():
    for nb_name, navbar in iter_navbars():
        nb = nbformat.read(nb_name, as_version=4)
        nb_file = os.path.basename(nb_name)
        is_comment = lambda cell: cell.source.startswith(NAV_COMMENT)

        if is_comment(nb.cells[1]):
            print("- amending navbar for {0}".format(nb_file))
            nb.cells[1].source = navbar
        else:
            print("- inserting navbar for {0}".format(nb_file))
            nb.cells.insert(1, new_markdown_cell(source=navbar))

        if is_comment(nb.cells[-1]):
            nb.cells[-1].source = navbar
        else:
            nb.cells.append(new_markdown_cell(source=navbar))
        nbformat.write(nb, nb_name)
コード例 #35
0
ファイル: utils.py プロジェクト: pl31/pgcontents
def test_notebook(name):
    """
    Make a test notebook for the given name.
    """
    nb = new_notebook()
    nb.cells.append(new_code_cell("'code_' + '{}'".format(name)))
    nb.cells.append(new_raw_cell("raw_{}".format(name)))
    nb.cells.append(new_markdown_cell("markdown_{}".format(name)))
    return nb
コード例 #36
0
    def cells():
        yield new_markdown_cell('<small>*Notebook auto-generated from '
                                '[``{0}``]({1})*</small>\n\n'
                                '# Altair Example: {2}\n\n'
                                '{3}\n\n'.format(full_filename, full_filepath,
                                                 title, description))
        yield new_code_cell('# Uncomment and run these two lines to enable rendering in JupyterLab/nteract\n'
                            '# from altair import enable_mime_rendering\n'
                            '# enable_mime_rendering()')
        yield new_markdown_cell('## Load Dataset\n'
                                 'The data comes in the form of a Pandas '
                                 'Dataframe:')
        yield new_code_cell('from altair import load_dataset\n'
                            'data = load_dataset("{0}")\n'
                            'data.head()'.format(dataset))

        yield new_markdown_cell('## Define Altair Specification')
        yield new_code_cell(''.join(['from altair import *  # Import the altair API\n\n',
                            'chart = {0}\n\n'.format(chart.to_altair(data='data')),
                            'chart.max_rows = len(data)  # Altair 1.2.1 has a max_rows of 500 by default']))
        yield new_markdown_cell('IPython rich display will invoke Vega-Lite:')
        yield new_code_cell('chart')

        yield new_markdown_cell('## Output Vega-Lite Specification')
        yield new_markdown_cell('Generate JSON dict, leaving data out:')
        yield new_code_cell('chart.to_dict(data=False)')
コード例 #37
0
ファイル: generate_api_docs.py プロジェクト: DaveGavin/altair
def create_doc_notebook(filename):
    kernelspec = {'display_name': 'Python 3',
                  'language': 'python',
                  'name': 'python3'}


    is_toplevel = lambda obj: 'Chart' in obj['name']
    content = sorted(altair_nbdoc(altair), key=itemgetter('name'))

    cells = [new_markdown_cell(source=(HEADER))]
    cells.append(new_markdown_cell(source='## Top-Level Objects'))
    cells.extend([new_markdown_cell(source=TEMPLATE.render(obj=obj))
                  for obj in filter(is_toplevel, content)])

    cells.append(new_markdown_cell(source='## Other Objects'))
    cells.extend([new_markdown_cell(source=TEMPLATE.render(obj=obj))
                  for obj in filterfalse(is_toplevel, content)])

    notebook = new_notebook(cells=cells,
                            metadata={'language': 'python',
                                      'kernelspec': kernelspec})
    nbformat.write(notebook, filename)
コード例 #38
0
def add_book_info():
    for nb_name in iter_notebooks():
        nb_file = os.path.join(NOTEBOOK_DIR, nb_name)
        nb = nbformat.read(nb_file, as_version=4)

        is_comment = lambda cell: cell.source.startswith(BOOK_COMMENT)

        if is_comment(nb.cells[0]):
            print('- amending comment for {0}'.format(nb_name))
            nb.cells[0].source = BOOK_INFO
        else:
            print('- inserting comment for {0}'.format(nb_name))
            nb.cells.insert(0, new_markdown_cell(BOOK_INFO))
        nbformat.write(nb, nb_file)
コード例 #39
0
    def cells():
        yield new_markdown_cell('<small>*Notebook auto-generated from '
                                '[``{0}``]({1})*</small>\n\n'
                                '# Altair Example: {2}\n\n'
                                '{3}\n\n'.format(full_filename, full_filepath,
                                                 title, description))

        yield new_markdown_cell('## Load Dataset\n'
                                 'The data comes in the form of a Pandas '
                                 'Dataframe:')
        yield new_code_cell('from altair import load_dataset\n'
                            'data = load_dataset("{0}")\n'
                            'data.head()'.format(dataset))

        yield new_markdown_cell('## Define Altair Specification')
        yield new_code_cell('from altair import *  # Import the altair API\n\n'
                            'chart = {0}'.format(chart.to_altair(data='data')))
        yield new_markdown_cell('IPython rich display will invoke Vega-Lite:')
        yield new_code_cell('chart')

        yield new_markdown_cell('## Output Vega-Lite Specification')
        yield new_markdown_cell('Generate JSON dict, leaving data out:')
        yield new_code_cell('chart.to_dict(data=False)')
コード例 #40
0
ファイル: removeJS.py プロジェクト: dpiparo/ROOT-Primer
offset = 0
for cell in nb.cells:
  if cell["cell_type"] == "code":
    if cell["source"] == '%jsroot on':
      offset = -1
    else:
      cells_new.append(new_code_cell(
      source=cell.source,
      metadata=cell.metadata,
      outputs=[],
      # print cell.execution_count
      execution_count=cell.execution_count+offset))
      # print cell.execution_count+offset
  elif cell["cell_type"] == "markdown":
    cells_new.append(new_markdown_cell(
    source=cell.source,
    metadata=cell.metadata))
  else:
    cells_new.append(new_raw_cell(
    source=cell.source,
    metadata=cell.metadata))

  # print cell.cell_type

nb_new = new_notebook(cells=cells_new,
    metadata=nb.metadata,
    nbformat=nb.nbformat,
    nbformat_minor=nb.nbformat_minor
)

with codecs.open(outfilename, encoding='utf-8', mode='w') as out:
コード例 #41
0
ファイル: notedown.py プロジェクト: maxxk/notedown
 def create_markdown_cell(block):
     """Create a markdown cell from a block."""
     kwargs = {'cell_type': block['type'],
               'source': block['content']}
     markdown_cell = nbbase.new_markdown_cell(**kwargs)
     return markdown_cell