How to use the nbformat.v4.new_code_cell function in nbformat

To help you get started, we’ve selected a few nbformat examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github d2l-ai / d2l-book / d2lbook / colab.py View on Github external
if cell.cell_type == 'code':
            lines = cell.source.split('\n')
            for l in lines:
                if l.strip().startswith('#'): # it's a comment
                    continue
                m = lib1_re.search(l)
                if not m:
                    m = lib2_re.search(l)
                if m and m[1] in lib_dict:
                    find_libs.append(m[1])
    if not find_libs:
        return None
    install_str = ''
    for lib in set(find_libs):
        install_str += '!pip install ' + lib_dict[lib] + '\n'
    return nbformat.v4.new_code_cell(source=install_str)
github uw-cmg / MAST-ML / plot_data / PlotHelper.py View on Github external
numpoints=1, #number of points
                        bbox_to_anchor=(0.5,1), #anchor against the figure axes; this anchor pins the lower center point to x=half axis and y=full axis
                        fontsize=smallfont,
                        )
        if not (lgd is None): #lgd is None if there are no labeled lines
            lgd.get_frame().set_alpha(0.5) #translucent legend
        """)
        codelist.append("""\
        plt.savefig("%s", bbox_inches="tight")
        plt.show()
        """ % nbfigname)
        code=""
        for codeitem in codelist:
            code = code + codeitem + "\n"
        nb = nbf.v4.new_notebook()
        nb['cells'] = [nbf.v4.new_code_cell(code)]
        with open(nbname, 'w', encoding="utf-8") as f:
            nbf.write(nb, f)
        return
github ParaToolsInc / taucmdr / packages / taucmdr / analysis / analyses / runtime_breakdown_bqplot.py View on Github external
"""
        trials, metric = self._check_input(inputs, **kwargs)
        notebook_cells = []
        commands = ['from taucmdr.analysis.analyses.runtime_breakdown_bqplot import BqplotRuntimeBreakdownVisualizer',
                    'from taucmdr.model.trial import Trial',
                    'from taucmdr.cf.storage.levels import ANALYSIS_STORAGE',
                    inspect.getsource(show_bqplot_runtime_breakdown)]
        def_cell_source = "\n".join(commands)
        notebook_cells.append(nbformat.v4.new_code_cell(def_cell_source))
        trials_list_str = "Trial.controller(ANALYSIS_STORAGE).search_hash([%s])" % (",".join(
            ['"%s"' % trial.hash_digest() for trial in trials]))
        if interactive:
            show_plot_str = self.get_interaction_code(inputs, 'show_bqplot_runtime_breakdown', *args, **kwargs)
        else:
            show_plot_str = 'show_bqplot_runtime_breakdown(%s, "%s")' % (trials_list_str, metric)
        notebook_cells.append(nbformat.v4.new_code_cell(show_plot_str))
        return notebook_cells
github shivam5992 / aster / maggle.py View on Github external
from sklearn.linear_model import LogisticRegression
					from sklearn.preprocessing import LabelEncoder
					from sklearn.metrics import confusion_matrix
					from sklearn.model_selection import KFold
					from sklearn.metrics import roc_auc_score
					from sklearn.metrics import roc_curve
					from xgboost import plot_importance
					from collections import Counter
					import matplotlib.pyplot as plt
					from sklearn import metrics
					import seaborn as sns 
					import xgboost as xgb 
					import pandas as pd
					import numpy as np 
					import itertools"""
		self.nb['cells'].append(nbformat.v4.new_code_cell(code).replace("\t",""))
github StochSS / stochss / stochss-pkg / handlers / util / convert_to_sciope_me.py View on Github external
cells.append(nbf.new_code_cell(
                    generate_imports_cell(json_data, interactive_backend=True)))
        # Create Model Cell
        cells.append(nbf.new_code_cell(generate_model_cell(json_data, name)))
        # Instantiate Model Cell
        cells.append(nbf.new_code_cell('model = {0}()'.format(name)))
        # Sciope Wrapper Cell
        cells.append(nbf.new_code_cell(generate_sciope_wrapper_cell(json_data)))
        # Sciope lhc Cell
        cells.append(nbf.new_code_cell(generate_sciope_lhc_cell()))
        # Sciope stochmet Cell
        cells.append(nbf.new_code_cell(generate_sciope_stochmet_cell()))
        # Sciope Parameter Sweep Run Cell
        cells.append(nbf.new_code_cell(generate_sciope_psweep_run_cell()))
        # Sciope Configure MET DATA
        cells.append(nbf.new_code_cell(generate_sciope_res_conf_cell()))
        # Sciope MET Explore Cell
        cells.append(nbf.new_code_cell(generate_sciope_met_explore_cell()))
        # Sciope Supervised Training Cell
        cells.append(nbf.new_code_cell(generate_sciope_supervised_train_cell()))
        # Sciope Map Labels Cell
        cells.append(nbf.new_code_cell(generate_sciope_map_labels_cell()))
        # Sciope Explore Model Cell
        cells.append(nbf.new_code_cell(generate_sciope_explore_model_cell()))
        # Sciope Set Labels Cell
        cells.append(nbf.new_code_cell(generate_sciope_set_labels_cell()))
    except KeyError as err:
        raise JSONFileNotModelError("Could not convert your model {}: {}".format(json_data, str(err)))
    # Append cells to worksheet
    nb = nbf.new_notebook(cells=cells)

    # Open and write to file
github ParaToolsInc / taucmdr / packages / taucmdr / analysis / analyses / trial_barplot.py View on Github external
Returns:
            list of :obj:`nbformat.NotebookNode`: The cells which show the barplot.

        Raises:
            ConfigurationError: The provided models are not Trials
        """
        trials, metric = self._check_input(inputs, **kwargs)
        notebook_cells = []
        commands = ['from taucmdr.analysis.analyses.trial_barplot import TrialBarPlotVisualizer',
                    'from taucmdr.model.trial import Trial',
                    'from taucmdr.cf.storage.levels import ANALYSIS_STORAGE',
                    inspect.getsource(run_trial_bar_plot),
                    inspect.getsource(show_trial_bar_plot)]
        def_cell_source = "\n".join(commands)
        notebook_cells.append(nbformat.v4.new_code_cell(def_cell_source))
        for trial in trials:
            if interactive:
                notebook_cells.append(nbformat.v4.new_code_cell(
                    self.get_interaction_code(inputs, 'show_trial_bar_plot', **kwargs)))
            else:
                digest = trial.hash_digest()
                notebook_cells.append(nbformat.v4.new_code_cell(
                    'show_trial_bar_plot(Trial.controller(ANALYSIS_STORAGE).search_hash("%s")[0], "%s")'
                    % (digest, metric)))
        return notebook_cells
github andrewcooke / choochoo / py / ch2 / jupyter / load.py View on Github external
def to_cell(self):
        return nbv.new_code_cell(self._text)
github dagster-io / dagster / python_modules / dagstermill / dagstermill / cli.py View on Github external
def execute_retroactive_scaffold(notebook_path):
    nb = load_notebook_node(notebook_path)
    new_nb = copy.deepcopy(nb)

    import_cell_source = 'import dagstermill'
    import_cell = nbformat.v4.new_code_cell(source=import_cell_source)

    parameters_cell_source = 'context = dagstermill.get_context()'
    parameters_cell = nbformat.v4.new_code_cell(source=parameters_cell_source)
    parameters_cell.metadata['tags'] = ['parameters']

    new_nb.cells = [import_cell, parameters_cell] + nb.cells
    write_ipynb(new_nb, notebook_path)