Skip to content

creating notebooks

Mile Shi edited this page May 26, 2025 · 2 revisions

Tutorial: Creating Notebooks

Learn how to create and manage interactive notebooks in the Intelligent IDE. This tutorial will guide you through the process of creating different types of notebooks, adding content, and collaborating with others.

Prerequisites

Before starting this tutorial, ensure you have:

  • Logged into the Intelligent IDE extension
  • Joined a course or have course creation permissions
  • Basic understanding of the VS Code interface
  • Python or JavaScript knowledge (for code examples)

Getting Started

Step 1: Creating Your First Notebook

Method 1: Using the Command Palette

  1. Open VS Code with the Intelligent IDE extension installed
  2. Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS)
  3. Type "Intelligent IDE: Create New Notebook"
  4. Select the command from the dropdown
// The extension will prompt you for:
{
  "notebook_name": "My First Notebook",
  "course_id": "CS101", 
  "language": "python", // or "javascript", "markdown"
  "template": "blank" // or "exercise", "assignment"
}

Method 2: Using the File Explorer

  1. Right-click in the file explorer
  2. Select "New Intelligent IDE Notebook"
  3. Choose your course and notebook settings
  4. Click "Create Notebook"

Method 3: Course Dashboard

  1. Navigate to your course dashboard
  2. Click the "Create New Content" button
  3. Select "Interactive Notebook"
  4. Fill in the notebook details

Step 2: Notebook Setup and Configuration

Once created, you'll see the notebook interface:

{
  "notebook_info": {
    "name": "My First Notebook",
    "course": "CS101 - Python Fundamentals", 
    "created_by": "You",
    "created_at": "2024-01-15T10:00:00Z",
    "language": "python",
    "collaborators": [],
    "status": "draft"
  }
}

Configuring Notebook Settings

  1. Click the gear icon in the notebook toolbar
  2. Set permissions:
    • 📝 Edit Access: Who can modify the notebook
    • 👁️ View Access: Who can read the notebook
    • 🔄 Collaboration: Enable real-time editing
  3. Choose execution environment:
    • 🐍 Python 3.11 (default)
    • 📊 Python with Data Science (includes pandas, numpy)
    • 🌐 JavaScript/Node.js
    • 🎯 Custom Environment

Working with Different Cell Types

1. Code Cells

Creating a Python Code Cell

  1. Click the "+ Code" button in the toolbar
  2. Start typing your Python code:
# This is a Python code cell
import math

def calculate_circle_area(radius):
    """Calculate the area of a circle given its radius."""
    return math.pi * radius ** 2

# Test the function
radius = 5
area = calculate_circle_area(radius)
print(f"The area of a circle with radius {radius} is {area:.2f}")
  1. Execute the cell by pressing Shift+Enter or clicking the play button
  2. View the output below the cell

JavaScript Code Cell Example

// JavaScript code cell
function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

// Generate first 10 Fibonacci numbers
const fibSequence = [];
for (let i = 0; i < 10; i++) {
    fibSequence.push(fibonacci(i));
}

console.log("Fibonacci sequence:", fibSequence);

2. Markdown Cells

Creating Rich Text Documentation

  1. Click "+ Markdown" to add a markdown cell
  2. Write your documentation:
# Data Analysis Tutorial

## Introduction
This notebook demonstrates basic data analysis techniques using Python and pandas.

### Learning Objectives
- Load and explore datasets
- Perform basic statistical analysis
- Create visualizations

> **Note**: Make sure to install required libraries before running code cells.

### Prerequisites
- Basic Python knowledge
- Understanding of data structures

Formatting Tips

  • Headers: Use #, ##, ### for different levels
  • Emphasis: *italic* and **bold** text
  • Lists: Use - or 1. for bullet and numbered lists
  • Code: Use backticks for inline code
  • Links: [link text](url) for hyperlinks

3. Output Cells

Output cells display results from code execution:

# This code will generate an output cell
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Sine Wave')
plt.legend()
plt.grid(True)
plt.show()

# The plot will appear in an output cell below

4. Exercise Cells

For educational content, create interactive exercises:

