Initial commit

This commit is contained in:
2026-01-26 16:43:01 -05:00
commit 23cb27503e
39 changed files with 96557 additions and 0 deletions

78
code/README.md Normal file
View File

@@ -0,0 +1,78 @@
# Code Section
Development workspace for bookmarklets, experiments, and scratch code.
## 🔖 Bookmarklets
Browser-based JavaScript utilities. **See [bookmarklets/README.md](bookmarklets/README.md) for full documentation.**
### Quick Start
1. Write regular JavaScript in `bookmarklets/` (use comments, modern syntax)
2. Run: `npm run bookmarklet -- code/bookmarklets/your-file.js`
3. Paste clipboard contents into browser bookmark URL
### Example
```javascript
/**
* My Bookmarklet
* Does something cool
*/
const elements = document.querySelectorAll("a");
elements.forEach((el) => {
el.style.backgroundColor = "yellow";
});
alert(`Highlighted ${elements.length} links!`);
```
The generator automatically removes comments, minifies, and wraps in IIFE format.
## 🛠️ Utils
Build tools and generators:
- **bookmarkletMaker.js** - Converts JS files to bookmarklets
- Removes comments
- Minifies code
- Wraps in `javascript:(function(){...})();` format
- Copies to clipboard
## 🧪 Scratchpad
Experiment with code organized by language. Use this for:
- Testing new ideas
- Prototyping features
- Learning new concepts
- Code snippets for other projects
### Running Code
- **Python:** `Cmd+Shift+P` → "Code Runner: Run Code"
- **JavaScript:** Same as above (uses Node.js)
- **TypeScript:** Install `ts-node` globally first
## 📄 Templates
Reusable code templates and boilerplate:
- **function-template.js** - Function with ES module exports
- **class-template.js** - Class definition with methods
- **module-template.js** - Multi-export module pattern
- Common patterns and structures
**Note:** All templates use ES modules (import/export). See `package.json` with `"type": "module"`.
## 💡 Tips
- Use `// TODO:` comments for tracking work
- Bookmark important code sections
- Test in scratchpad before moving to bookmarklets
- Keep snippets small and focused
---
**Remember:** This is your experimental playground. Break things, learn, iterate!

142
code/bookmarklets/README.md Normal file
View File

