Python nbformat.v4.new_code_cell() Examples

The following are 20 code examples of nbformat.v4.new_code_cell(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module nbformat.v4 , or try the search function .
Example #1
Source File: py2ipynb.py    From py2ipynb with GNU General Public License v3.0 7 votes vote down vote up
def py2ipynb(input, output, cellmark_style, other_ignores=[]):
    """Converts a .py file to a V.4 .ipynb notebook usiing `parsePy` function

    :param input: Input .py filename
    :param output: Output .ipynb filename
    :param cellmark_style: Determines cell marker based on IDE, see parsePy documentation for values
    :param other_ignores: Other lines to ignore
    """
    # Create the code cells by parsing the file in input
    cells = []
    for c in parsePy(input, cellmark_style, other_ignores):
        codecell, metadata, code = c
        cell = new_code_cell(source=code, metadata=metadata) if codecell else new_markdown_cell(source=code, metadata=metadata)
        cells.append(cell)

    # This creates a V4 Notebook with the code cells extracted above
    nb0 = new_notebook(cells=cells,
                       metadata={'language': 'python',})

    with codecs.open(output, encoding='utf-8', mode='w') as f:
        nbformat.write(nb0, f, 4) 
Example #2
Source File: to_ipynb.py    From cloudml-samples with Apache License 2.0 6 votes vote down vote up
def add_cell(cells, filename, insert=None, **kwargs):
    """Modifies cells in place by adding the content of filename as a new cell in position `insert`.
    When `insert` is None, the new cell is appended to cells.
    Allows optional formatting arguments as kwargs."""
    with open(filename, 'r') as f:
        code_source = f.read()

    if kwargs:
        code_source = code_source.format(**kwargs)

    new_cell = new_code_cell(code_source)

    if insert is None:
        cells.append(new_cell)
    else:
        cells.insert(insert, new_cell)

    return cells 
Example #3
Source File: __init__.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_task_cell(source, cell_type, grade_id, points, schema_version=SCHEMA_VERSION):
    if cell_type == "markdown":
        cell = new_markdown_cell(source=source)
    elif cell_type == "code":
        cell = new_code_cell(source=source)
    else:
        raise ValueError("invalid cell type: {}".format(cell_type))

    cell.metadata.nbgrader = {}
    cell.metadata.nbgrader["solution"] = False
    cell.metadata.nbgrader["grade"] = False
    cell.metadata.nbgrader["task"] = True
    cell.metadata.nbgrader["grade_id"] = grade_id
    cell.metadata.nbgrader["points"] = points
    cell.metadata.nbgrader["locked"] = True
    cell.metadata.nbgrader["schema_version"] = schema_version

    return cell 
Example #4
Source File: __init__.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_locked_cell(source, cell_type, grade_id, schema_version=SCHEMA_VERSION):
    if cell_type == "markdown":
        cell = new_markdown_cell(source=source)
    elif cell_type == "code":
        cell = new_code_cell(source=source)
    else:
        raise ValueError("invalid cell type: {}".format(cell_type))

    cell.metadata.nbgrader = {}
    cell.metadata.nbgrader["locked"] = True
    cell.metadata.nbgrader["grade_id"] = grade_id
    cell.metadata.nbgrader["solution"] = False
    cell.metadata.nbgrader["task"] = False
    cell.metadata.nbgrader["grade"] = False
    cell.metadata.nbgrader["schema_version"] = schema_version

    return cell 
Example #5
Source File: __init__.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_solution_cell(source, cell_type, grade_id, schema_version=SCHEMA_VERSION):
    if cell_type == "markdown":
        cell = new_markdown_cell(source=source)
    elif cell_type == "code":
        cell = new_code_cell(source=source)
    else:
        raise ValueError("invalid cell type: {}".format(cell_type))

    cell.metadata.nbgrader = {}
    cell.metadata.nbgrader["solution"] = True
    cell.metadata.nbgrader["grade_id"] = grade_id
    cell.metadata.nbgrader["grade"] = False
    cell.metadata.nbgrader["task"] = False
    cell.metadata.nbgrader["locked"] = False
    cell.metadata.nbgrader["schema_version"] = schema_version

    return cell 
Example #6
Source File: __init__.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_grade_cell(source, cell_type, grade_id, points, schema_version=SCHEMA_VERSION):
    if cell_type == "markdown":
        cell = new_markdown_cell(source=source)
    elif cell_type == "code":
        cell = new_code_cell(source=source)
    else:
        raise ValueError("invalid cell type: {}".format(cell_type))

    cell.metadata.nbgrader = {}
    cell.metadata.nbgrader["grade"] = True
    cell.metadata.nbgrader["grade_id"] = grade_id
    cell.metadata.nbgrader["points"] = points
    cell.metadata.nbgrader["solution"] = False
    cell.metadata.nbgrader["task"] = False
    cell.metadata.nbgrader["locked"] = False
    cell.metadata.nbgrader["schema_version"] = schema_version

    return cell 
Example #7
Source File: __init__.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_regular_cell(source, cell_type, schema_version=SCHEMA_VERSION):
    if cell_type == "markdown":
        cell = new_markdown_cell(source=source)
    elif cell_type == "code":
        cell = new_code_cell(source=source)
    else:
        raise ValueError("invalid cell type: {}".format(cell_type))

    cell.metadata.nbgrader = {}
    cell.metadata.nbgrader["grade"] = False
    cell.metadata.nbgrader["grade_id"] = ""
    cell.metadata.nbgrader["points"] = 0.0
    cell.metadata.nbgrader["solution"] = False
    cell.metadata.nbgrader["task"] = False
    cell.metadata.nbgrader["locked"] = False
    cell.metadata.nbgrader["schema_version"] = schema_version

    return cell 
Example #8
Source File: driver.py    From Xpedite with Apache License 2.0 6 votes vote down vote up
def buildInitCell(nb, numOfCategories, d3Flots, appName, runId):
  """
  Method to build the init cell which contains the intro,
   serialized transactions object and metadata for generating reports

  """
  from xpedite.jupyter.templates import loadInitCell
  initCode = loadInitCell()
  try:
    envLink = buildReportLink('envReport', Action.Load)
    initCode = initCode.format(
      envLink=envLink, appName=appName, categoryCount=numOfCategories + 1, runId=runId
    )
  except TypeError:
    typeErr = 'Number of placeholders in init code string do not match the number of args supplied'
    LOGGER.exception(typeErr)
    raise InvariantViloation(typeErr)

  nb['cells'] = [nbf.new_code_cell(source=initCode, metadata={'init_cell': True, 'isInit': '0xFFFFFFFFA5A55A5DUL',\
  'hide_input': True, 'editable': False, 'deletable': False,\
  'd3Flots': d3Flots})] + nb['cells'] 
Example #9
Source File: exporter.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def create_cell_from_custom_code(code: list) -> NotebookNode:
    """Creates a NotebookNode object with provided list as code in node.

    Args:
        code: list representing lines of code to be run.

    Returns:
        NotebookNode with specified file as code within node.

    """
    cell = new_code_cell("\n".join(code))
    cell.get("metadata")["hide_logging"] = False
    return cell 
Example #10
Source File: test_notebooks.py    From scrapbook with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_no_outputs():
    nb = Notebook(new_notebook(cells=[new_code_cell("test", outputs=[])]))
    assert nb.scraps == collections.OrderedDict() 
Example #11
Source File: test_notebooks.py    From scrapbook with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_metadata():
    output = new_output(output_type="display_data", data={}, metadata={})
    raw_nb = new_notebook(cells=[new_code_cell("test", outputs=[output])])
    nb = Notebook(raw_nb)
    assert nb.scraps == collections.OrderedDict() 
Example #12
Source File: test_notebooks.py    From scrapbook with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_metadata_but_empty_content():
    output = new_output(output_type="display_data", metadata={"scrapbook": {}})
    raw_nb = new_notebook(cells=[new_code_cell("test", outputs=[output])])
    nb = Notebook(raw_nb)
    assert nb.scraps == collections.OrderedDict() 
Example #13
Source File: test_execution.py    From treon with MIT License 5 votes vote down vote up
def unittest_cell():
    source = textwrap.dedent("""
        from IPython.display import clear_output
        import unittest

        r = unittest.main(argv=[''], verbosity=2, exit=False)

        if r.result.testsRun == 0:
            clear_output()
    """)
    return new_code_cell(source=source) 
Example #14
Source File: test_execution.py    From treon with MIT License 5 votes vote down vote up
def doctest_cell():
    source = textwrap.dedent("""
        from IPython.display import clear_output
        import doctest

        r = doctest.testmod(verbose=True)

        if r.attempted == 0:
            clear_output()
    """)
    return new_code_cell(source=source) 
Example #15
Source File: load.py    From choochoo with GNU General Public License v2.0 5 votes vote down vote up
def to_cell(self):
        return nbv.new_code_cell(self._text) 
Example #16
Source File: __init__.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_code_cell():
    source = """print("something")
### BEGIN SOLUTION
print("hello")
### END SOLUTION"""
    cell = new_code_cell(source=source)
    return cell 
Example #17
Source File: exporter.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def create_cell_from_file(filepath: Text) -> NotebookNode:
    """Creates a NotebookNode object with provided file as code in node.

    Args:
        filepath: Path to file that should be used.

    Returns:
        NotebookNode with specified file as code within node.

    """
    with open(filepath, 'r') as f:
        code = f.read()	

    return new_code_cell(code) 
Example #18
Source File: exporter.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def create_cell_from_args(variables: dict) -> NotebookNode:
    """Creates NotebookNode object containing dict of provided variables.

    Args:
        variables: Arguments that need to be injected into a NotebookNode.

    Returns:
        NotebookNode with provided arguments as variables.

    """
    return new_code_cell("variables = {}".format(repr(variables))) 
Example #19
Source File: server.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def generate_notebook_from_arguments(
        self,
        arguments: dict,
        source: Text,
        visualization_type: Text
    ) -> NotebookNode:
        """Generates a NotebookNode from provided arguments.

        Args:
            arguments: JSON object containing provided arguments.
            source: Path or path pattern to be used as data reference for
            visualization.
            visualization_type: Name of visualization to be generated.

        Returns:
                NotebookNode that contains all parameters from a post request.
        """
        nb = new_notebook()
        nb.cells.append(exporter.create_cell_from_args(arguments))
        nb.cells.append(new_code_cell('source = "{}"'.format(source)))
        if visualization_type == "custom":
            code = arguments.get("code", [])
            nb.cells.append(exporter.create_cell_from_custom_code(code))
        else:
            visualization_file = str(Path.cwd() / "types/{}.py".format(visualization_type))
            nb.cells.append(exporter.create_cell_from_file(visualization_file))
        
        return nb 
Example #20
Source File: to_ipynb.py    From cloudml-samples with Apache License 2.0 5 votes vote down vote up
def code_cell(group, remove=None):
    source = '\n'.join(group).strip()
    return new_code_cell(source)