# Exercise Cell - Student completes this
def calculate_factorial(n):
    """
    Calculate the factorial of a number.
    
    Args:
        n (int): Non-negative integer
        
    Returns:
        int: Factorial of n
    """
    # TODO: Implement factorial calculation
    # Hint: Use a loop or recursion
    pass

# Test your implementation
assert calculate_factorial(5) == 120
assert calculate_factorial(0) == 1
print("All tests passed!")

Notebook Templates

1. Blank Notebook Template

{
  "template": "blank",
  "description": "Empty notebook for free-form content creation",
  "default_cells": [
    {
      "type": "markdown",
      "content": "# New Notebook\n\nAdd your content here..."
    },
    {
      "type": "code", 
      "content": "# Your code here\nprint('Hello, World!')"
    }
  ]
}

2. Assignment Template

{
  "template": "assignment",
  "description": "Structured template for homework assignments",
  "sections": [
    "instructions",
    "starter_code",
    "exercises",
    "submission_area"
  ]
}

3. Data Science Template

# Data Science Notebook Template

# 1. Import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# 2. Load Data
# data = pd.read_csv('your_dataset.csv')

# 3. Explore Data
# data.head()
# data.info()
# data.describe()

# 4. Data Cleaning
# Handle missing values, outliers, etc.

# 5. Analysis
# Perform your analysis here

# 6. Visualization
# Create plots and charts

# 7. Conclusions
# Summarize your findings

Collaboration Features

1. Real-time Collaborative Editing

Enabling Collaboration

  1. Open notebook settings
  2. Toggle "Enable Real-time Collaboration"
  3. Add collaborators by email or username
  4. Set permissions (view, edit, admin)
{
  "collaboration_settings": {
    "real_time_editing": true,
    "collaborators": [
      {
        "user": "alice@university.edu",
        "permission": "edit",
        "joined_at": "2024-01-15T14:00:00Z"
      },
      {
        "user": "bob@university.edu", 
        "permission": "view",
        "joined_at": "2024-01-15T14:15:00Z"
      }
    ]
  }
}

Working with Collaborators

  • See live cursors of other users editing
  • Chat in real-time using the integrated chat panel
  • View edit history and track changes
  • Resolve conflicts automatically with merge algorithms

2. Version Control

Creating Checkpoints

  1. Click "Save Checkpoint" in the toolbar
  2. Add description: "Completed data loading section"
  3. View checkpoint history in the version panel
📋 Checkpoint History

🔄 **v1.3** - "Added visualization section" (2 hours ago)
🔄 **v1.2** - "Completed data cleaning" (4 hours ago)  
🔄 **v1.1** - "Initial analysis code" (1 day ago)
🔄 **v1.0** - "Created notebook" (2 days ago)

Branching and Merging

  • Create branches for experimental changes
  • Merge branches back to main version
  • Compare versions side-by-side
  • Restore from any checkpoint

Advanced Features

1. Interactive Widgets

# Interactive widgets for exploration
import ipywidgets as widgets
from IPython.display import display

# Create slider widget
radius_slider = widgets.IntSlider(
    value=5,
    min=1,
    max=20,
    step=1,
    description='Radius:'
)

# Function to update based on slider
def update_circle_area(radius):
    area = math.pi * radius ** 2
    print(f"Circle area with radius {radius}: {area:.2f}")

# Create interactive widget
widgets.interact(update_circle_area, radius=radius_slider)

2. Custom Visualizations

# Custom interactive plots with Plotly
import plotly.graph_objects as go
import plotly.express as px

# Create interactive scatter plot
fig = px.scatter(
    x=[1, 2, 3, 4, 5],
    y=[2, 4, 1, 3, 5],
    title="Interactive Scatter Plot",
    hover_data=['Point 1', 'Point 2', 'Point 3', 'Point 4', 'Point 5']
)

fig.show()

3. External Data Integration

# Connect to databases and APIs
import requests
import sqlite3

# API data fetching
def fetch_weather_data(city):
    api_key = "your_api_key"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
    response = requests.get(url)
    return response.json()

# Database connections
conn = sqlite3.connect('course_data.db')
query = "SELECT * FROM student_scores WHERE course_id = 'CS101'"
df = pd.read_sql_query(query, conn)

Sharing and Publishing

1. Export Options

Export to PDF

  1. Click "Export" in the toolbar
  2. Select "PDF Report"
  3. Choose export options:
    • Include code cells
    • Include output
    • Include markdown
  4. Download the generated PDF

Export to HTML

# Command line export (for advanced users)
intelligent-ide export notebook.ipynb --format html --include-code --include-output

Export to GitHub

  1. Connect your GitHub account
  2. Select repository and branch
  3. Choose export format (notebook, markdown, script)
  4. Push to repository

2. Sharing Links

Create Shareable Links

  1. Click "Share" button
  2. Set permissions:
    • 🔗 View only: Others can see but not edit
    • ✏️ Edit access: Others can modify content
    • 🎓 Student access: Restricted editing for assignments
  3. Copy link and share with others

Embed in Websites

<!-- Embed notebook in external website -->
<iframe 
    src="https://intelligent-ide.edu/embed/notebook/abc123"
    width="100%" 
    height="600px"
    frameborder="0">
</iframe>

Best Practices

1. Organization and Structure

Notebook Organization

# Good Notebook Structure

## 1. Introduction and Overview
- Purpose of the notebook
- Learning objectives
- Prerequisites

## 2. Setup and Imports
- Import necessary libraries
- Define constants and configurations

## 3. Main Content
- Organized into logical sections
- Clear headings and documentation

## 4. Exercises/Activities
- Interactive elements
- Practice problems

## 5. Conclusion
- Summary of key points
- Next steps or additional resources

Cell Organization

  • Keep cells focused: One concept per cell
  • Use descriptive comments: Explain your code
  • Separate concerns: Data loading, processing, visualization
  • Consistent naming: Use clear variable names

2. Documentation Best Practices

# Documentation Guidelines

## Code Comments
- Explain **why**, not just **what**
- Use docstrings for functions
- Comment complex algorithms

## Markdown Cells
- Provide context and explanations
- Use headers for organization
- Include learning objectives
- Add relevant links and resources

3. Collaboration Etiquette

Working with Others

  1. Communicate changes: Use descriptive checkpoint messages
  2. Respect others' work: Don't delete without discussion
  3. Use chat feature: Coordinate real-time editing
  4. Test before sharing: Ensure code runs correctly

Code Review

# Example of well-documented collaborative code
def analyze_student_performance(scores_df):
    """
    Analyze student performance data and generate insights.
    
    Args:
        scores_df (pandas.DataFrame): DataFrame with student scores
        
    Returns:
        dict: Analysis results including mean, median, and distribution
        
    Author: Alice Chen
    Last modified: 2024-01-15
    Review: Bob Smith approved changes
    """
    # Implementation here...
    pass

Troubleshooting

Common Issues

Notebook Won't Load

# Check notebook service status
curl -X GET "/api/notebooks/health"

# Clear browser cache and refresh
# Or try incognito/private browsing mode

Code Execution Errors

# Debug execution environment
import sys
print("Python version:", sys.version)
print("Available packages:", [pkg for pkg in sys.modules if not pkg.startswith('_')])

# Check memory usage
import psutil
print(f"Memory usage: {psutil.virtual_memory().percent}%")

Collaboration Sync Issues

  1. Refresh the notebook browser tab
  2. Check internet connection stability
  3. Save checkpoint and reload
  4. Contact instructor if issues persist

Performance Optimization

# Optimize notebook performance
# 1. Clear unused variables
del large_dataset

# 2. Use generators for large data
data_generator = (x for x in range(1000000))

# 3. Profile code execution
%timeit your_function()

# 4. Monitor memory usage
%memit your_function()

Next Steps

After completing this tutorial, you should be able to:

  • ✅ Create different types of notebooks
  • ✅ Add and manage various cell types
  • ✅ Collaborate with others in real-time
  • ✅ Export and share your work
  • ✅ Follow best practices for notebook organization

Recommended Follow-up Tutorials

  1. Working with Notebooks - Advanced notebook features
  2. Submitting Assignments - How to submit notebook assignments
  3. Using Q&A System - Getting help with your notebooks

Additional Resources

Happy notebook creation! 🎉

Clone this wiki locally