@@ -0,0 +1,142 @@
# Bookmarklets
Browser-based JavaScript utilities that run with a single click from your bookmarks bar.
## 🚀 Creating a Bookmarklet
### 1. Write Your JavaScript
Create a new `.js` file in this directory with regular, readable JavaScript:
```javascript
/**
* My Awesome Bookmarklet
* Does something cool on any webpage
*/
// Your code here
const elements = document.querySelectorAll(".some-class");
elements.forEach((el) => {
// Do something
});
alert("Done!");
```
### 2. Generate the Bookmarklet
Run the generator:
```bash
npm run bookmarklet -- code/bookmarklets/your-file.js
```
The generator will:
- ✂️ Remove all comments
- 🗜️ Minify the code
- 📦 Wrap in bookmarklet format
- 📋 Copy to your clipboard
### 3. Install in Browser
1. Create a new bookmark (Cmd+D or Ctrl+D)
2. Paste the clipboard content as the URL
3. Name it and save
4. Click to use!
## 📚 Available Bookmarklets
### [highlight-links.js](highlight-links.js)
Highlights all links on a page in yellow and shows count.
**Generate:** `npm run bookmarklet -- code/bookmarklets/highlight-links.js`
### [example-bookmarklet.js](example-bookmarklet.js)
Example template showing basic structure.
## 💡 Tips
- **Test first**: Try your logic in the browser console before creating bookmarklet
- **Be browser-safe**: Stick to vanilla JS, avoid ES6+ features in production if supporting old browsers
- **Keep it simple**: Bookmarklets should be quick utilities, not full apps
- **Comment generously**: Comments are stripped out, so explain your code
- **Use descriptive names**: Variables and functions will be minified
## 🔧 Bookmarklet Generator
The generator ([code/utils/bookmarkletMaker.js](../utils/bookmarkletMaker.js)) handles:
- Comment removal (single-line `//` and multi-line `/* */`)
- Code minification (whitespace removal, single-line conversion)
- IIFE wrapping with `javascript:` protocol
- Clipboard copying
## 📝 Common Patterns
### Getting Page Info
```javascript
// Current URL
const url = window.location.href;
// Page title
const title = document.title;
// Selected text
const selected = window.getSelection().toString();
```
### Modifying the Page
```javascript
// Find elements
const elements = document.querySelectorAll(".selector");
// Style them
elements.forEach((el) => {
el.style.backgroundColor = "yellow";
});
// Add content
const div = document.createElement("div");
div.textContent = "Hello!";
document.body.appendChild(div);
```
### Opening New Windows
```javascript
// Open in new tab
window.open("https://example.com", "_blank");
// With specific size
window.open("https://example.com", "_blank", "width=800,height=600");
```
### Copying to Clipboard
```javascript
navigator.clipboard
.writeText("text to copy")
.then(() => alert("Copied!"))
.catch((err) => alert("Failed: " + err));
```
## 🐛 Debugging
If your bookmarklet doesn't work:
1. Open browser console (F12)
2. Paste your original code (without `javascript:` wrapper)
3. Debug errors
4. Update the source file
5. Regenerate bookmarklet
## 🔗 Resources
- [Bookmarklet Best Practices](https://en.wikipedia.org/wiki/Bookmarklet)
- [MDN: DOM API](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model)
- [Browser Compatibility](https://caniuse.com/)

View File

@@ -0,0 +1,30 @@
/**
* Example Bookmarklet Template
*
* This is a template for creating browser bookmarklets.
* To use: Wrap in javascript: protocol and minify
*/
(function () {
"use strict";
// Example: Highlight all links on a page
const links = document.querySelectorAll("a");
links.forEach((link) => {
link.style.backgroundColor = "yellow";
link.style.padding = "2px";
});
// Show confirmation
alert(`Highlighted ${links.length} links!`);
})();
/**
* To convert to bookmarklet:
* 1. Minify the code
* 2. Wrap in: javascript:(function(){YOUR_MINIFIED_CODE})();
* 3. Add to browser bookmarks
*
* Example bookmarklet format:
* javascript:(function(){'use strict';const links=document.querySelectorAll('a');links.forEach(link=>{link.style.backgroundColor='yellow';});alert(`Highlighted ${links.length} links!`);})();
*/

View File

@@ -0,0 +1,23 @@
/**
* Highlight Links Bookmarklet
*
* Highlights all links on the current page with a yellow background
* and displays a count of total links found.
*
* Usage: Click the bookmarklet on any webpage
*/
// Find all anchor tags
const links = document.querySelectorAll("a");
// Style each link
links.forEach((link) => {
link.style.backgroundColor = "yellow";
link.style.padding = "2px 4px";
link.style.borderRadius = "3px";
});
// Show result
alert(
`Highlighted ${links.length} link${links.length !== 1 ? "s" : ""} on this page!`,
);

View File

@@ -0,0 +1,110 @@
/*
* This script extracts event data from a table on a webpage and generates an iCalendar (.ics) file for download.
* It looks for a table with specific headers ('event', 'date', 'venue', 'address'), parses the event details,
* and then creates an iCalendar file with the extracted event information. The file is then automatically
* downloaded to the user's device.
*/
javascript: (() => {
function extractEventData() {
let tables = document.querySelectorAll('table');
if (tables.length > 1) {
tables = [tables[0]];
}
const data = [];
tables.forEach(table => {
const headers = [];
const rows = table.querySelectorAll('tr');
const firstRow = rows[0];
firstRow.querySelectorAll('td').forEach(td => {
headers.push(td.textContent.trim().toLowerCase());
});
if (
headers.includes('event') &&
headers.includes('date') &&
headers.includes('venue') &&
headers.includes('address')
) {
Array.from(rows)
.slice(1)
.forEach(row => {
const cells = row.querySelectorAll('td');
const rowData = {};
cells.forEach((cell, j) => {
const header = headers[j];
let cellText = cell.innerHTML
.replace(/<br\s*\/?>/gi, ', ')
.trim();
cellText = cellText.replace(/<\/?[^>]+(>|$)/g, '').trim();
if (header === 'event') {
rowData.event = cellText;
} else if (header === 'date') {
const month = cellText.split(' ')[0];
const year = cellText.split(',')[1].trim();
const startDay = cellText
.split(' ')[1]
.split(cellText.includes(' ') ? ' ' : '')[0]
.trim();
const endDay = cellText
.split(cellText.includes(' ') ? ' ' : '')[1]
.split(',')[0]
.trim();
rowData.startDate = `${month} ${startDay}, ${year}`;
rowData.endDate = `${month} ${endDay}, ${year}`;
} else if (header === 'venue') {
rowData.venue = cellText;
} else if (header === 'location') {
rowData.address = cellText;
}
});
data.push(rowData);
});
}
});
console.log(data);
return data;
}
const data = extractEventData();
function createICal(events) {
let icalContent =
'BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//FragginWagon//International-Championships\n';
events.forEach(event => {
icalContent += 'BEGIN:VEVENT\n';
icalContent += `DTSTART:${new Date(event.startDate).toISOString().replace(/[-:]/g, '').split('.')[0]}Z\n`;
icalContent += `DTEND:${new Date(event.endDate).toISOString().replace(/[-:]/g, '').split('.')[0]}Z\n`;
icalContent += `SUMMARY:${event.event} \n`;
icalContent += `LOCATION:${event.location}\n`;
icalContent += 'END:VEVENT\n';
});
icalContent += 'END:VCALENDAR';
return icalContent;
}
function downloadICal(content, filename) {
const blob = new Blob([content], { type: 'text/calendar' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
const newIcalContent = createICal(data);
downloadICal(
newIcalContent,
'play_pokemon_international_championships_events.ics'
);
})();

View File

@@ -0,0 +1,117 @@
/**
*
* This bookmarklet extracts event data from the first four tables on a webpage,
* specifically looking for tables that contain 'date', 'venue', and 'location' headers.
* It processes the event data to identify special events and formats the dates.
* The extracted data is then used to create an iCalendar (.ics) file, which is
* automatically downloaded to the user's device.
*
* Functions:
* - extractEventData: Extracts event data from the first four tables on the webpage.
* - createICal: Creates an iCalendar (.ics) content string from the extracted event data.
* - downloadICal: Initiates the download of the iCalendar (.ics) file with the given content and filename.
*/
javascript: (() => {
function extractEventData() {
let tables = document.querySelectorAll('table');
if (tables.length > 4) {
tables = Array.from(tables).slice(0, 4);
}
const data = [];
tables.forEach(table => {
const headers = [];
const rows = table.querySelectorAll('tr');
const firstRow = rows[0];
firstRow.querySelectorAll('td').forEach(td => {
headers.push(td.textContent.trim().toLowerCase());
});
if (
headers.includes('date') &&
headers.includes('venue') &&
headers.includes('location')
) {
Array.from(rows)
.slice(1)
.forEach(row => {
const cells = row.querySelectorAll('td');
const rowData = {};
if (
Array.from(cells).some(cell =>
cell.querySelector('span[style*="color: #2dc26b"]')
)
) {
rowData.specialEvent = true;
}
cells.forEach((cell, j) => {
const header = headers[j];
let cellText = cell.innerHTML.replace(/<br\s*\/?>/gi, ', ').trim();
cellText = cellText.replace(/<\/?[^>]+(>|$)/g, '').trim();
if (header === 'date') {
const month = cellText.split(' ')[0];
const year = cellText.split(',')[1].trim();
const startDay = cellText
.split(' ')[1]
.split(cellText.includes(' ') ? ' ' : '')[0]
.trim();
const endDay = cellText
.split(cellText.includes(' ') ? ' ' : '')[1]
.split(',')[0]
.trim();
rowData.startDate = `${month} ${startDay}, ${year}`;
rowData.endDate = `${month} ${endDay}, ${year}`;
} else if (header === 'venue') {
rowData.venue = cellText;
} else if (header === 'location') {
rowData.location = cellText;
}
});
data.push(rowData);
});
}
});
return data;
}
const data = extractEventData(tables);
function createICal(events) {
let icalContent =
'BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//FragginWagon//P!P //Regional-Special-Championships\n';
events.forEach(event => {
icalContent += 'BEGIN:VEVENT\n';
icalContent += `DTSTART:${new Date(event.startDate).toISOString().replace(/[-:]/g, '').split('.')[0]}Z\n`;
icalContent += `DTEND:${new Date(event.endDate).toISOString().replace(/[-:]/g, '').split('.')[0]}Z\n`;
icalContent += `SUMMARY:${event.specialEvent ? 'Special Event' : 'Regional'} - ${event.venue} \n`;
icalContent += `LOCATION:${event.location}\n`;
icalContent += 'END:VEVENT\n';
});
icalContent += 'END:VCALENDAR';
return icalContent;
}
function downloadICal(content, filename) {
const blob = new Blob([content], { type: 'text/calendar' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
const newIcalContent = createICal(extractEventData());
downloadICal(newIcalContent, 'play_pokemon_regional_special_events.ics');
})();

125
code/junk-drawer/scrape.js Normal file
View File

@@ -0,0 +1,125 @@
/**
* This script scrapes a website for table data using Puppeteer and Cheerio.
* It specifically looks for tables with headers "Date", "Venue", and "Location",
* and extracts the data from these tables.
*
* The script performs the following steps:
* 1. Launches a Puppeteer browser instance.
* 2. Sets the user agent and viewport to mimic a real browser.
* 3. Navigates to the specified URL.
* 4. Simulates human-like interactions (mouse movements and delays).
* 5. Extracts the HTML content of the page.
* 6. Loads the HTML content into Cheerio for parsing.
* 7. Finds all table elements and checks if they contain the headers "Date", "Venue", and "Location".
* 8. Extracts the data from the matching tables and returns it.
*
* @param {string} url - The URL of the website to scrape.
* @returns {Promise<Array<Object>>} - A promise that resolves to an array of objects containing the scraped data.
*
* Example usage:
* const url = 'https://www.pokemon.com/us/play-pokemon/pokemon-events/championship-series/2025/regional-special-championships';
* scrapeWebsite(url)
* .then(data => console.log(data))
* .catch(error => console.error(error));
*
* Required npm packages:
* - puppeteer: ^10.0.0
* - cheerio: ^1.0.0-rc.10
*
* Currently not working due to recaptch on P!P site
*/
const puppeteer = require("puppeteer");
const cheerio = require("cheerio");
async function scrapeWebsite(url) {
// Launch Puppeteer
const browser = await puppeteer.launch({
headless: false, // Run in headless mode
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-accelerated-2d-canvas",
"--disable-gpu",
"--window-size=1920x1080",
],
});
const page = await browser.newPage();
// Set user agent to mimic a real browser
await page.setUserAgent(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
);
// Set viewport to mimic a real browser
await page.setViewport({ width: 1920, height: 1080 });
// Navigate to the URL
await page.goto(url, { waitUntil: "networkidle2" });
// Simulate human-like interactions
await page.waitForTimeout(2000); // Wait for 2 seconds
await page.mouse.move(100, 100); // Move mouse to a specific position
await page.mouse.move(200, 200, { steps: 10 }); // Move mouse with steps
await page.waitForTimeout(1000); // Wait for 1 second
// Get the HTML content
const content = await page.content();
await browser.close();
// Load the HTML content into Cheerio
const $ = cheerio.load(content);
// Find all table elements
const tables = $("table");
const data = [];
// Loop through each table
tables.each((index, table) => {
const headers = [];
const rows = $(table).find("tr");
// Check if the first row contains the headers Date, Venue, and Location
const firstRow = rows.first();
firstRow.find("tr").each((i, th) => {
headers.push($(th).text().trim().toLowerCase());
});
if (
headers.includes("date") &&
headers.includes("venue") &&
headers.includes("location")
) {
// Loop through the remaining rows and extract data
rows.slice(1).each((i, row) => {
const cells = $(row).find("td");
const rowData = {};
cells.each((j, cell) => {
const header = headers[j];
const cellText = $(cell).text().trim();
if (header === "date") {
const dates = cellText.split(" - ");
rowData.startDate = dates[0];
rowData.endDate = dates[1] || dates[0];
} else if (header === "venue") {
rowData.venue = cellText;
} else if (header === "location") {
rowData.location = cellText;
}
});
data.push(rowData);
});
}
});
return data;
}
// Example usage
const url =
"https://www.pokemon.com/us/play-pokemon/pokemon-events/championship-series/2025/regional-special-championships";
scrapeWebsite(url)
.then((data) => console.log(data))
.catch((error) => console.error(error));

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
/**
* Example JavaScript scratchpad file
*
* Use this area to test JavaScript/Node.js code
* This project uses ES modules (import/export)
*/
// Example imports (uncomment to use)
// import fs from 'fs';
// import path from 'path';
// import { someFunction } from './other-file.js';
function helloWorld() {
console.log("Hello from Memory Palace!");
return "Success";
}
// TODO: Add your experimental code here
// Run the example
const result = helloWorld();
console.log(`Result: ${result}`);
// Export for use in other modules
export { helloWorld };
export default helloWorld;

View File

@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""
Example Python scratchpad file
Use this area to test Python code, experiment with libraries,
or prototype features for other projects.
"""
def hello_world():
"""Example function"""
print("Hello from Memory Palace!")
return "Success"
# TODO: Add your experimental code here
if __name__ == "__main__":
result = hello_world()
print(f"Result: {result}")

View File

@@ -0,0 +1,43 @@
/**
* Class Template
*
* @class ClassName
* @description Description of what this class does
*/
export class ClassName {
/**
* Create a new instance
* @param {type} param - Description
*/
constructor(param) {
this.param = param;
// TODO: Initialize properties
}
/**
* Method description
* @param {type} arg - Description
* @returns {type} Description
*/
methodName(arg) {
// TODO: Implement method logic
return result;
}
/**
* Static method example
* @param {type} arg - Description
* @returns {type} Description
*/
static staticMethod(arg) {
// TODO: Implement static method
return result;
}
}
// Alternative export:
// export default ClassName;
// Usage example:
// import { ClassName } from './class-template.js';
// const instance = new ClassName(param);

View File

@@ -0,0 +1,16 @@
/**
* Function Template
*
* @param {type} paramName - Description
* @returns {type} Description
*/
export function functionName(paramName) {
// TODO: Implement function logic
return result;
}
// Alternative export styles:
// export default functionName; // Default export
// export { functionName }; // Named export
// export { functionName as myFunction }; // Renamed export

View File

@@ -0,0 +1,51 @@
/**
* Module Template
*
* Example of a utility module with multiple exports
*/
/**
* Function one
* @param {type} param - Description
* @returns {type} Description
*/
export function functionOne(param) {
// Implementation
return result;
}
/**
* Function two
* @param {type} param - Description
* @returns {type} Description
*/
export function functionTwo(param) {
// Implementation
return result;
}
/**
* Constant export
*/
export const CONSTANT_VALUE = "value";
/**
* Object export
*/
export const config = {
option1: true,
option2: "value",
};
// Default export (optional)
export default {
functionOne,
functionTwo,
CONSTANT_VALUE,
config,
};
// Usage examples:
// import { functionOne, functionTwo } from './module-template.js';
// import utils from './module-template.js'; // Default import
// import * as utils from './module-template.js'; // Namespace import

View File

@@ -0,0 +1,106 @@
/**
* Bookmarklet Generator
*
* Converts a regular JavaScript file into a bookmarklet format.
* - Removes all comments (single-line and multi-line)
* - Wraps code in IIFE for bookmarklet format
* - Minifies to a single line
* - Copies to clipboard
*
* Usage:
* node code/utils/bookmarkletMaker.js <path-to-js-file>
* npm run bookmarklet -- <path-to-js-file>
*
* Example:
* npm run bookmarklet -- code/bookmarklets/example-bookmarklet.js
*/
import fs from "fs";
import path from "path";
import clipboardy from "clipboardy";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Remove all comments from JavaScript code
* @param {string} code - The JavaScript code
* @returns {string} Code without comments
*/
function removeComments(code) {
// Remove multi-line comments /* ... */
code = code.replace(/\/\*[\s\S]*?\*\//g, "");
// Remove single-line comments //
code = code.replace(/\/\/.*$/gm, "");
return code;
}
/**
* Minify code to a single line
* @param {string} code - The JavaScript code
* @returns {string} Minified code
*/
function minify(code) {
return code
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.join(" ")
.replace(/\s+/g, " ")
.replace(/\s*([{}();,])\s*/g, "$1");
}
/**
* Generate bookmarklet from JavaScript file
* @param {string} filePath - Path to the JavaScript file
* @returns {string} The bookmarklet code
*/
function generateBookmarklet(filePath) {
// Validate file exists
if (!fs.existsSync(filePath)) {
throw new Error(`File not found: ${filePath}`);
}
// Read the JavaScript file
const jsCode = fs.readFileSync(filePath, "utf8");
// Clean and minify
let cleanedCode = removeComments(jsCode);
cleanedCode = minify(cleanedCode);
// Wrap in IIFE and add javascript: protocol
const bookmarklet = `javascript:(function(){${cleanedCode}})();`;
return bookmarklet;
}
// Main execution
try {
const filePath = process.argv[2];
if (!filePath) {
console.error("❌ Error: Please provide a file path");
console.log("\nUsage:");
console.log(" npm run bookmarklet -- <path-to-js-file>");
console.log("\nExample:");
console.log(" npm run bookmarklet -- code/bookmarklets/my-bookmarklet.js");
process.exit(1);
}
const bookmarklet = generateBookmarklet(filePath);
const fileName = path.basename(filePath);
// Copy to clipboard
clipboardy.writeSync(bookmarklet);
console.log("✅ Bookmarklet generated successfully!");
console.log(`📁 Source: ${fileName}`);
console.log(`📋 Copied to clipboard (${bookmarklet.length} characters)`);
console.log("\n📝 Next steps:");
console.log(" 1. Create a new bookmark in your browser");
console.log(" 2. Paste the clipboard content as the URL");
console.log(" 3. Give it a name and save");
} catch (error) {
console.error("❌ Error:", error.message);
process.exit(1);
}