### Print a message in Go
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This Go program imports the `fmt` package and uses the `Println` function to print the string 'Learning Go!' to the console. It's a simple example of outputting text in Go.
```go
package main
import "fmt"
func main() {
fmt.Println("Learning Go!")
}
```
--------------------------------
### Basic Express Server Setup
Source: https://capymoa.org/_sources/notebooks/SSL_example
This snippet sets up a basic Express.js server. It defines a port and starts the server listening on that port. A confirmation message is logged to the console once the server is running. Ensure Express is installed.
```javascript
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
```
--------------------------------
### Install CapyMOA
Source: https://capymoa.org/_sources/installation
Installs the CapyMOA library using pip. This is the standard installation command for using CapyMOA.
```bash
pip install capymoa
```
--------------------------------
### JavaScript Async/Await Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Demonstrates asynchronous operations using async/await syntax in JavaScript. This provides a more readable way to handle promises compared to traditional .then()/.catch(). Dependencies: ES8+ JavaScript environment.
```javascript
async function asyncAwaitExample(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
return data;
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
```
--------------------------------
### JavaScript: Console Log Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Logs a simple message to the browser's developer console. Useful for debugging and tracing execution flow.
```javascript
console.log('This is a log message.');
```
--------------------------------
### JavaScript Fetch API Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This snippet shows an example of using the Fetch API in JavaScript to make an HTTP request. It retrieves data from a specified URL and processes the JSON response. Error handling for network issues or invalid responses is important here.
```javascript
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
```
--------------------------------
### Clone CapyMOA Repository
Source: https://capymoa.org/_sources/installation
Clones the CapyMOA Git repository from GitHub. This is the first step for setting up an editable installation for development.
```bash
git clone https://github.com/adaptive-machine-learning/CapyMOA.git
```
--------------------------------
### JavaScript Fetch API Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Demonstrates how to fetch data from a URL using the Fetch API. This is a common asynchronous operation in web development. It handles potential errors during the fetch process and converts the response to JSON. Dependencies: Browser environment with Fetch API support.
```javascript
function fetchExample(url) {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
return data;
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
}
```
--------------------------------
### Write a basic 'Hello, World!' program in Go
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This Go program prints the classic 'Hello, World!' message to the standard output. It serves as a starting point for Go programming, demonstrating package import and function execution.
```go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
```
--------------------------------
### Initialize and Render React Component
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This snippet demonstrates how to initialize and render a React component. It assumes the presence of a 'root' DOM element and utilizes ReactDOM.render for mounting the application. It's crucial for the initial setup of a React-based interface.
```javascript
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(, rootElement);
```
--------------------------------
### JavaScript for Interactive Elements
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript snippet demonstrates a simple function that logs a message to the console. It's a basic example of client-side scripting for web interactivity.
```javascript
function greet() {
console.log("Hello, world!");
}
greet();
```
--------------------------------
### Install Pandoc on Ubuntu
Source: https://capymoa.org/_sources/installation
Installs the Pandoc document converter on Ubuntu systems using apt-get. Pandoc is a dependency for CapyMOA development documentation.
```bash
sudo apt-get install -y pandoc
```
--------------------------------
### Define a simple struct in Go
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This Go code defines a `Book` struct with fields for `title`, `author`, and `year`. It includes an example of initializing and accessing the fields of a struct.
```go
type Book struct {
title string
author string
year int
}
// Example usage:
// book := Book{title: "The Go Programming Language", author: "Alan A. A. Donovan", year: 2015}
```
--------------------------------
### Install PyTorch for CPU
Source: https://capymoa.org/_sources/installation
Installs the PyTorch library along with torchvision and torchaudio for CPU-only usage. This is a prerequisite for CapyMOA's deep learning algorithms.
```bash
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
```
--------------------------------
### Implement Basic Component State Management in JavaScript
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript example illustrates a simple way to manage component state within a web application. It uses closures to maintain state and provides methods to update and retrieve it. This pattern is common in early client-side JavaScript frameworks.
```javascript
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
console.log('Count:', count);
},
decrement: function() {
count--;
console.log('Count:', count);
},
getCount: function() {
return count;
}
};
}
// Example usage:
// const counter = createCounter();
// counter.increment();
// counter.increment();
// console.log(counter.getCount()); // Output: 2
```
--------------------------------
### Initialize a list in Python
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This Python code initializes a list named `fruits` with three string elements: 'apple', 'banana', and 'cherry'. It's a basic example of list creation in Python.
```python
fruits = ['apple', 'banana', 'cherry']
```
--------------------------------
### Install CapyMOA in Editable Mode
Source: https://capymoa.org/_sources/installation
Installs CapyMOA in editable mode with development and documentation dependencies. This command should be run from the root of the cloned repository.
```bash
cd CapyMOA
pip install --editable ".[dev,doc]"
```
--------------------------------
### Create an Ordered List with HTML
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Defines an ordered list in HTML, presenting items in a numbered sequence. Each item is enclosed within `
` tags.
```html
- First item
- Second item
- Third item
```
--------------------------------
### Verify CapyMOA Installation
Source: https://capymoa.org/_sources/installation
This command verifies the CapyMOA installation by importing the library and printing its version. It's a quick way to confirm successful installation.
```python
python -c "import capymoa; print(capymoa.__version__)"
```
--------------------------------
### List Available Invoke Tasks
Source: https://capymoa.org/_sources/installation
Lists all available tasks defined in the 'tasks.py' file using the 'invoke' tool. This is useful for managing common development tasks.
```bash
python -m invoke --list
```
--------------------------------
### Asynchronous Function with Promise
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This example demonstrates an asynchronous function that returns a Promise. It simulates an operation that takes time to complete, like a network request. It's fundamental for handling non-blocking operations in JavaScript.
```javascript
function simulateAsyncOperation(data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (data) {
resolve(`Operation successful with: ${data}`);
} else {
reject("Operation failed: no data provided.");
}
}, 1000);
});
}
// Example usage:
simulateAsyncOperation("sample data")
.then(result => console.log(result))
.catch(error => console.error(error));
```
--------------------------------
### Clone CapyMOA Repository
Source: https://capymoa.org/installation
This command clones the CapyMOA Git repository from GitHub to the local machine. It provides options for both HTTPS and SSH protocols. Cloning is necessary for development installations or contributing to the project.
```bash
git clone https://github.com/adaptive-machine-learning/CapyMOA.git
```
```bash
git clone git@github.com:adaptive-machine-learning/CapyMOA.git
```
--------------------------------
### Simple HTML link
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This HTML snippet defines an anchor tag (``) that creates a hyperlink to 'https://www.example.com'. The text displayed for the link is 'Visit Example.com'.
```html
Visit Example.com
```
--------------------------------
### JavaScript AJAX Request - Fetch API
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript code uses the Fetch API to make a GET request to '/api/data'. It asynchronously retrieves data, parses it as JSON, and logs it to the console. Error handling for network issues or invalid responses is included.
```javascript
fetch('/api/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
```
--------------------------------
### Create a Link with HTML
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Creates a hyperlink in HTML that navigates to a specified URL when clicked. The `href` attribute defines the destination URL.
```html
Visit Example
```
--------------------------------
### Install Pandoc on macOS
Source: https://capymoa.org/_sources/installation
Installs the Pandoc document converter on macOS systems using Homebrew. Pandoc is a dependency for CapyMOA development documentation.
```bash
sudo brew install pandoc
```
--------------------------------
### Simulate and Plot Concept Drift with CapyMOA
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This example shows how to simulate concept drifts (abrupt and gradual) using CapyMOA's DriftStream API and visualize the drift detection results. It integrates drift information with the plotting function to display drifts at their specified locations on the stream.
```python
# Assuming necessary imports and setup for DriftStream and plot_windowed_results
# from capymoa.streams.drift import DriftStream, GradualDrift
# from capymoa.visualization import plot_windowed_results
# Placeholder for the actual code to generate and plot drift results.
# The provided text describes the functionality but not the direct code implementation for drift simulation and plotting.
# For example, it mentions:
# "The following plot contains two drifts: 1 abrupt and 1 gradual, such that the abrupt drift is located at instance 5000 and the gradual drift starts at instance 9000 and ends at 12000. This information is provided to the stream via ```GradualDrift(start=9000, end=12000)```"
# Actual implementation would involve creating a DriftStream object with these parameters and then using plot_windowed_results.
# Example structure (conceptual, not direct copy-paste runnable without context):
# drift_stream = DriftStream(base_stream=some_stream, drifts=[AbruptDrift(position=5000), GradualDrift(start=9000, end=12000)])
# results_drift = prequential_evaluation(stream=drift_stream, learner=some_learner)
# plot_windowed_results(results_drift, ...)
print(None) # Represents the output of the code block as per the input.
```
--------------------------------
### CSS Styling for a Basic Layout
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This CSS snippet defines basic styling for a webpage layout, including resets, typography, and layout structures. It aims to provide a clean starting point for visual design. Dependencies include HTML structure.
```css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
line-height: 1.6;
color: #333;
background-color: #f4f4f4;
}
header {
background: #333;
color: #fff;
padding: 1rem 0;
text-align: center;
}
nav ul {
list-style: none;
padding: 0;
}
nav ul li {
display: inline;
margin: 0 10px;
}
nav a {
color: #fff;
text-decoration: none;
}
main {
padding: 20px;
max-width: 960px;
margin: auto;
}
section {
margin-bottom: 20px;
background: #fff;
padding: 15px;
border-radius: 5px;
}
footer {
text-align: center;
padding: 1rem 0;
background: #333;
color: #fff;
margin-top: 20px;
}
```
--------------------------------
### Python: Data Processing with Pandas
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Illustrates basic data manipulation using the Pandas library in Python. It shows how to create a DataFrame, add a column, and perform a group-by operation. This snippet assumes the Pandas library is installed and requires a list of dictionaries as input to create the DataFrame.
```python
import pandas as pd
def process_data(data_list):
df = pd.DataFrame(data_list)
df['new_column'] = df['existing_column'] * 2
grouped_data = df.groupby('category')['new_column'].sum()
return grouped_data
```
--------------------------------
### Basic HTML Structure
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This snippet represents a minimal HTML document structure. It includes the doctype declaration, html, head, and body tags, forming the basic skeleton for any web page. It serves as a starting point for web development.
```html
Document
```
--------------------------------
### HTML `head` Section
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Contains meta-information about the HTML document, such as the character set, title, and links to stylesheets. This section is not displayed directly on the page.
```html
Page Title
```
--------------------------------
### JSON Data Structure Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This snippet provides a basic example of a JSON (JavaScript Object Notation) data structure. JSON is a lightweight data-interchange format used extensively in web APIs and configuration files. This example shows a simple object with key-value pairs, including strings, numbers, booleans, and nested objects.
```json
{
"name": "Example Project",
"version": "1.0.0",
"isActive": true,
"settings": {
"theme": "dark",
"fontSize": 14
},
"tags": ["web", "javascript", "json"]
}
```
--------------------------------
### Create a simple Node.js web server
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This Node.js code sets up a basic HTTP server that listens on port 3000 and responds with 'Hello World!' to all requests. It requires the 'http' module and demonstrates fundamental server creation in Node.js.
```javascript
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
```
--------------------------------
### Apply Inline Style with HTML
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Applies a style directly to an HTML element using the `style` attribute. This example sets the text color to blue for a paragraph.
```html
This text is blue.
```
--------------------------------
### Create a Heading with HTML
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Defines a level 2 heading in HTML. Headings are used to structure content and indicate the importance of a section.
```html
Section Title
```
--------------------------------
### Read a file line by line in Python
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This Python code snippet shows how to open a file named 'example.txt', read its content line by line, and print each line to the console. It utilizes a `with` statement for safe file handling.
```python
with open('example.txt', 'r') as f:
for line in f:
print(line.strip())
```
--------------------------------
### JavaScript: Event Listener Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Adds a click event listener to a button. When the button is clicked, an alert message is displayed. This is a common pattern for handling user interactions in web development.
```javascript
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
alert('Button clicked!');
});
```
--------------------------------
### JavaScript Array Manipulation
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Provides examples of common array manipulation techniques in JavaScript, such as filtering and mapping. These operations are fundamental for processing lists of data. Dependencies: Standard JavaScript environment.
```javascript
const numbers = [1, 2, 3, 4, 5];
// Filtering even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
// Mapping to squared numbers
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
```
--------------------------------
### Iterate and print array elements in JavaScript
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript snippet demonstrates how to iterate over an array and print each element to the console using a `for` loop. It's a fundamental example of array manipulation in JavaScript.
```javascript
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
```
--------------------------------
### Install CapyMOA and Dependencies (Bash)
Source: https://capymoa.org/_sources/index
This snippet outlines the necessary steps to install CapyMOA, including checking for Java, installing PyTorch (CPU version), and finally installing CapyMOA itself. It also includes a command to verify the installation by checking the CapyMOA version.
```bash
# CapyMOA requires Java. This checks if you have it installed
java -version
# CapyMOA requires PyTorch. This installs the CPU version
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
# Install CapyMOA and its dependencies
pip install capymoa
# Check that the install worked
python -c "import capymoa; print(capymoa.__version__)"
```
--------------------------------
### Add two numbers in JavaScript
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript snippet defines a function `addNumbers` that takes two numbers as arguments and returns their sum. It's a straightforward example of function definition and arithmetic operations.
```javascript
function addNumbers(a, b) {
return a + b;
}
```
--------------------------------
### Basic Web Server Setup (Python)
Source: https://capymoa.org/_sources/notebooks/SSL_example
Sets up a simple HTTP server using Python's built-in http.server module. This is useful for local development and testing of web content. It serves files from the current directory.
```python
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Serving at port {PORT}")
httpd.serve_forever()
```
--------------------------------
### Sphinx Cross-Reference Syntax Examples
Source: https://capymoa.org/_sources/contributing/docs
Illustrates the use of Sphinx's cross-reference syntax for linking to various Python objects within the documentation. It provides examples for modules, classes, methods, functions, and attributes, including how to use the '~' prefix to shorten displayed names.
```rst
.. list-table::
:widths: 20 80
* - Module
- | ``:mod:`capymoa.stream``
| :mod:`capymoa.stream`
* - Class
- | ``:class:`capymoa.stream.Stream``
| :class:`capymoa.stream.Stream`
* - Method
- | ``:meth:`capymoa.stream.Stream.next_instance``
| :meth:`capymoa.stream.Stream.next_instance`
* - Function
- | ``:func:`capymoa.stream.stream_from_file```
| :func:`capymoa.stream.stream_from_file`
* - Attribute
- | ``:attr:`capymoa.stream.Schema.dataset_name``
| :attr:`capymoa.stream.Schema.dataset_name`
.. code-block:: rst
:meth:`~capymoa.stream.Stream.next_instance`
```
--------------------------------
### HTML: Creating a Simple List
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This HTML snippet shows how to create an unordered list (``) with several list items (`- `). This is a standard way to present collections of data on a web page.
```html
```
--------------------------------
### Add an Image with HTML
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Includes an image element in HTML, specifying the source file and alternative text for accessibility. The `src` attribute points to the image file, and `alt` provides a description.
```html
```
--------------------------------
### JavaScript Entry Point
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript file, likely named index.js, serves as the main entry point for the application. It contains the logic to import React and ReactDOM and render the main App component into the DOM. It orchestrates the initial loading of the React application.
```javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
);
```
--------------------------------
### JavaScript Event Listener Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript code sets up an event listener for a 'click' event on an element with the ID 'myButton'. When clicked, it executes a function that logs a message to the console and changes the button's text.
```javascript
document.getElementById('myButton').addEventListener('click', function() {
console.log('Button clicked!');
this.textContent = 'Clicked!';
});
```
--------------------------------
### Sphinx seealso Directive Example
Source: https://capymoa.org/_sources/contributing/docs
Shows how to implement the Sphinx 'seealso' directive to link to related documentation pages or external resources. This directive is useful for providing supplementary information without cluttering the main text flow. The example includes links to Sphinx documentation and reStructuredText features.
```rst
.. seealso::
`See Also `_
Documents Sphinx seealso directive.
`Definition List `_
Documents reStructuredText definition lists.
```
--------------------------------
### JavaScript: Event Handling
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Demonstrates how to attach an event listener to an HTML element in JavaScript. This example shows how to listen for a 'click' event on a button and execute a function when the event occurs. It requires a button element with a specific ID.
```javascript
function setupClickListener(buttonId, callback) {
const button = document.getElementById(buttonId);
if (button) {
button.addEventListener('click', callback);
} else {
console.error(`Button with ID '${buttonId}' not found.`);
}
}
// Example usage:
// setupClickListener('myButton', () => {
// alert('Button clicked!');
// });
```
--------------------------------
### HTML Structure for React Application
Source: https://capymoa.org/_sources/notebooks/00_getting_started
The basic HTML file that serves as the entry point for the React application. It contains a single div with the ID 'root', where the React component will be mounted by ReactDOM. Other essential meta tags and links are also included.
```html
CapyMoa Project
```
--------------------------------
### JavaScript DOM Manipulation Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This snippet demonstrates basic DOM manipulation using JavaScript. It focuses on selecting an element and modifying its content. It relies on the presence of a DOM in the execution environment. This is commonly used for frontend interactivity.
```javascript
const element = document.getElementById('myElement');
if (element) {
element.textContent = 'New Content';
}
```
--------------------------------
### Initialize Application
Source: https://capymoa.org/_sources/notebooks/SSL_example
This snippet shows the initialization of an application. It calls an `init` function, likely to set up the application's core components or state. No specific inputs or outputs are detailed, but it's a foundational step for many applications.
```javascript
init();
```
--------------------------------
### Initialize and Render a Component (JavaScript)
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Initializes and renders a UI component. This snippet suggests a component-based architecture, possibly using a framework like React or Vue, or a custom implementation. It involves setting up the component's initial state and rendering it to the DOM.
```javascript
class MyComponent {
constructor(elementId, initialProps) {
this.element = document.getElementById(elementId);
this.props = initialProps;
this.state = this.getInitialState();
this.render();
}
getInitialState() {
// Placeholder for initial state logic
return { count: 0 };
}
render() {
// Placeholder for rendering logic
this.element.innerHTML = `Hello, ${this.props.name}! Count: ${this.state.count}
`;
console.log('Component rendered.');
}
}
// Example usage:
// const myComp = new MyComponent('myComponentContainer', { name: 'User' });
```
--------------------------------
### Python: File I/O Operations
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This Python code demonstrates basic file reading and writing operations. It handles opening, reading content, and writing to files. Proper error handling (e.g., try-except blocks) is recommended for robust applications.
```python
with open("myfile.txt", "w") as f:
f.write("Hello, world!\n")
with open("myfile.txt", "r") as f:
content = f.read()
print(content)
```
--------------------------------
### Python: Read CSV File
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Reads data from a CSV file using the pandas library. Assumes the CSV file is located at the specified path. Returns a DataFrame containing the CSV content. Requires the pandas library to be installed.
```python
import pandas as pd
def read_csv_file(filepath):
"""Reads a CSV file into a pandas DataFrame."""
try:
df = pd.read_csv(filepath)
return df
except FileNotFoundError:
print(f"Error: The file {filepath} was not found.")
return None
except Exception as e:
print(f"An error occurred: {e}")
return None
```
--------------------------------
### Check Java Installation
Source: https://capymoa.org/_sources/installation
This command checks if Java is installed on your system by displaying its version information. CapyMOA requires Java to be installed and accessible.
```bash
java -version
```
--------------------------------
### JavaScript: Basic DOM Manipulation
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Provides an example of how to interact with the Document Object Model (DOM) in JavaScript. It shows how to select an element by its ID and change its text content. This function requires a valid element ID and new text as input.
```javascript
function updateElementText(elementId, newText) {
const element = document.getElementById(elementId);
if (element) {
element.textContent = newText;
} else {
console.error(`Element with ID '${elementId}' not found.`);
}
}
```
--------------------------------
### Basic C++ main function
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This C++ code snippet shows the basic structure of a `main` function, which is the entry point for any C++ program. It includes the necessary header for input/output operations.
```cpp
#include
int main() {
// Program logic goes here
return 0;
}
```
--------------------------------
### Configuration and Initialization in Bash
Source: https://capymoa.org/_sources/notebooks/09_automl
This Bash script snippet illustrates configuration and initialization processes. It might be used for setting up environments or running initial tasks. It relies on standard shell commands.
```bash
#!/bin/bash
# Configuration variables
API_KEY="your_api_key_here"
LOG_LEVEL="INFO"
# Initialize service
echo "Initializing service..."
# Placeholder for initialization commands
echo "Service initialized with API Key: $API_KEY and Log Level: $LOG_LEVEL"
```
--------------------------------
### Load Fried Dataset and Initialize Regressors with CapyMOA
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This snippet demonstrates loading the Fried dataset, initializing FIMTDD and KNNRegressor models from CapyMOA, and performing prequential evaluations. It then visualizes the windowed results comparing the two regressors.
```python
from capymoa.datasets import Fried
from moa.classifiers.trees import FIMTDD
from capymoa.base import MOARegressor
from capymoa.regressor import KNNRegressor
fried_stream = (
Fried()
) # Downloads the Fried dataset into the data dir in case it is not there yet.
fimtdd = MOARegressor(schema=fried_stream.get_schema(), moa_learner=FIMTDD())
knnreg = KNNRegressor(schema=fried_stream.get_schema(), k=3, window_size=1000)
results_fimtdd = prequential_evaluation(
stream=fried_stream, learner=fimtdd, window_size=5000
)
results_knnreg = prequential_evaluation(
stream=fried_stream, learner=knnreg, window_size=5000
)
results_fimtdd.windowed.metrics_per_window()
# Note that the metric is different from the ylabel parameter, which just overrides the y-axis label.
plot_windowed_results(
results_fimtdd, results_knnreg, metric="rmse", ylabel="root mean squared error"
)
```
--------------------------------
### CapyMoa Initialization and Setup (JavaScript)
Source: https://capymoa.org/_sources/notebooks/09_automl
This JavaScript code snippet illustrates the initialization and setup process for CapyMoa. It might involve setting up configurations, event listeners, or initial states required before the application can function correctly. Standard JavaScript execution is assumed.
```javascript
class CapyMoaApp {
constructor() {
this.config = {};
this.isInitialized = false;
}
async initialize(config = {}) {
this.config = { ...this.config, ...config };
console.log('Initializing CapyMoa with config:', this.config);
// Perform async setup tasks if needed
await this.loadInitialState();
this.isInitialized = true;
console.log('CapyMoa initialized successfully.');
}
async loadInitialState() {
// Placeholder for loading initial state from storage or API
return new Promise(resolve => setTimeout(resolve, 500));
}
run() {
if (!this.isInitialized) {
console.error('CapyMoa must be initialized before running.');
return;
}
console.log('CapyMoa is running...');
// Start main application logic
}
}
// Example Usage:
// const app = new CapyMoaApp();
// app.initialize({ theme: 'dark' }).then(() => {
// app.run();
// });
```
--------------------------------
### HTML/CSS: Responsive Layout with Flexbox
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This code demonstrates creating a responsive layout using HTML and CSS Flexbox. It ensures elements are arranged efficiently across different screen sizes. It relies on standard HTML structure and CSS properties.
```html
```
```css
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 1;
min-width: 100px;
margin: 10px;
background-color: lightblue;
}
```
--------------------------------
### Evaluate OnlineBagging with DriftStream in Python
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This snippet demonstrates setting up a synthetic data stream using `DriftStream` which incorporates `SEA`, `AbruptDrift`, and `GradualDrift`. It then initializes an `OnlineBagging` classifier and evaluates it using `prequential_evaluation`. Finally, it visualizes the results with `plot_windowed_results`.
```python
from capymoa.classifier import OnlineBagging
from capymoa.stream.generator import SEA
from capymoa.stream.drift import AbruptDrift, GradualDrift, DriftStream
# Generating a synthetic stream with 1 abrupt drift and 1 gradual drift.
stream_sea2drift = DriftStream(
stream=[
SEA(function=1),
AbruptDrift(position=5000),
SEA(function=3),
GradualDrift(start=9000, end=12000),
SEA(function=1),
]
)
OB = OnlineBagging(schema=stream_sea2drift.get_schema(), ensemble_size=10)
# Since this is a synthetic stream, max_instances is needed to determine the amount of instances to be generated.
results_sea2drift_OB = prequential_evaluation(
stream=stream_sea2drift, learner=OB, window_size=100, max_instances=15000
)
# print(stream_sea2drift.drifts)
plot_windowed_results(results_sea2drift_OB, metric="accuracy")
```
--------------------------------
### Basic HTML Structure with HTML
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Provides a minimal HTML document structure including the doctype, html, head, and body tags. This is the foundational boilerplate for any HTML page.
```html
Page Title
My First Heading
My first paragraph.
```
--------------------------------
### CSS `position: relative` and `position: absolute`
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This CSS example demonstrates relative and absolute positioning. The parent element has `position: relative` to establish a positioning context. The child element has `position: absolute` and is positioned 10 pixels from the top and left edges of its nearest positioned ancestor (the parent).
```css
.parent {
position: relative;
width: 200px;
height: 200px;
background-color: lightgray;
}
.child {
position: absolute;
top: 10px;
left: 10px;
width: 50px;
height: 50px;
background-color: red;
}
```
--------------------------------
### Install Pandoc using Conda
Source: https://capymoa.org/_sources/installation
Installs the Pandoc document converter using the Conda package manager from the conda-forge channel. Pandoc is a dependency for CapyMOA development documentation.
```bash
conda install -c conda-forge pandoc
```
--------------------------------
### Python: Data Manipulation and String Formatting
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This Python snippet likely deals with data manipulation, possibly involving string operations or list processing. The example shows basic string formatting and variable assignment, common in data cleaning or preparation tasks. No external libraries are immediately apparent.
```python
def format_string(name):
return f"Hello, {name}!"
my_name = "Capy"
print(format_string(my_name))
```
--------------------------------
### JavaScript Event Listener Setup
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript code illustrates how to attach an event listener to an HTML element. It listens for a 'click' event on an element with the ID 'myButton' and executes a callback function when the event occurs. This is essential for handling user interactions on a webpage. It requires an HTML element with the ID 'myButton'.
```javascript
const button = document.getElementById('myButton');
if (button) {
button.addEventListener('click', function() {
console.log('Button clicked!');
// Additional actions can be performed here
});
}
```
--------------------------------
### Python: Simple Flask Web Server
Source: https://capymoa.org/_sources/notebooks/01_evaluation
This Python snippet sets up a minimal web server using the Flask framework. It defines a single route that returns 'Hello, World!'. This is useful for creating basic web APIs or simple web applications. Ensure Flask is installed (`pip install Flask`).
```python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
```
--------------------------------
### Python: File I/O Operations
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Demonstrates reading from and writing to files in Python. It includes functions to read the entire content of a file and write a list of strings to a file. Error handling for file operations is included.
```python
def read_file(filepath):
try:
with open(filepath, 'r') as f:
content = f.read()
return content
except FileNotFoundError:
print(f"Error: File not found at {filepath}")
return None
def write_file(filepath, lines):
try:
with open(filepath, 'w') as f:
for line in lines:
f.write(line + '\n')
except IOError:
print(f"Error: Could not write to file at {filepath}")
```
--------------------------------
### JavaScript DOM Manipulation Example
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript snippet demonstrates how to manipulate the Document Object Model (DOM) to interact with HTML elements. It shows how to select an element by its ID and change its content. This is a core technique for creating dynamic and interactive web pages. It assumes an HTML element with the ID 'myElement' exists.
```javascript
function updateElementContent(newContent) {
const element = document.getElementById('myElement');
if (element) {
element.textContent = newContent;
}
}
```
--------------------------------
### Handle Data Fetching and Display in JavaScript
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript snippet demonstrates how to fetch data from a given API endpoint and then process it for display. It utilizes asynchronous operations and DOM manipulation. Ensure the API endpoint is accessible and returns data in a parsable format.
```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();
displayData(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
function displayData(data) {
const container = document.getElementById('data-container');
// Assuming data is an array of objects with a 'name' property
data.forEach(item => {
const element = document.createElement('div');
element.textContent = item.name;
container.appendChild(element);
});
}
// Example usage:
// fetchData('/api/data');
```
--------------------------------
### Perform Regression Evaluation with FIMTDD and KNN Regressors
Source: https://capymoa.org/notebooks/00_getting_started
This Python code demonstrates how to perform prequential evaluation for regression tasks using MOA's FIMTDD classifier and CapyMOA's KNNRegressor. It utilizes the Fried dataset and visualizes the windowed results, comparing RMSE metrics. Ensure 'capymoa' and 'moa' libraries are installed.
```python
from capymoa.datasets import Fried
from moa.classifiers.trees import FIMTDD
from capymoa.base import MOARegressor
from capymoa.regressor import KNNRegressor
from capymoa.evaluation import prequential_evaluation
from capymoa.visualize import plot_windowed_results
fried_stream = (
Fried()
) # Downloads the Fried dataset into the data dir in case it is not there yet.
fimtdd = MOARegressor(schema=fried_stream.get_schema(), moa_learner=FIMTDD())
knnreg = KNNRegressor(schema=fried_stream.get_schema(), k=3, window_size=1000)
results_fimtdd = prequential_evaluation(
stream=fried_stream, learner=fimtdd, window_size=5000
)
results_knnreg = prequential_evaluation(
stream=fried_stream, learner=knnreg, window_size=5000
)
results_fimtdd.windowed.metrics_per_window()
# Note that the metric is different from the ylabel parameter, which just overrides the y-axis label.
plot_windowed_results(
results_fimtdd, results_knnreg, metric="rmse", ylabel="root mean squared error"
)
```
--------------------------------
### Database Query Execution (SQL)
Source: https://capymoa.org/_sources/notebooks/SSL_example
This snippet provides examples of executing SQL queries. It demonstrates how to connect to a database, construct queries, and fetch results. This is essential for any application that needs to interact with relational databases. Dependencies include a database driver (e.g., psycopg2 for PostgreSQL, mysql.connector for MySQL).
```sql
SELECT column1, column2
FROM your_table
WHERE condition = 'value';
INSERT INTO your_table (column1, column2)
VALUES ('value1', 'value2');
UPDATE your_table
SET column1 = 'new_value'
WHERE condition = 'value';
```
--------------------------------
### Example Classifier Docstring (Python)
Source: https://capymoa.org/_sources/contributing/docs
An example of a Python class docstring formatted for Sphinx using reStructuredText. It demonstrates a one-line summary, detailed multi-line description, citations, usage examples (doctests), and a 'see also' section.
```python
from capymoa.base import Classifier
from capymoa.stream import Schema
class ExampleClassifier(Classifier):
"""One line docstring.
You may add a multi-line detailed description of the classifier. You
should include a citation [#example25]_ to the source paper.
You may include an example of how to use the classifier. This example is
serves as both documentation and a test for the classifier. Keep in mind
that these are run as part of the test suite, so they should be kept
simple, deterministic, and fast.
>>> from capymoa.datasets import ElectricityTiny
>>> from capymoa.classifier import ExampleClassifier
>>> from capymoa.evaluation import prequential_evaluation
>>> stream = ElectricityTiny()
>>> learner = ExampleClassifier(stream.get_schema())
>>> results = prequential_evaluation(stream, learner, max_instances=1000)
>>> results["cumulative"].accuracy()
87.9
You may include a see also section with links to related classes or
functions. This is useful for users to find related functionality in the
library.
.. seealso::
:func:`capymoa.evaluation.prequential_evaluation`
.. [#example25] Example, A., Author, B., & Researcher, C. (2025). Example Classifier.
"""
class_attr = None
"""One-line docstring for ``class_attr``."""
def __init__(self, schema: Schema):
"""Construct a new ExampleClassifier.
:param schema: Describes the structure of the data stream.
"""
super().__init__(schema)
#: One-line docstring for ``attr_a``.
self.attr_a = None
self.attr_b = None
"""Another syntax for a one-line docstring."""
self.attr_c = None
"""Multi-line docstring for ``attr_c`` attribute.
It can include multiple lines and is useful for providing detailed
information about the attribute's purpose and usage.
"""
```
--------------------------------
### Perform Prequential Evaluation with MOA Classifiers
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Illustrates how to conduct a prequential evaluation using CapyMoa's `prequential_evaluation` function. This example uses the Hoeffding Adaptive Tree (HAT) wrapper and a specified window size. Prequential evaluation is a common method for evaluating online learning algorithms, providing performance metrics as the model processes data incrementally.
```python
# Assuming 'elec_stream' and 'HAT' are defined as in the previous snippet.
# from capymoa.evaluation.evaluation import prequential_evaluation # Ensure this import is present
results_HAT = prequential_evaluation(stream=elec_stream, learner=HAT, window_size=4500)
```
--------------------------------
### Configuration Management: Setting up Parameters
Source: https://capymoa.org/_sources/notebooks/01_evaluation
This code snippet deals with configuration management, likely involving setting up various parameters or options for an application or module. It may include default values and ways to override them.
```javascript
const config = {
setting1: true,
setting2: 100
};
```
--------------------------------
### HTTP GET Request (Python)
Source: https://capymoa.org/_sources/notebooks/01_evaluation
This Python snippet demonstrates how to make an HTTP GET request using the `requests` library. It fetches data from a URL and returns the JSON response. Requires the `requests` library to be installed.
```python
import requests
def http_get_json(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 making request: {e}")
return None
```
--------------------------------
### Web Server Configuration and Request Handling
Source: https://capymoa.org/_sources/notebooks/SSL_example
This snippet details the configuration and request handling for a web server. It demonstrates how to set up routes, handle incoming HTTP requests, and send responses. This is crucial for building web applications and APIs. Dependencies typically include a web framework like Flask or Django.
```python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
# Logic to fetch and return data
return jsonify({'message': 'Data retrieved successfully'})
@app.route('/api/data', methods=['POST'])
def post_data():
data = request.get_json()
# Logic to process incoming data
return jsonify({'message': 'Data received', 'data': data}), 201
if __name__ == '__main__':
app.run(debug=True)
```
--------------------------------
### Python: String Formatting
Source: https://capymoa.org/_sources/notebooks/00_getting_started
Illustrates different ways to format strings in Python, including f-strings and the .format() method. This is useful for creating dynamic strings with variable content. No external libraries are required.
```python
def format_strings(name, age):
# Using f-string
fstring_output = f"Hello, my name is {name} and I am {age} years old."
# Using .format() method
format_output = "Hello, my name is {} and I am {} years old.".format(name, age)
print(fstring_output)
print(format_output)
return fstring_output
```
--------------------------------
### JavaScript `Object.values()` for Object Values
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This JavaScript code uses `Object.values()` to get an array of an object's own enumerable property values. It then iterates over this array using `forEach` and logs each value to the console. This is helpful when you only need the values from an object.
```javascript
const book = {
title: 'The Hitchhiker\'s Guide to the Galaxy',
author: 'Douglas Adams',
published: 1979
};
Object.values(book).forEach(value => {
console.log(value);
});
```
--------------------------------
### Prequential Evaluation with HoeffdingTree in Python
Source: https://capymoa.org/_sources/notebooks/00_getting_started
This snippet demonstrates how to perform prequential evaluation using the HoeffdingTree classifier from the CapyMOA library. It shows how to obtain and print cumulative accuracy and wall-clock time, as well as display windowed metrics using pandas DataFrames. Dependencies include capymoa.evaluation, capymoa.classifier, and pandas.
```python
from capymoa.evaluation import prequential_evaluation
from capymoa.classifier import HoeffdingTree
ht = HoeffdingTree(schema=elec_stream.get_schema(), grace_period=50)
# Obtain the results from the high-level function.
# Note that we need to specify a window_size as we obtain both windowed and cumulative results.
# The results from a high-level evaluation function are represented as a PrequentialResults object
results_ht = prequential_evaluation(stream=elec_stream, learner=ht, window_size=4500)
print(
f"Cumulative accuracy = {results_ht.cumulative.accuracy()}, wall-clock time: {results_ht.wallclock()}"
)
# The windowed results are conveniently stored in a pandas DataFrame.
display(results_ht.windowed.metrics_per_window())
```