### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Bash Script for Environment Setup Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_PyTorch_users A simple bash script to set up a development environment. It involves updating package lists and installing necessary packages. This is useful for reproducible environments. It's intended to be run in a Linux/macOS terminal. ```bash #!/bin/bash echo "Updating package lists..." apt-get update -y echo "Installing required packages..." apt-get install -y python3 python3-pip git echo "Environment setup complete." ``` -------------------------------- ### Install Documentation Requirements Source: https://docs.jaxstack.ai/en/latest/_sources/contributing Installs all necessary packages for contributing to the documentation from a requirements file. Ensure you are in the root of the repository before running this command. ```bash pip install -r docs/requirements.txt ``` -------------------------------- ### Import JAX and Check Version Source: https://docs.jaxstack.ai/en/latest/JAX_for_PyTorch_users This snippet imports the JAX library and prints the installed version. It's a basic setup step to ensure JAX is correctly installed and to verify the version being used. Requires the `jax` and `jax.numpy` libraries. ```python import jax import jax.numpy as jnp print(jax.__version__) ``` -------------------------------- ### Example Usage of MBConv Block in JAX/Flax Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model Demonstrates the practical usage of an initialized MBConv block with specific configurations. It shows how to set up normalization layers and input data, then call the block to get the output shape. This example requires `jax.numpy` and `functools.partial`. ```python from functools import partial norm_layer = partial(nnx.BatchNorm, epsilon=1e-3, momentum=0.99) x = jnp.ones((4, 28, 28, 32)) mod = MBConv(32, 64, 4, 0.25, 2, activation_layer=nnx.gelu, norm_layer=norm_layer) y = mod(x) y.shape ``` -------------------------------- ### Untitled No description -------------------------------- ### Install PyTorch and Torchvision Source: https://docs.jaxstack.ai/en/latest/data_loaders_on_gpu_with_jax Installs the necessary PyTorch and Torchvision libraries. These are fundamental for deep learning tasks and data loading with PyTorch. ```shell !pip install torch torchvision ``` -------------------------------- ### PartitionAttentionLayer Usage Examples (PyTorch) Source: https://docs.jaxstack.ai/en/latest/JAX_porting_PyTorch_model Demonstrates how to instantiate and use the `PartitionAttentionLayer` with different partitioning types ('window' and 'grid') and prints the resulting tensor shape. This example requires `jax` and `nnx` libraries. ```python x = jnp.ones((4, 224, 224, 36)) grid_size = (224, 224) mod = PartitionAttentionLayer( 36, 6, 7, "window", grid_size=grid_size, mlp_ratio=4, activation_layer=nnx.gelu, norm_layer=nnx.LayerNorm, attention_dropout=0.4, mlp_dropout=0.3, p_stochastic_dropout=0.2, ) y = mod(x) print(y.shape) mod = PartitionAttentionLayer( 36, 6, 7, "grid", grid_size=grid_size, mlp_ratio=4, activation_layer=nnx.gelu, norm_layer=nnx.LayerNorm, attention_dropout=0.4, mlp_dropout=0.3, p_stochastic_dropout=0.2, ) y = mod(x) print(y.shape) ``` -------------------------------- ### Install jupytext for Notebook Syncing (pip) Source: https://docs.jaxstack.ai/en/latest/contributing Installs the jupytext tool using pip, which is used to synchronize Jupyter notebooks with markdown files. ```bash python -m pip install jupytext ``` -------------------------------- ### Install Profiling Dependencies Source: https://docs.jaxstack.ai/en/latest/JAX_for_LLM_pretraining Installs necessary packages for TensorBoard profiling with TensorFlow and JAX. This includes tensorboard-plugin-profile, tensorflow, and tensorboard. ```python !pip install -Uq tensorboard-plugin-profile tensorflow tensorboard ``` -------------------------------- ### Install pre-commit Hook Manager Source: https://docs.jaxstack.ai/en/latest/contributing Installs the pre-commit framework, which is used to manage and run pre-commit hooks for checking code and file synchronization, particularly for notebooks. ```bash pip install pre-commit ``` -------------------------------- ### Untitled No description -------------------------------- ### Install Libraries with Pip Source: https://docs.jaxstack.ai/en/latest/JAX_for_LLM_pretraining Installs or upgrades the tiktoken, grain, and matplotlib Python libraries using pip. This command ensures that the necessary tools for tokenization, data loading, and visualization are available for the project. ```bash !pip install -Uq tiktoken grain matplotlib ``` -------------------------------- ### Untitled No description -------------------------------- ### Visualize Training Traces with TensorBoard Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_LLM_pretraining Launches TensorBoard to visualize training traces stored in the specified directory. This is crucial for analyzing performance bottlenecks. ```shell %tensorboard --logdir=$trace_dir ``` -------------------------------- ### Make HTTP GET Request with Requests in Python Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_PyTorch_users This Python code snippet shows how to perform an HTTP GET request to a specified URL using the 'requests' library. It includes basic error handling for network issues and checks the HTTP status code. Make sure 'requests' is installed (`pip install requests`). ```python import requests def fetch_data_from_api(url): try: response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) # Process the JSON response data = response.json() print("Data fetched successfully:") print(data) return data except requests.exceptions.RequestException as e: print(f"Error fetching data from {url}: {e}") return None # Example usage: # api_url = "https://api.example.com/data" # fetched_data = fetch_data_from_api(api_url) ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Install Hugging Face Datasets Library Source: https://docs.jaxstack.ai/en/latest/_sources/data_loaders_on_gpu_with_jax Installs the 'datasets' library from Hugging Face using pip. This is a prerequisite for loading and using datasets like MNIST. It ensures all necessary dependencies are met. ```bash !pip install datasets ``` -------------------------------- ### Jaxstack AI: Python API Interaction Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_visualizing_models_metrics Shows how to make a GET request to an API endpoint using the Python `requests` library. Ensure 'requests' is installed (`pip install requests`). ```python import requests url = "https://api.example.com/items" try: response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes data = response.json() print(data) except requests.exceptions.RequestException as e: print(f"Error making request: {e}") ``` -------------------------------- ### Python Jax Model Inference Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model Illustrates how to perform inference using a pre-trained model with the Jax library. This example assumes you have a Jax model and input data ready. Jax should be installed (`pip install jax jaxlib`). ```python import jax import jax.numpy as jnp # Assume 'model' is a pre-trained Jax model function # Assume 'input_data' is a Jax array def perform_inference(model, input_data): # JIT compile the model for performance inference_fn = jax.jit(model) # Perform inference predictions = inference_fn(input_data) return predictions ``` -------------------------------- ### Optax Optimizer Setup for JAX Models Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model Demonstrates how to set up an optimizer using the Optax library, commonly used with JAX and Flax for training neural networks. It shows the initialization of an optimizer and how it would be used in a training loop. ```python import jax import jax.numpy as jnp import optax # Define a simple loss function def mse_loss(params, x, y): # Assuming a simple linear model: y_pred = jnp.dot(x, params) y_pred = jnp.dot(x, params) return jnp.mean((y_pred - y) ** 2) # Initialize model parameters (e.g., for a linear regression) key = jax.random.PRNGKey(0) params = jax.random.normal(key, (3, 1)) # Example parameters # Create dummy data x_data = jnp.ones((10, 3)) y_data = jnp.zeros((10, 1)) # Set up an optimizer (e.g., Adam) optimizer = optax.adam(learning_rate=0.01) opt_state = optimizer.init(params) # Training step function (conceptual) @jax.jit def train_step(params, opt_state, x, y): loss, grads = jax.value_and_grad(mse_loss)(params, x, y) updates, opt_state = optimizer.update(grads, opt_state, params) params = optax.apply_updates(params, updates) return params, opt_state, loss # Example of one training step # params, opt_state, loss = train_step(params, opt_state, x_data, y_data) # print(f"Loss after one step: {loss}") ``` -------------------------------- ### Python Requests Library for HTTP Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model Demonstrates making an HTTP GET request using the `requests` library in Python. This is a standard way to interact with APIs in Python. The `requests` library must be installed (`pip install requests`). ```python import requests url = 'https://api.example.com/data' try: response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes data = response.json() print(data) except requests.exceptions.RequestException as e: print(f'Error fetching data: {e}') ``` -------------------------------- ### Python Range Function Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_PyTorch_users This example shows how to use the Python range() function to generate a sequence of numbers. It's commonly used in for loops. range(start, stop, step) generates numbers from start up to (but not including) stop, with a specified step. ```python # Generates numbers from 0 to 4 for i in range(5): print(i) # Generates numbers from 2 to 7 for j in range(2, 8): print(j) # Generates even numbers from 0 to 8 for k in range(0, 10, 2): print(k) ``` -------------------------------- ### Untitled No description -------------------------------- ### JaxStack AI Model and Training Setup (Python) Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_LLM_pretraining Initializes the JaxStack AI model, optimizer, and metrics. It also sets up the tokenizer and generates initial text. The code then enters a training loop, processing batches of text data, updating the model, and periodically printing metrics and generated text. Finally, it generates the concluding text. ```python model = create_model(rngs=nnx.Rngs(0)) optimizer = nnx.ModelAndOptimizer(model, optax.adam(1e-3)) metrics = nnx.MultiMetric( loss=nnx.metrics.Average('loss'), ) rng = jax.random.PRNGKey(0) start_prompt = "Once upon a time" start_tokens = tokenizer.encode(start_prompt)[:maxlen] generated_text = model.generate_text( maxlen, start_tokens ) print(f"Initial generated text:\n{generated_text}\n") metrics_history = { 'train_loss': [], } prep_target_batch = jax.vmap(lambda tokens: jnp.concatenate((tokens[1:], jnp.array([0])))) step = 0 for epoch in range(num_epochs): start_time = time.time() for batch in text_dl: if len(batch) % len(jax.devices()) != 0: continue # skip the remaining elements input_batch = jnp.array(jnp.array(batch).T) target_batch = prep_target_batch(input_batch) train_step(model, optimizer, metrics, jax.device_put((input_batch, target_batch), NamedSharding(mesh, P('batch', None)))) if (step + 1) % 200 == 0: for metric, value in metrics.compute().items(): metrics_history[f'train_{metric}'].append(value) metrics.reset() elapsed_time = time.time() - start_time print(f"Step {step + 1}, Loss: {metrics_history['train_loss'][-1]}, Elapsed Time: {elapsed_time:.2f} seconds") start_time = time.time() generated_text = model.generate_text( maxlen, start_tokens ) print(f"Generated text:\n{generated_text}\n") step += 1 # Final text generation generated_text = model.generate_text( maxlen, start_tokens ) print(f"Final generated text:\n{generated_text}") ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Initialize Model and Optimizer with Optax Source: https://docs.jaxstack.ai/en/latest/JAX_visualizing_models_metrics Sets up an optimizer (Stochastic Gradient Descent) using Optax and pairs it with the `SimpleNN` model using `nnx.ModelAndOptimizer`. This prepares the model for training. ```python import jax import optax optimizer = nnx.ModelAndOptimizer(model, optax.sgd(learning_rate=0.05)) ``` -------------------------------- ### Jax Model Training and Generation Source: https://docs.jaxstack.ai/en/latest/JAX_for_LLM_pretraining This code snippet demonstrates the initialization of a Jax model and optimizer, definition of training metrics, and the main training loop. It includes data preparation, the training step function (assumed to be defined elsewhere), metric computation, and text generation for monitoring training progress. Data is sharded using `NamedSharding` and `jax.device_put` for parallel processing, and `jax.vmap` is used to prepare target batches. ```python model = create_model(rngs=nnx.Rngs(0)) optimizer = nnx.ModelAndOptimizer(model, optax.adam(1e-3)) metrics = nnx.MultiMetric( loss=nnx.metrics.Average('loss'), ) rng = jax.random.PRNGKey(0) start_prompt = "Once upon a time" start_tokens = tokenizer.encode(start_prompt)[:maxlen] generated_text = model.generate_text( maxlen, start_tokens ) print(f"Initial generated text:\n{generated_text}\n") metrics_history = { 'train_loss': [], } prep_target_batch = jax.vmap(lambda tokens: jnp.concatenate((tokens[1:], jnp.array([0])))) step = 0 for epoch in range(num_epochs): start_time = time.time() for batch in text_dl: if len(batch) % len(jax.devices()) != 0: continue # skip the remaining elements input_batch = jnp.array(jnp.array(batch).T) target_batch = prep_target_batch(input_batch) train_step(model, optimizer, metrics, jax.device_put((input_batch, target_batch), NamedSharding(mesh, P('batch', None)))) if (step + 1) % 200 == 0: for metric, value in metrics.compute().items(): metrics_history[f'train_{metric}'].append(value) metrics.reset() elapsed_time = time.time() - start_time print(f"Step {step + 1}, Loss: {metrics_history['train_loss'][-1]}, Elapsed Time: {elapsed_time:.2f} seconds") start_time = time.time() generated_text = model.generate_text( maxlen, start_tokens ) print(f"Generated text:\n{generated_text}\n") step += 1 ``` -------------------------------- ### Vision Transformer Model Usage Example Source: https://docs.jaxstack.ai/en/latest/JAX_Vision_transformer Demonstrates how to instantiate and use the Vision Transformer model. It initializes a model with a specified number of classes and passes a dummy input tensor through it to obtain predictions. This example requires JAX and NumPy to be installed. ```python # Example usage for testing: x = jnp.ones((4, 224, 224, 3)) model = VisionTransformer(num_classes=1000) y = model(x) print("Predictions shape: ", y.shape) ``` -------------------------------- ### Untitled No description -------------------------------- ### Creating a Simple HTTP Request (Python) Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model This Python snippet shows how to make a GET request to a specified URL using the `requests` library. It prints the status code and the first 100 characters of the response text. Ensure the `requests` library is installed (`pip install requests`). ```python import requests def make_get_request(url): try: response = requests.get(url, timeout=10) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) print(f"Status Code: {response.status_code}") print(f"Response Text (first 100 chars): {response.text[:100]}...") except requests.exceptions.RequestException as e: print(f"Error making request to {url}: {e}") # Example Usage: # make_get_request('https://jsonplaceholder.typicode.com/posts/1') ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Basic API Request in Python Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_PyTorch_users A simple example of making an HTTP GET request to an API endpoint using the `requests` library in Python. This demonstrates fetching data from external services. ```python import requests # Define the API endpoint URL api_url = "https://jsonplaceholder.typicode.com/posts/1" try: # Make the GET request response = requests.get(api_url) # Check if the request was successful (status code 200) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) # Parse the JSON response data = response.json() # Print the data print("API Response:") print(data) except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") except ValueError as e: print(f"Failed to parse JSON response: {e}") ``` -------------------------------- ### Example Training Progress Output Source: https://docs.jaxstack.ai/en/latest/data_loaders_on_cpu_with_jax This snippet shows the typical output logged during a training loop, indicating the epoch number, time taken, and accuracy for both training and testing sets. This helps in monitoring model convergence. ```text Epoch 1 in 15.39 sec: Train Accuracy: 0.9158, Test Accuracy: 0.9196 Epoch 2 in 15.27 sec: Train Accuracy: 0.9372, Test Accuracy: 0.9384 Epoch 3 in 12.61 sec: Train Accuracy: 0.9492, Test Accuracy: 0.9468 Epoch 4 in 12.62 sec: Train Accuracy: 0.9569, Test Accuracy: 0.9532 Epoch 5 in 12.39 sec: Train Accuracy: 0.9630, Test Accuracy: 0.9579 Epoch 6 in 12.19 sec: Train Accuracy: 0.9674, Test Accuracy: 0.9615 Epoch 7 in 12.56 sec: Train Accuracy: 0.9708, Test Accuracy: 0.9650 Epoch 8 in 13.04 sec: Train Accuracy: 0.9737, Test Accuracy: 0.9671 ``` -------------------------------- ### Untitled No description -------------------------------- ### Array Manipulation with NumPy (Python) Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_PyTorch_users This example demonstrates creating and manipulating NumPy arrays. NumPy is crucial for numerical operations in Python, offering efficient array handling. Ensure the 'numpy' library is installed. ```python import numpy as np def create_numpy_array(data): """Creates a NumPy array from a list. Args: data (list): The list of elements to convert. Returns: np.ndarray: The created NumPy array. """ return np.array(data) # Example usage: # my_list = [1, 2, 3, 4, 5] # np_array = create_numpy_array(my_list) # print(np_array) # print(np_array * 2) # Element-wise multiplication ``` -------------------------------- ### JavaScript `Object.values()` Example Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_time_series_classification Shows the use of `Object.values()` to get an array of a given object's own enumerable property values. Useful for accessing just the values of an object. ```javascript const personInfo = { name: 'David', occupation: 'Engineer' }; const values = Object.values(personInfo); console.log(values); // ["David", "Engineer"] ``` -------------------------------- ### JAXSTACK AI: Logging Setup Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_LLM_pretraining This snippet shows how to set up basic logging for an application. Proper logging is essential for debugging and monitoring. It configures the logging level and format. The `logging` module is part of Python's standard library. ```python import logging def setup_logging(level=logging.INFO): """Sets up basic logging configuration.""" logging.basicConfig( level=level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) # Example usage: # setup_logging() # logging.info('Application started') # logging.warning('Something might be wrong') # logging.error('An error occurred') ``` -------------------------------- ### MaxVitLayer Instantiation and Forward Pass Example (Python) Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model Demonstrates how to instantiate a MaxVitLayer with specific configuration parameters and perform a forward pass with a dummy input tensor. This example includes calculating the grid size using a helper function and setting up normalization and activation layers. ```python x = jnp.ones((4, 224, 224, 3)) grid_size = _get_conv_output_shape((224, 224), kernel_size=3, stride=2, padding=1) norm_layer = partial(nnx.BatchNorm, epsilon=1e-3, momentum=0.99) mod = MaxVitLayer( 3, 36, squeeze_ratio=0.25, expansion_ratio=4, stride=2, norm_layer=norm_layer, activation_layer=nnx.gelu, head_dim=6, mlp_ratio=4, mlp_dropout=0.5, attention_dropout=0.4, p_stochastic_dropout=0.3, partition_size=7, grid_size=grid_size, ) y = mod(x) print(y.shape) ``` -------------------------------- ### JavaScript `Object.keys()` Example Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_time_series_classification Illustrates the use of `Object.keys()` to get an array of a given object's own enumerable property names. Useful for iterating over object keys. ```javascript const personInfo = { name: 'David', occupation: 'Engineer' }; const keys = Object.keys(personInfo); console.log(keys); // ["name", "occupation"] ``` -------------------------------- ### Install Hugging Face Datasets Library Source: https://docs.jaxstack.ai/en/latest/_sources/data_loaders_on_cpu_with_jax Installs the Hugging Face `datasets` library, which is essential for loading and processing datasets. This command-line instruction fetches the latest version of the library and its dependencies, enabling efficient data handling for machine learning tasks. ```bash pip install datasets ``` -------------------------------- ### JAX: Relative Positional Multi-Head Attention Example Usage Source: https://docs.jaxstack.ai/en/latest/JAX_porting_PyTorch_model This snippet demonstrates how to instantiate and use the `RelativePositionalMultiHeadAttention` module in JAX. It initializes the module with specified dimensions and then passes a dummy input tensor to get an output. ```python import jax import jax.numpy as jnp # Assuming RelativePositionalMultiHeadAttention class is defined as above # ... (class definition would be here or imported) x = jnp.ones((4, 32, 49, 64)) mod = RelativePositionalMultiHeadAttention(64, 16, 49) y = mod(x) print(y.shape) ``` -------------------------------- ### Untitled No description -------------------------------- ### JaxStack AI: Jax Example for GPU Computation Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model This snippet demonstrates how to use Jax for GPU computation, including array manipulation and basic mathematical operations. It requires the Jax library to be installed. The output will be the result of the computations performed on the GPU. ```python import jax.numpy as jnp from jax import device_put # Example data data = jnp.array([1.0, 2.0, 3.0]) # Move data to GPU data_gpu = device_put(data, jax.devices('gpu')[0]) # Perform computation on GPU result = data_gpu * 2 print(result) ``` -------------------------------- ### Docker Entrypoint Script for Jaxstack AI Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_for_PyTorch_users This shell script serves as the entrypoint for the Jaxstack AI Docker container. It executes necessary setup commands and then runs the main application process. It's essential for container initialization and application startup. ```bash #!/bin/bash # Perform any necessary setup tasks here echo "Starting Jaxstack AI..." # Execute the main application command exec "$@" ``` -------------------------------- ### Untitled No description -------------------------------- ### Python API Call with Requests Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model This Python code snippet shows how to make a GET request to an external API using the 'requests' library. It retrieves data from a specified URL and handles potential errors. The 'requests' library must be installed. ```python import requests def get_api_data(url): try: response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching data: {e}") return None # Example usage: # api_url = "https://api.example.com/data" # data = get_api_data(api_url) ``` -------------------------------- ### API Request with Requests Library Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model This code snippet shows how to make an HTTP GET request to a specified URL using the Python Requests library. It handles potential errors and returns JSON data. The 'requests' library must be installed. ```python import requests url = "https://api.example.com/data" try: response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes data = response.json() print(data) except requests.exceptions.RequestException as e: print(f"Error making request: {e}") ``` -------------------------------- ### Move and Add New Notebook Source: https://docs.jaxstack.ai/en/latest/_sources/contributing Moves a new tutorial notebook to the correct directory within the docs and then uses jupytext to set the notebook to sync with markdown files using the 'myst' format. ```bash mv ~/new-tutorial.ipynb docs/source/new_tutorial.ipynb jupytext --set-formats ipynb,md:myst docs/source/new_tutorial.ipynb ``` -------------------------------- ### Untitled No description -------------------------------- ### JavaScript Fetch API Example Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_porting_PyTorch_model Illustrates how to make an HTTP GET request using the Fetch API in JavaScript to retrieve data from a remote URL. This is crucial for interacting with web services. Browser or Node.js environment with fetch support is required. ```javascript async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } fetchData('https://api.example.com/data'); ``` -------------------------------- ### JavaScript Date Object Manipulation Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_time_series_classification Provides examples of creating and manipulating JavaScript Date objects, including getting the current date, formatting dates, and performing date calculations. Important for time-related functionalities. ```javascript const today = new Date(); console.log(today.toDateString()); ``` -------------------------------- ### Pre-commit Workflow for Notebook Edits Source: https://docs.jaxstack.ai/en/latest/_sources/contributing Demonstrates the workflow for editing an existing notebook. It involves installing pre-commit, staging changes, running pre-commit checks, staging updates from pre-commit, and committing the changes. ```bash pip install pre-commit git add docs/source/new_tutorial.* pre-commit run git add docs/source/new_tutorial.* git commit -m "update new tutorial" ``` -------------------------------- ### JavaScript Fetch API for Network Requests Source: https://docs.jaxstack.ai/en/latest/_sources/JAX_time_series_classification Provides an example of using the Fetch API in JavaScript to make network requests (e.g., GET requests). It's a modern standard for handling HTTP requests in browsers. ```javascript fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ```