### nbdev_install command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Installs Quarto and the current library. This command ensures your development environment is set up correctly. ```python #| export @call_parse def nbdev_install(branch=None): "Install Quarto and the current library" from nbdev.quarto import install_quarto install_quarto(branch=branch) ``` -------------------------------- ### Pre-documentation Processing (`_pre_docs`) Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Performs essential setup steps before rendering documentation, including ensuring Quarto is installed, refreshing configuration files, building module index, and processing notebooks. ```python #| export def _pre_docs(path=None, n_workers:int=defaults.cpus, **kwargs): cfg = get_config() path = Path(path) if path else cfg.nbs_path _ensure_quarto() refresh_quarto_yml() import nbdev.doclinks nbdev.doclinks._build_modidx() nbdev_sidebar.__wrapped__(path=path, **kwargs) cache = proc_nbs(path, n_workers=n_workers, **kwargs) return cache,cfg,path ``` -------------------------------- ### nbdev_install_quarto command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Installs the latest Quarto on macOS or Linux and prints instructions for Windows. This command is crucial for setting up the documentation build environment. ```python #| export @call_parse def nbdev_install_quarto(branch=None): "Install latest Quarto on macOS or Linux, prints instructions for Windows" from nbdev.quarto import install_quarto install_quarto(branch=branch) ``` -------------------------------- ### Install Quarto and Library Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Installs the latest Quarto version and the current nbdev library. If the library's `__init__.py` file exists, it performs an editable installation of the library with development dependencies. ```python #| export @call_parse def install(): """Install Quarto and the current library""" install_quarto.__wrapped__() d = get_config().lib_path if (d/'__init__.py').exists(): system(f'pip install -e "{d.parent}[dev]"') ``` -------------------------------- ### Ensure Quarto Installation (`_ensure_quarto`) Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Checks if Quarto is installed in the system's PATH. If not, it proceeds to download and install Quarto automatically. ```python #| export def _ensure_quarto(): if shutil.which('quarto'): return print("Quarto is not installed. We will download and install it for you.") install.__wrapped__() ``` -------------------------------- ### Example: Retrieving notebook sources Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/19_diff.ipynb Demonstrates calling `nbs_pair` to get the source dictionaries for a notebook at two different references. ```python a,b = nbs_pair(nb_path) a ``` -------------------------------- ### nbdev_preview command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Previews documentation locally. This command is useful for checking how your documentation will look before deploying. ```python #| export @call_parse def nbdev_preview(fname=None): "Preview docs locally" from nbdev.quarto import nbdev_preview nbdev_preview(fname=fname) ``` -------------------------------- ### Quarto Publish Examples Source: https://github.com/answerdotai/nbdev/blob/main/nbs/explanations/docs.ipynb Illustrates various ways to use `quarto publish` for different deployment targets and configurations. Examples include publishing to Netlify, GitHub Pages, RStudio Connect, and using options like `--no-prompt` or `--no-render`. ```bash quarto publish ``` ```bash quarto publish document.qmd ``` ```bash quarto publish netlify ``` ```bash quarto publish netlify --id DA36416-F950-4647-815C-01A24233E294 ``` ```bash quarto publish gh-pages ``` ```bash quarto publish connect ``` ```bash quarto publish connect --server example.com --token 01A24233E294 ``` ```bash quarto publish --no-prompt ``` ```bash quarto publish --no-render ``` ```bash quarto publish --no-browser ``` ```bash quarto publish accounts ``` -------------------------------- ### Running a Function Example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Include regular code cells for examples. These will appear with their output in the generated documentation and can also serve as tests. ```python say_hello("Isaac") ``` -------------------------------- ### Create Quarto Blog Project and Install Extensions Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/blogging.ipynb Use these terminal commands to create a new Quarto blog project and install necessary extensions like video support. Ensure you are in the root directory of your Quarto project. ```bash quarto create-project --type website:blog . quarto install extension quarto-ext/video ``` -------------------------------- ### Demonstrate code functionality immediately Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/best_practices.ipynb Split code into small cells with explanations and examples after each. This allows users to understand and experiment with each part interactively. This example shows importing and displaying an image. ```python from fastai.vision.all import * path = untar_data(URLs.MNIST_SAMPLE) img = PILImage.create(path/'train'/'3'/'100.png') ``` -------------------------------- ### nbdev_docs command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Creates Quarto documentation and README.md. This command is used to generate your project's documentation. ```python #| export @call_parse def nbdev_docs(fname=None, skip_procs=None): "Create Quarto docs and README.md" from nbdev.doc import docs docs(fname=fname, skip_procs=skip_procs) ``` -------------------------------- ### nbdev_install_hooks command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Installs Jupyter and git hooks to automatically clean, trust, and fix merge conflicts in notebooks. This command helps maintain notebook integrity. ```python #| export @call_parse def nbdev_install_hooks(): "Install Jupyter and git hooks to automatically clean, trust, and fix merge conflicts in notebooks" from nbdev.hooks import install_hooks install_hooks() ``` -------------------------------- ### Setup for testing notebook diffing Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/19_diff.ipynb Initializes a temporary directory, a Git repository, and a sample notebook for testing diff functionalities. ```python import shutil, tempfile, random ``` ```python random.seed(42) ``` ```python td = Path(tempfile.mkdtemp(prefix='nbdiff_test_')) g = Git(td) g.init(b='main') nb_path = td/'test.ipynb' nb = new_nb(['x=1', 'y=2']) write_nb(nb, nb_path) g.add('test.ipynb') g.commit(m='initial notebook') nb.cells[0].source = 'x = 100' nb.cells.append(mk_cell('z=3')) write_nb(nb, nb_path) ``` -------------------------------- ### ModuleMaker Example Usage Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/02_maker.ipynb Demonstrates the initialization of the ModuleMaker class to create a new module file. ```python mm = ModuleMaker(dest='tmp', name='test.testing', nb_path=Path.cwd()/'04_export.ipynb', is_new=True) mm.fname ``` -------------------------------- ### Install Quarto on macOS Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Installs the latest Quarto version on macOS systems using a `.pkg` installer. Requires root privileges. ```python #| export def _install_mac(): system(f'curl -LO {BASE_QUARTO_URL}quarto-macos.pkg') system('sudo installer -pkg quarto-macos.pkg -target / && rm quarto-macos.pkg') ``` -------------------------------- ### Install fastcore and nbdev Source: https://github.com/answerdotai/nbdev/blob/main/tests/2020-09-01-fastcore.ipynb Installs the latest versions of fastcore and nbdev from GitHub, along with numpy. This is a prerequisite for using the library. ```python #hide ! pip install -U git+git://github.com/fastai/fastcore@master ! pip install -U git+git://github.com/fastai/nbdev@master ! pip install -U numpy from fastcore.foundation import * from fastcore.meta import * from fastcore.utils import * from fastcore.test import * from nbdev.showdoc import * from fastcore.dispatch import typedispatch from functools import partial import numpy as np import inspect ``` -------------------------------- ### nbdev_help command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Displays help information for all nbdev console scripts. This is useful for discovering available commands and their basic usage. ```python #| export @call_parse def chelp(): "Show help for all console scripts" from fastcore.xtras import console_help console_help('nbdev') ``` ```python chelp() ``` -------------------------------- ### nbdev_create_config command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Creates a `pyproject.toml` configuration file. This command is used to set up the project's configuration. ```python #| export @call_parse def nbdev_create_config(fname='pyproject.toml'): "Create a pyproject.toml config file." from nbdev.config import nbdev_create_config nbdev_create_config(fname=fname) ``` -------------------------------- ### nbdev Configuration Settings Example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/explanations/config.ipynb Example of nbdev-specific settings in a `pyproject.toml` file. This includes library name, repository details, and author information. ```toml [DEFAULT] lib_name = nbdev repo = nbdev description = Create delightful software with Jupyter Notebooks copyright = 2020 onwards, Jeremy Howard keywords = nbdev fastai jupyter notebook export user = fastai author = Jeremy Howard and Hamel Husain author_email = j@fast.ai branch = master ``` -------------------------------- ### Install Quarto with nbdev Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Installs the latest version of Quarto using the nbdev command-line tool. This may prompt for your password. ```shell nbdev-install-quarto ``` -------------------------------- ### nbdev_readme command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Generates the README.md file from a specified notebook. By default, it uses 'index.ipynb'. ```python #| export @call_parse def nbdev_readme(fname=None, skip_procs=None): "Create README.md from readme_nb (index.ipynb by default)" from nbdev.doc import readme_nb readme_nb(fname=fname, skip_procs=skip_procs) ``` -------------------------------- ### Install Quarto on Linux Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Installs the latest Quarto version on Linux systems. It detects the machine architecture (ARM or AMD) and uses `dpkg` to install the appropriate `.deb` package. Requires root privileges. ```python #| export BASE_QUARTO_URL='https://www.quarto.org/download/latest/' def _install_linux(): from os import uname machine = 'arm' if uname().machine in ('arm64', 'aarch64', 'armv8', 'armv8l') else 'amd' system(f'curl -LO {BASE_QUARTO_URL}quarto-linux-{machine}64.deb') system(f'sudo dpkg -i quarto-linux-{machine}64.deb && rm quarto-linux-{machine}64.deb') ``` -------------------------------- ### Install nbdev with Development Dependencies Source: https://github.com/answerdotai/nbdev/blob/main/CONTRIBUTING.md Install nbdev in editable mode, including development dependencies required for contributing. ```sh pip install -e '.[dev]' ``` -------------------------------- ### Install pre-commit using pip Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/pre_commit.ipynb Install the pre-commit framework using pip. Ensure you follow the latest instructions from the pre-commit website if you encounter issues. ```sh pip install pre-commit ``` -------------------------------- ### Install pre-commit hooks into repository Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/pre_commit.ipynb Execute this command to install the configured pre-commit hooks into your local repository. This command should be run after creating the .pre-commit-config.yaml file. ```sh pre-commit install ``` -------------------------------- ### Install necessary packages for Conda upload Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Before uploading to Conda, install the required packages: `anaconda-client`, `conda-build`, and `conda-verify`. ```bash pip install anaconda-client conda-build conda-verify ``` -------------------------------- ### Command-line Configuration Creation Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/01_config.ipynb Example of how to create a `pyproject.toml` configuration file using the `nbdev-create-config` command with specific parameters. ```sh nbdev-create-config --repo nbdev --user fastai --author fastai \ --author_email info@fast.ai --description 'A test project' ``` -------------------------------- ### Install pre-commit using Homebrew (macOS) Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/pre_commit.ipynb Install the pre-commit framework on macOS using Homebrew. This is a convenient method for macOS users. ```sh brew install pre-commit ``` -------------------------------- ### Bootstrap nbdev Export Example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/01_config.ipynb This example demonstrates the usage of `_basic_export_nb` to export a notebook (`01_config.ipynb`) into a Python module (`config.py`) for bootstrapping nbdev. ```python # #| hide # #| eval: false # path = Path('../nbdev') # (path/'config.py').unlink(missing_ok=True) # # _basic_export_nb("01_config.ipynb", 'config.py') # # g = exec_new('from nbdev import config') # assert g['config'].add_init # assert 'add_init' in g['config'].__all__ ``` -------------------------------- ### Configure PyPI upload credentials Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Set up your `~/.pypirc` file with your PyPI username and API token for uploading your project. Ensure you have installed `twine` using `pip install twine`. ```ini [pypi] username = __token__ password = your_pypi_token ``` -------------------------------- ### Install Latest Quarto Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Installs the latest Quarto version on macOS or Linux. For unsupported platforms like Windows, it prints instructions to visit the Quarto website. This function requires root access and uses a temporary file to manage the installation process. ```python #| export @call_parse def install_quarto(): """Install latest Quarto on macOS or Linux, prints instructions for Windows""" if sys.platform not in ('darwin','linux'): return print('Please visit https://quarto.org/docs/get-started/ to install quarto') print("Installing or upgrading quarto -- this requires root access.") system('sudo touch .installing') try: installing = Path('.installing') if not installing.exists(): return print("Cancelled. Please download and install Quarto from quarto.org.") if 'darwin' in sys.platform: _install_mac() elif 'linux' in sys.platform: _install_linux() finally: system('sudo rm -f .installing') ``` -------------------------------- ### Preview Documentation Locally with nbdev Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Starts a local preview server for the documentation. It watches for file changes and re-renders affected parts of the documentation. ```python #| export @call_parse @delegates(_nbglob_docs) def nbdev_preview( path:str=None, # Path to notebooks port:int=None, # The port on which to run preview host:str=None, # The host on which to run preview no_browser:bool=False, # Do not open a browser n_workers:int=defaults.cpus, # Number of workers **kwargs): """Preview docs locally""" os.environ['QUARTO_PREVIEW']='1' cache,cfg,path = _pre_docs(path, n_workers=n_workers, **kwargs) xtra = [] if port: xtra += ['--port', str(port)] if host: xtra += ['--host', host] if no_browser: xtra += ['--no-browser'] def _f(e): res = _proc_file(Path(e.src_path), cache, path) if res: try: serve_drv.main(res) except: traceback.print_exc() os.chdir(cache) xtra = xtra or [] with fs_watchdog(_f, path): subprocess.run(['quarto','preview']+xtra) ``` -------------------------------- ### nbdev_pypi command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Creates and uploads a Python package to PyPI. This command is used for releasing your library. ```python #| export @call_parse def nbdev_pypi(version=None, **kwargs): "Create and upload Python package to PyPI" from nbdev.release import pypi_pkg pypi_pkg(version=version, **kwargs) ``` -------------------------------- ### nbdev_sidebar command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Creates a `sidebar.yml` file. This command is used to generate the navigation structure for your documentation. ```python #| export @call_parse def nbdev_sidebar(fname=None): "Create sidebar.yml" from nbdev.doc import sidebar sidebar(fname=fname) ``` -------------------------------- ### Shell Commands Example Source: https://github.com/answerdotai/nbdev/blob/main/tests/2020-01-14-test-markdown-post.md Format text as shell commands. This is useful for showing command-line operations. ```shell echo "hello world" ./some_script.sh --option "value" wget https://example.com/cat_photo1.png ``` -------------------------------- ### Install nbdev Git Hooks Source: https://github.com/answerdotai/nbdev/blob/main/README.md Run this command in your cloned nbdev repository to install the necessary git hooks for development. ```bash nbdev-install-hooks ``` -------------------------------- ### Example: Generating source diff Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/19_diff.ipynb Shows how to use `source_diff` to generate a diff output for a simple code change. ```python print(source_diff('x = 1\ny=2', 'x = 100\ny=2')) ``` -------------------------------- ### YAML Formatting Example Source: https://github.com/answerdotai/nbdev/blob/main/tests/2020-01-14-test-markdown-post.md Format text as YAML. Useful for displaying configuration files or data structures. ```yaml key: value - another_key: "another value" ``` -------------------------------- ### nbdev_migrate command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Converts all markdown and notebook files in a given path from v1 to v2. This command is for migrating older nbdev projects. ```python #| export @call_parse def nbdev_migrate(path='.', fname=None): "Convert all markdown and notebook files in `path` from v1 to v2" from nbdev.migrate import nbdev_migrate nbdev_migrate(path=path, fname=fname) ``` -------------------------------- ### nbdev_test command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Tests notebooks matching the specified path. You can pass additional flags to the test execution. ```python #| export @call_parse def nbdev_test(path='.', flags=None): "Test in parallel notebooks matching `path`, passing along `flags`" from nbdev.test import nbtest nbtest(path, flags=flags) ``` -------------------------------- ### Install nbdev (Quiet) Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/git_friendly_jupyter.ipynb Installs or upgrades nbdev quietly. This is often used in automated setups. ```shell pip install -Uqq nbdev ``` -------------------------------- ### Example: Reading notebook cells from Git Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/19_diff.ipynb Demonstrates how to use `read_nb_from_git` to retrieve and display the cells of a notebook from a specific Git reference. ```python read_nb_from_git(g, 'test.ipynb', 'HEAD').cells ``` -------------------------------- ### nbdev_proc_nbs command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Processes notebooks in a given path for documentation rendering. This command prepares notebooks for the documentation build process. ```python #| export @call_parse def nbdev_proc_nbs(path='nbs', skip_procs=None): "Process notebooks in `path` for docs rendering" from nbdev.doc import proc_nbs proc_nbs(path=path, skip_procs=skip_procs) ``` -------------------------------- ### Start nbdev Documentation Preview Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Launch the nbdev preview server to render your documentation locally using Quarto. It watches for file changes and updates the preview automatically. ```bash nbdev-preview ``` -------------------------------- ### nbdev_prepare command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Prepares notebooks by exporting, testing, and cleaning them. It also renders the README if necessary. This is a comprehensive command for ensuring your project is ready. ```python #| export @call_parse def nbdev_prepare(path='nbs', docs=False): "Export, test, and clean notebooks, and render README if needed" from nbdev.prepare import prepare_all prepare_all(path=path, docs=docs) ``` -------------------------------- ### nbdev_changelog command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Creates a CHANGELOG.md file from closed and labeled GitHub issues. This automates the process of documenting changes. ```python #| export @call_parse def nbdev_changelog(fname=None, version=None, **kwargs): "Create a CHANGELOG.md file from closed and labeled GitHub issues" from nbdev.release import changelog_maker changelog_maker(fname=fname, version=version, **kwargs) ``` -------------------------------- ### ModuleMaker Usage Example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/02_maker.ipynb Demonstrates creating code cells and using ModuleMaker to generate a Python file when is_new is False. ```python c2 = make_code_cells("def c(): ...", "def d(): ...") mm = ModuleMaker(dest='tmp', name='test.testing', nb_path=Path.cwd()/'04_export.ipynb', is_new=False) mm.make(c2, c2) ``` -------------------------------- ### nbdev_requirements command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Writes a `requirements.txt` file to a specified directory based on `pyproject.toml`. This command helps in managing project dependencies. ```python #| export @call_parse def nbdev_requirements(directory='.'): "Writes a `requirements.txt` file to `directory` based on pyproject.toml." from nbdev.config import nbdev_requirements nbdev_requirements(directory=directory) ``` -------------------------------- ### Install pre-commit using conda Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/pre_commit.ipynb Install the pre-commit framework using conda. This command installs pre-commit from the conda-forge channel. ```sh conda install -c conda-forge pre-commit ``` -------------------------------- ### Create New Quarto Blog Project Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/blogging.ipynb Use the Quarto CLI to initialize a new blog project. This command sets up the basic structure for a website with blog functionality. ```bash quarto create-project myblog --type website:blog ``` -------------------------------- ### nbdev_release_git command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Tags and creates a GitHub release for the current version. This command is part of the release workflow. ```python #| export @call_parse def nbdev_release_git(version=None, **kwargs): "Tag and create a release in GitHub for the current version" from nbdev.release import release_git release_git(version=version, **kwargs) ``` -------------------------------- ### Example: Autogenerating __all__ Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/02_maker.ipynb Demonstrates how `make_all` autogenerates the `__all__` list from notebook cells, including explicit `_all_` assignments and public symbols. ```python nb = make_code_cells("from __future__ import print_function", "def a():...", "def b():...", "c=d=1", "_f=1", "_g=1", "_h=1", "_all_=['_g', _h]", "@patch\ndef h(self:ca):...") test_eq(set(mm.make_all(nb)), set(['a','b','c','d', '_g', '_h'])) ``` -------------------------------- ### nbdev_contributing command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Creates a `CONTRIBUTING.md` file from `contributing_nb`. If `contributing_nb` is not present, it skips the process. This command helps in setting up contribution guidelines. ```python #| export @call_parse def nbdev_contributing(fname=None, skip_procs=None): "Create CONTRIBUTING.md from contributing_nb (defaults to 'contributing.ipynb' if present). Skips if the file doesn't exist." from nbdev.doc import contributing_nb contributing_nb(fname=fname, skip_procs=skip_procs) ``` -------------------------------- ### Install nbdev with pip Source: https://github.com/answerdotai/nbdev/blob/main/README.md Install nbdev using pip. Ensure it's installed in the same Python environment used for Jupyter and your project. ```sh pip install nbdev ``` -------------------------------- ### Install nbdev Div Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/15_qmd.ipynb Creates a qmd div with tabbed content for installing nbdev via pip and conda. This is useful for providing installation instructions. ```python #| export def _install_nbdev(): return div('''#### pip ```sh pip install -U nbdev ``` #### conda ```sh conda install -c fastai nbdev ``` ''', ['panel-tabset']) ``` -------------------------------- ### Turn code examples into tests with assertions Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/best_practices.ipynb Enhance code examples by adding assertions to turn them into valuable tests. This example uses `fastcore.test.test_eq` to verify the output of an increment function. ```python from fastcore.test import * def inc(x): return x + 1 test_eq(inc(3), 4) ``` -------------------------------- ### Publish Docs with nbdev-proc-nbs and Quarto Source: https://github.com/answerdotai/nbdev/blob/main/nbs/explanations/docs.ipynb Run `nbdev-proc-nbs` to pre-process notebooks, then `cd` into the `_proc/` directory and use `quarto publish` to deploy your documentation. This is necessary for services like Netlify. ```bash nbdev-proc-nbs && cd _proc && quarto publish netlify ``` -------------------------------- ### Install nbdev Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/git_friendly_jupyter.ipynb Installs or upgrades nbdev using pip. This is a prerequisite for using nbdev hooks. ```python #| hide from nbdev.qmd import _install_nbdev ``` ```python #| echo: false #| output: asis print(_install_nbdev()) ``` -------------------------------- ### Install JupyterLab with Pip Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Installs JupyterLab using the pip package manager. Use this if you are not using conda. ```shell pip install jupyterlab ``` -------------------------------- ### Initialize and Process Notebook with Custom Extension Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/extensions.ipynb Instantiate NBProcessor with the custom LayoutProc and the converted notebook, then apply the processors. ```python processor = NBProcessor(procs=LayoutProc, nb=dict2nb(nb)) ``` ```python processor.process() ``` -------------------------------- ### nbdev_conda command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Creates a `meta.yaml` file for Conda packaging and optionally builds and uploads the package. This command facilitates Conda distribution. ```python #| export @call_parse def nbdev_conda(version=None, **kwargs): "Create a `meta.yaml` file ready to be built into a package, and optionally build and upload it" from nbdev.release import conda_pkg conda_pkg(version=version, **kwargs) ``` -------------------------------- ### Install nbdev via conda Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/git_friendly_jupyter.ipynb Installs the nbdev package using conda. Use this command in your terminal. ```shell conda install -c fastai nbdev ``` -------------------------------- ### Install nbdev via pip Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/git_friendly_jupyter.ipynb Installs the nbdev package using pip. Use this command in your terminal. ```shell pip install -U nbdev ``` -------------------------------- ### Example: Relative Import Calculations Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/02_maker.ipynb Tests the `relative_import` function with various module and filename combinations to ensure correct relative path generation. ```python test_eq(relative_import('nbdev.core', "xyz"), 'nbdev.core') test_eq(relative_import('nbdev.core', 'nbdev'), '.core') _p = Path('fastai') test_eq(relative_import('fastai.core', _p/'vision'), '..core') test_eq(relative_import('fastai.core', _p/'vision/transform'), '...core') test_eq(relative_import('fastai.vision.transform', _p/'vision'), '.transform') test_eq(relative_import('fastai.notebook.core', _p/'data'), '..notebook.core') test_eq(relative_import('fastai.vision', _p/'vision'), '.') test_eq(relative_import('fastai', _p), '.') test_eq(relative_import('fastai', _p/'vision'), '..') test_eq(relative_import('fastai', _p/'vision/transform'), '...') ``` -------------------------------- ### Create and Update Project Configuration Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/01_config.ipynb This snippet demonstrates how to create a basic project configuration file (`_pyproject.toml`) and update it, simulating the initial setup of an nbdev project. ```python with tempfile.TemporaryDirectory() as d: d = Path(d) cfg_text = (pyproj_tmpl.replace('name = "FILL_IN"', 'name = "testpkg"').replace('requires-python="FILL_IN"', 'requires-python=">=3.10"')) cfg_text += ' [tool.nbdev] ' (d/_pyproj).write_text(cfg_text) (d/'testpkg').mkdir() with working_directory(d): update_proj(d) result = (d/_pyproj).read_text() assert 'name = "testpkg"' in result ``` -------------------------------- ### Create a minimal settings.ini in a temporary directory Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/16_migrate.ipynb Demonstrates the setup for testing the `nbdev_migrate_config` function by creating a temporary directory and a minimal `settings.ini` file within it. ```python with tempfile.TemporaryDirectory() as d: # Create a minimal settings.ini ``` -------------------------------- ### Create and Migrate settings.ini Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/16_migrate.ipynb This snippet shows the creation of a sample settings.ini file and the subsequent migration to pyproject.toml using nbdev_migrate_config. It asserts the existence of the new file and checks for key configuration values. ```python (Path(d)/'settings.ini').write_text('''[DEFAULT]\nrepo = test-proj\nuser = testuser\nauthor = Test Author\nauthor_email = test@test.com\ndescription = A test project\nversion = 1.0.0\n''') nbdev_migrate_config(d) assert (Path(d)/'pyproject.toml').exists() txt = (Path(d)/'pyproject.toml').read_text() assert 'name = "test-proj"' in txt assert '[tool.nbdev]' in txt assert (Path(d)/'test_proj/__init__.py').exists() ``` -------------------------------- ### Install nbdev with Conda Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Installs the nbdev library using the conda package manager. This command is for Mac and Linux users. ```shell conda install -c fastai -y nbdev ``` -------------------------------- ### nbdev_new command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Use this command to create a new nbdev project. Specify repository details like name, branch, user, author, and a description. ```python #| export @call_parse def nbdev_new(**kwargs): "Create an nbdev project." from nbdev.quarto import _new_quarto_project _new_quarto_project(**kwargs) ``` -------------------------------- ### Install JupyterLab with Conda Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Installs JupyterLab using the conda package manager. This is a recommended method for managing Python environments. ```shell conda install -c conda-forge -y jupyterlab ``` -------------------------------- ### Initialize your nbdev repository Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Use the `nbdev-new` command to initialize your empty Git repository. This command infers project information and sets up essential files for package publishing, documentation, and GitHub Actions. ```shell nbdev-new ``` -------------------------------- ### Example Usage of `_repl_v1dir` Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/16_migrate.ipynb Demonstrates the application of `_repl_v1dir` to a sample notebook cell containing nbdev v1 directives, showing the transformed source code. ```python #| hide _code = _test_dir tst = {'cell_type': 'code', 'execution_count': 26, 'metadata': {'hide_input': True, 'meta': 23}, 'outputs': [{'execution_count': 2, 'data': { 'application/vnd.google.colaboratory.intrinsic+json': {'type': 'string'}, 'plain/text': ['sample output',] }, 'output': 'super'}], 'source': _code} nb = {'metadata': {'kernelspec': 'some_spec', 'jekyll': 'some_meta', 'meta': 37}, 'cells': [tst]} for cell in nb['cells']: _repl_v1dir(cell) test_eq(nb['cells'][0]['source'], """ #| default_exp #| export #| code-fold: show #| code-fold: true #| code-fold: true # collapse_output not_dir='#export' # hide_input foo # hide""") ``` -------------------------------- ### Example usage of nbdev_filter (commented out) Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb A commented-out example demonstrating how to use `nbdev_filter` with a specified file and `printit` set to False. ```python #| hide # res = nbdev_filter(fname=get_config().nbs_path/'API'/'merge.ipynb', printit=False) ``` -------------------------------- ### Prepare Project Environment Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Exports, tests, and cleans notebooks. It also refreshes Quarto configuration and ensures README.md and CONTRIBUTING.md are up-to-date. ```python #| export @call_parse def prepare(): """Export, test, and clean notebooks, and render README if needed""" import nbdev.test, nbdev.clean nbdev_export.__wrapped__() nbdev.test.nbdev_test.__wrapped__() nbdev.clean.nbdev_clean.__wrapped__() refresh_quarto_yml() nbdev_readme.__wrapped__(chk_time=True) nbdev_contributing.__wrapped__(chk_time=True) ``` -------------------------------- ### Install Quarto JupyterLab Extension Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Installs the JupyterLab extension for Quarto, enabling it to render Quarto markdown content within JupyterLab. ```shell pip install jupyterlab-quarto ``` -------------------------------- ### Install nbdev Git Hooks Source: https://github.com/answerdotai/nbdev/blob/main/CONTRIBUTING.md Install git hooks to automatically strip notebooks of metadata during commits and merges, preventing conflicts. ```sh nbdev_install_hooks ``` -------------------------------- ### Create New nbdev Project Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Initializes a new nbdev project, creating configuration files, copying template contents, and setting up the repository. ```python #| export @call_parse @delegates(nbdev_create_config) def nbdev_new(**kwargs): """Create an nbdev project.""" from ghapi.core import GhApi nbdev_create_config.__wrapped__(**kwargs) cfg = get_config() if (Path('.git')).exists(): _update_repo_meta(cfg) else: print(f"No git repo found. Run: gh repo create {cfg.user}/{cfg.repo} --public --source=.") path = Path() _ORG_OR_USR,_REPOSITORY = 'answerdotai','nbdev3-template' _TEMPLATE = f'{_ORG_OR_USR}/{_REPOSITORY}' template = kwargs.get('template', _TEMPLATE) try: org_or_usr, repo = template.split('/') except ValueError: org_or_usr, repo = _ORG_OR_USR, _REPOSITORY tag = kwargs.get('tag', None) if tag is None: with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) tag = GhApi(gh_host='https://api.github.com', authenticate=False ).repos.get_latest_release(org_or_usr, repo).tag_name url = f"https://github.com/{org_or_usr}/{repo}/archive/{tag}.tar.gz" extract_tgz(url) tmpl_path = path/f'{repo}-{tag}' cfg.nbs_path.mkdir(exist_ok=True) nbexists = bool(first(cfg.nbs_path.glob('*.ipynb'))) _nbs_path_sufs = ('.ipynb','.css') for o in tmpl_path.ls(): p = cfg.nbs_path if o.suffix in _nbs_path_sufs else path if o.name == '_quarto.yml': continue if o.name == 'index.ipynb': _render_nb(o, cfg) if o.name == '00_core.ipynb' and not nbexists: move(o, p) elif not (path/o.name).exists(): move(o, p) rmtree(tmpl_path) refresh_quarto_yml() nbdev_export.__wrapped__() nbdev_readme.__wrapped__() nbdev_contributing.__wrapped__() ``` -------------------------------- ### Install Quarto Without Root Access Source: https://github.com/answerdotai/nbdev/blob/main/README.md Use this script to install Quarto without root privileges on Linux. Ensure '~/.local/bin' is in your PATH. ```bash dpkg -x quarto*.deb . mv opt/quarto ./ rmdir opt mkdir -p ~/.local/bin ln -s "$(pwd)"/quarto/bin/quarto ~/.local/bin ``` -------------------------------- ### Example: Create Module with __all__ Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/02_maker.ipynb Demonstrates creating a Python module from code cells, including a `__future__` import and functions `a` and `b`. The `__all__` list is generated based on the provided `all_cells` argument, which includes only the cell defining function `b`. ```python cells = make_code_cells("from __future__ import print_function", "#| export\ndef a(): ...", "def b(): ...") mm.make(cells, L([cells[2]])) show_src(Path('tmp/test/testing.py').read_text(encoding='utf-8')) ``` -------------------------------- ### Generate README from Notebook (`nbdev_readme`) Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Creates a README.md file by rendering a specified notebook (defaults to `index.ipynb`) using Quarto. It handles temporary removal of `sidebar.yml` to optimize rendering and saves the output to the correct location. ```python #| export @call_parse def nbdev_readme( path:str=None, # Path to notebooks chk_time:bool=False): # Only build if out of date """Create README.md from readme_nb (index.ipynb by default)""" cfg = get_config() path = Path(path) if path else cfg.nbs_path if chk_time and _doc_mtime_not_older(cfg.config_path/'README.md', path/cfg.readme_nb): return with _SidebarYmlRemoved(path): # to avoid rendering whole website cache = proc_nbs(path) _sprun(f'cd "{cache}" && quarto render "{cache/cfg.readme_nb}" -o README.md -t gfm --no-execute') _save_cached_readme(cache, cfg) ``` -------------------------------- ### Hide Imports and Setup Code Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/git_friendly_jupyter.ipynb These Python code blocks are marked with '#| hide' and are not displayed in the rendered notebook. They are used for internal setup and imports. ```python #| hide import os,tempfile from pathlib import Path ``` ```python #| hide tmpdir = Path(tempfile.mkdtemp()) repo_path = tmpdir/'repo' repo_path.mkdir(exist_ok=True) cwd = Path.cwd() os.chdir(repo_path) ``` -------------------------------- ### Quarto Publish Help Source: https://github.com/answerdotai/nbdev/blob/main/nbs/explanations/docs.ipynb Displays the help information for the `quarto publish` command, outlining available providers, options, and commands. Use this to understand publishing workflows and configurations. ```bash !quarto publish -h ``` -------------------------------- ### Import Testing Utilities Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/extensions.ipynb Import nbdev utilities for testing custom processors by mocking notebook cells and processors. ```python from nbdev.processors import mk_cell, NBProcessor ``` -------------------------------- ### Sample settings.ini content Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/16_migrate.ipynb This is a sample string representing the content of a settings.ini file, used for testing the migration process. ```python _test_settings_ini = '''[DEFAULT]\nrepo = fasthtml\nlib_name = python-fasthtml\nversion = 0.12.40\nmin_python = 3.10\nlicense = apache2\nrequirements = fastcore>=1.10.0 python-dateutil starlette>0.33 oauthlib itsdangerous uvicorn[standard]>=0.30\ndev_requirements = ipython lxml pysymbol_llm monsterui PyJWT\nblack_formatting = False\nconda_user = fastai\ndoc_path = _docs\nlib_path = fasthtml\nnbs_path = nbs\nrecursive = True\ntst_flags = notest\nput_version_in_init = True\nbranch = main\ncustom_sidebar = False\ndoc_host = https://www.fastht.ml\ndoc_baseurl = /docs/\ngit_url = https://github.com/AnswerDotAI/fasthtml\ntitle = fasthtml\naudience = Developers\nauthor = Jeremy Howard and contributors\nauthor_email = github@jhoward.fastmail.fm\ncopyright = 2024 onwards, Jeremy Howard\ndescription = The fastest way to create an HTML app\nkeywords = nbdev jupyter notebook python\nlanguage = English\nstatus = 3\nconsole_scripts = fh_railway_link=fasthtml.cli:railway_link\n\tfh_railway_deploy=fasthtml.cli:railway_deploy\nuser = AnswerDotAI\nreadme_nb = index.ipynb\nallowed_metadata_keys = \nallowed_cell_metadata_keys = \njupyter_hooks = True\nclean_ids = True\nclear_all = False\ncell_number = False\nskip_procs = \nupdate_pyproject = True\n''' ``` -------------------------------- ### Install Latest nbdev Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/migrating.ipynb Install or upgrade to the latest version of nbdev using pip or conda. A terminal restart may be necessary for changes to take effect. ```bash pip install -U nbdev ``` ```bash conda install -c fastai nbdev ``` -------------------------------- ### Install nbdev Jupyter and Git Hooks Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/11_clean.ipynb Installs Jupyter and git hooks to automatically clean, trust, and fix merge conflicts in notebooks. This function handles configuration of Jupyter files, git post-merge hooks, and git attributes for merge drivers. ```python #| export @call_parse def nbdev_install_hooks(): """Install Jupyter and git hooks to automatically clean, trust, and fix merge conflicts in notebooks""" cfg_path = Path.home()/'.jupyter' cfg_path.mkdir(exist_ok=True) cfg_fns = [cfg_path/f'jupyter_{o}_config.py' for o in ('notebook','server')] for fn in cfg_fns: src = fn.read_text() if fn.exists() else '' upd = _add_jupyter_hooks(src, fn) if upd is not None: fn.write_text(upd) repo_path = _git_root() if repo_path is None: sys.stderr.write('Not in a git repository, git hooks cannot be installed.\n') return hook_path = repo_path/'.git'/'hooks' fn = hook_path/'post-merge' hook_path.mkdir(parents=True, exist_ok=True) fn.write_text("#!/bin/bash\nnbdev-trust") os.chmod(fn, os.stat(fn).st_mode | stat.S_IEXEC) cmd = 'git config --local include.path ../.gitconfig' (repo_path/'.gitconfig').write_text(f'''# Generated by nbdev-install-hooks # # If you need to disable this instrumentation do: # git config --local --unset include.path # # To restore: # {cmd} # [merge "nbdev-merge"] name = resolve conflicts with nbdev_fix driver = nbdev-merge %O %A %B %P ''') run(cmd) attrs_path = repo_path/'.gitattributes' nbdev_attr = '*.ipynb merge=nbdev-merge\n' try: attrs = attrs_path.read_text() if nbdev_attr not in attrs: if not attrs.endswith('\n'): attrs+='\n' attrs_path.write_text(attrs+nbdev_attr) except FileNotFoundError: attrs_path.write_text(nbdev_attr) print("Hooks are installed.") ``` -------------------------------- ### Launch JupyterLab Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/tutorial.ipynb Starts the JupyterLab application, which should open in a new browser tab. ```shell jupyter lab ``` -------------------------------- ### Get Patch Name Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/05_doclinks.ipynb Determines the class-prefix name for a function decorated with `patch` or `patch_to`. ```python def patch_name(o): """If `o` is decorated with `patch` or `patch_to`, return its class-prefix name""" if not isinstance(o, (ast.FunctionDef,ast.AsyncFunctionDef)): return o.name d = first([d for d in o.decorator_list if decor_id(d).startswith('patch')]) if not d: return o.name nm = decor_id(d) if nm=='patch': a = o.args.args[0].annotation if isinstance(a, ast.BinOp): return _binop_leafs(a, o) elif nm=='patch_to': a = d.args[0] else: return o.name return _sym_nm(a,o) ``` -------------------------------- ### Display nbdev Create Config Documentation Source: https://github.com/answerdotai/nbdev/blob/main/nbs/explanations/config.ipynb Displays documentation for the `nbdev_create_config` function. This is useful for understanding the parameters and usage of the configuration creation tool. ```python #| exec_doc #| echo: false DocmentTbl(nbdev_create_config) ``` -------------------------------- ### Define function '_f_y_nall' for export Source: https://github.com/answerdotai/nbdev/blob/main/tests/01_everything.ipynb A function starting with an underscore, marked for export and with the 'nall' suffix. ```python #| export def _f_y_nall(): ... ``` -------------------------------- ### Documenting a class with show_doc Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/08_showdoc.ipynb Shows how `show_doc` can be used to document a class, including its `__init__` method and properties. ```python #| hide class Foo: def __init__(self, d:str,e:int): """This is the docstring for the `__init__` method""" ... @property def some_prop(self): """This is a class property.""" return 'foo property' show_doc(Foo) ``` -------------------------------- ### Verify Current Directory Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/git_friendly_jupyter.ipynb Prints the current working directory. Useful for confirming the location before installing hooks. ```shell pwd ``` -------------------------------- ### Import nbdev modules and wildcard import Source: https://github.com/answerdotai/nbdev/blob/main/tests/01_everything.ipynb Demonstrates importing specific nbdev modules and using a wildcard import. ```python import nbdev.x,y,nbdev.z from nbdev.x import * ``` -------------------------------- ### Example of a cell processed by scrub_magics Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/extensions.ipynb A cell with a Jupyter magic line that will be removed during export when scrub_magics is enabled. ```python %%time #| export def my_func(): return 42 ``` -------------------------------- ### Example: Identifying changed cells Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/19_diff.ipynb Demonstrates how to use `changed_cells` to find the IDs of cells that have been modified in the notebook. ```python changed_cells(td/'test.ipynb') ``` -------------------------------- ### nbdev_release_both command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Releases both Conda and PyPI packages. This command is a convenience for deploying to both distribution channels. ```python #| export @call_parse def nbdev_release_both(version=None, **kwargs): "Release both conda and PyPI packages" from nbdev.release import release_both release_both(version=version, **kwargs) ``` -------------------------------- ### Document function parameters with docments Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/best_practices.ipynb Use fastcore.docments for a concise way to document function parameters, which nbdev renders beautifully. This example shows how to document the number of cards to draw and whether to draw with replacement. ```python def draw_n(n:int, # Number of cards to draw replace:bool=True # Draw with replacement? )->list: # List of cards """Draw `n` cards.""" ``` ```python #| echo: false #| output: asis print(div(DocmentTbl(draw_n)._repr_markdown_(), classes='py-2 px-3 mb-4 border rounded shadow-sm'.split())) ``` -------------------------------- ### Get Documentation Link for NbdevLookup Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/05_doclinks.ipynb Retrieves the documentation URL for the `NbdevLookup` class using the `doc` method. ```python c.doc('nbdev.doclinks.NbdevLookup') ``` -------------------------------- ### Generate Full Documentation with nbdev Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/14_quarto.ipynb Renders Quarto documentation and README.md for the project. It also ensures CONTRIBUTING.md is up-to-date. ```python #| export @call_parse @delegates(_nbglob_docs) def nbdev_docs( path:str=None, # Path to notebooks n_workers:int=defaults.cpus, # Number of workers **kwargs): """Create Quarto docs and README.md""" cache,cfg,path = _pre_docs(path, n_workers=n_workers, **kwargs) nbdev_readme.__wrapped__(path=path, chk_time=True) nbdev_contributing.__wrapped__(path=path, chk_time=True) _sprun(f'cd "{cache}" && quarto render --no-cache') shutil.rmtree(cfg.doc_path, ignore_errors=True) move(cache/cfg.doc_path.name, cfg.config_path) ``` -------------------------------- ### Substitute Layout Template Source: https://github.com/answerdotai/nbdev/blob/main/nbs/tutorials/extensions.ipynb Example of using the string template to format a Quarto div with specific layout and content. ```python _LAYOUT_STR.substitute( layout="column-margin", content="Some text to go on the sidebar" ) ``` -------------------------------- ### nbdev_migrate_config command example Source: https://github.com/answerdotai/nbdev/blob/main/nbs/api/13_cli.ipynb Migrates settings from `settings.ini` to `pyproject.toml`. This command helps in updating project configuration files. ```python #| export @call_parse def nbdev_migrate_config(): "Migrate settings.ini to pyproject.toml" from nbdev.migrate import nbdev_migrate_config nbdev_migrate_config() ```