### Serve API with esbuild Source: https://github.com/mindrally/skills/blob/main/esbuild-bundler/SKILL.md Starts a local development server to serve API files. It bundles the entry point and serves the output directory. Requires esbuild to be installed. ```javascript const ctx = await esbuild.context({ entryPoints: ['src/index.ts'], bundle: true, outdir: 'dist' }); await ctx.serve({ servedir: 'dist', port: 3000 }); ``` -------------------------------- ### SvelteKit File-Based Routing Examples Source: https://github.com/mindrally/skills/blob/main/sveltekit/SKILL.md Illustrates SvelteKit's file-based routing system, showing how directory and file names map to URL paths, including root pages, nested routes, and dynamic route parameters. ```text routes/ ├── +page.svelte # / ├── about/+page.svelte # /about ├── blog/ │ ├── +page.svelte # /blog │ └── [slug]/ │ └── +page.svelte # /blog/:slug ``` -------------------------------- ### RESTful Controller Example in C# Source: https://github.com/mindrally/skills/blob/main/aspnet-core/SKILL.md Demonstrates a RESTful controller for managing products in ASP.NET Core. It includes endpoints for getting all products, getting a product by ID, and creating a new product. This follows standard API design principles. ```csharp using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Threading.Tasks; [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly IProductService _productService; public ProductsController(IProductService productService) { _productService = productService; } [HttpGet] public async Task>> GetProducts() { var products = await _productService.GetAllAsync(); return Ok(products); } [HttpGet("{id}")] public async Task> GetProduct(int id) { var product = await _productService.GetByIdAsync(id); if (product == null) return NotFound(); return Ok(product); } [HttpPost] public async Task> CreateProduct(CreateProductDto dto) { var product = await _productService.CreateAsync(dto); return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); } } ``` -------------------------------- ### Install AutoGen and Dependencies Source: https://github.com/mindrally/skills/blob/main/autogen-development/SKILL.md Installs the necessary AutoGen packages for agent chat and extensions. This is the initial step for setting up an AutoGen development environment. ```python # Install AutoGen # pip install autogen-agentchat autogen-ext from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.teams import RoundRobinGroupChat from autogen_ext.models.openai import OpenAIChatCompletionClient ``` -------------------------------- ### Svelte Component Script Setup with TypeScript Source: https://github.com/mindrally/skills/blob/main/sveltekit/SKILL.md Demonstrates how to set up a Svelte component's script section using TypeScript, including importing lifecycle functions, defining types for page data, and managing local state with reactive declarations. ```svelte ``` -------------------------------- ### RESTful API Controller Example (C#) Source: https://github.com/mindrally/skills/blob/main/dotnet/SKILL.md Demonstrates a basic RESTful API controller using ASP.NET Core, including routing, HTTP methods (GET, POST), and handling query parameters for pagination. It defines endpoints for managing users. ```csharp [ApiController] [Route("api/v1/[controller]")] public class UsersController : ControllerBase { [HttpGet] public async Task>> GetUsers([FromQuery] PaginationParams pagination) [HttpGet("{id}")] public async Task> GetUser(int id) [HttpPost] public async Task> CreateUser(CreateUserDto dto) } ``` -------------------------------- ### Fine-tuning with Hugging Face Trainer API Source: https://github.com/mindrally/skills/blob/main/transformers-huggingface/SKILL.md Illustrates the setup of the Hugging Face Trainer API for fine-tuning models. It includes defining training arguments, initializing the Trainer with model, datasets, tokenizer, and a metrics computation function. ```python from transformers import Trainer, TrainingArguments training_args = TrainingArguments( output_dir="./results", evaluation_strategy="epoch", learning_rate=2e-5, per_device_train_batch_size=16, num_train_epochs=3, weight_decay=0.01, save_strategy="epoch", load_best_model_at_end=True, ) trainer = Trainer( model=model, # Assuming 'model' is a pre-trained Hugging Face model args=training_args, train_dataset=train_dataset, # Assuming 'train_dataset' is a Hugging Face Dataset eval_dataset=eval_dataset, # Assuming 'eval_dataset' is a Hugging Face Dataset tokenizer=tokenizer, # Assuming 'tokenizer' is a Hugging Face tokenizer compute_metrics=compute_metrics, # Assuming 'compute_metrics' is a function to calculate metrics ) ``` -------------------------------- ### Setup Anthropic Client with API Key (Python) Source: https://github.com/mindrally/skills/blob/main/anthropic-claude-development/SKILL.md Demonstrates how to initialize the Anthropic client using an API key stored in environment variables. It emphasizes best practices for API key management, such as using `.env` files and avoiding hardcoding. ```python import os from anthropic import Anthropic # Always use environment variables for API keys client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY")) ``` -------------------------------- ### Install Lottie Packages Source: https://github.com/mindrally/skills/blob/main/lottie/SKILL.md Installs the necessary Lottie animation packages for React and vanilla JavaScript projects using npm. ```bash # For React npm install @lottiefiles/dotlottie-react # For vanilla JS npm install @lottiefiles/dotlottie-web ``` -------------------------------- ### React Three Fiber Scene Component Example Source: https://github.com/mindrally/skills/blob/main/react-native-r3f/SKILL.md A functional React component demonstrating the setup of a 3D scene using React Three Fiber. It includes basic lighting, a mesh, orbit controls, and environment settings, wrapped in Suspense for fallback handling. This example utilizes `@react-three/fiber`, `@react-three/drei`, and `react`. ```tsx import { Canvas } from '@react-three/fiber' import { OrbitControls, Environment } from '@react-three/drei' import { Suspense } from 'react' interface SceneProps { isAnimating: boolean } function Scene({ isAnimating }: SceneProps) { return ( ) } export { Scene } ``` -------------------------------- ### Basic ScrollTrigger Setup (JavaScript) Source: https://github.com/mindrally/skills/blob/main/gsap/SKILL.md Provides a fundamental example of setting up ScrollTrigger to animate an element based on its scroll position. It includes defining the trigger element, start and end points of the animation relative to the viewport, and using `scrub` for smooth, scroll-linked animation. ```javascript gsap.to(".element", { x: 500, scrollTrigger: { trigger: ".element", start: "top center", end: "bottom center", scrub: true, markers: false // Enable for debugging only } }); ``` -------------------------------- ### Project Structure Example Source: https://github.com/mindrally/skills/blob/main/go-backend-microservices/SKILL.md Illustrates a modular project structure for Go backend microservices, organizing code into distinct directories for entry points, private code, public libraries, API definitions, configurations, and tests. ```text project/ ├── cmd/ # Application entry points ├── internal/ # Private application code ├── pkg/ # Public library code ├── api/ # API definitions (OpenAPI, protobuf) ├── configs/ # Configuration files └── test/ # Additional test utilities ``` -------------------------------- ### SQL Pagination Example Source: https://github.com/mindrally/skills/blob/main/sql-best-practices/SKILL.md Shows how to implement pagination in SQL using LIMIT and OFFSET clauses to retrieve data in chunks. ```sql -- Pagination example SELECT product_id, product_name, price FROM products ORDER BY product_id LIMIT 20 OFFSET 40; ``` -------------------------------- ### Install Puppeteer Source: https://github.com/mindrally/skills/blob/main/puppeteer-automation/SKILL.md Installs Puppeteer, a Node.js library for controlling headless Chrome or Chromium. This is the first step to setting up your automation project. ```bash npm init -y npm install puppeteer ``` -------------------------------- ### Structured Logging Example Source: https://github.com/mindrally/skills/blob/main/go-backend-microservices/SKILL.md Illustrates structured logging in Go, emphasizing consistent field names and including trace IDs for better log analysis and debugging. This approach aids in correlating logs across distributed systems. ```go import ( "context" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func logWithTraceID(ctx context.Context, message string) { traceID, ok := ctx.Value("traceID").(string) if !ok { traceID = "-" } log.Ctx(ctx).Info().Str("trace_id", traceID).Msg(message) } ``` -------------------------------- ### SvelteKit API Route Handler (GET and POST) Source: https://github.com/mindrally/skills/blob/main/sveltekit/SKILL.md Implements an API route handler in SvelteKit (`+server.ts`) supporting both GET and POST requests. The GET handler retrieves posts with an optional limit, and the POST handler creates a new post from JSON data. ```typescript // routes/api/posts/+server.ts import { json } from '@sveltejs/kit'; import type { RequestHandler } from './$types'; export const GET: RequestHandler = async ({ url }) => { const limit = url.searchParams.get('limit') ?? '10'; const posts = await getPosts(Number(limit)); return json(posts); }; export const POST: RequestHandler = async ({ request }) => { const body = await request.json(); const post = await createPost(body); return json(post, { status: 201 }); }; ``` -------------------------------- ### Tauri Rust Command Definition and Setup Source: https://github.com/mindrally/skills/blob/main/tauri-development/SKILL.md Shows how to define a command in Rust that can be called from the frontend and how to register it with the Tauri application builder. Requires Tauri and Rust setup. ```rust #[tauri::command] fn my_command(arg: String) -> Result { // Implementation Ok(format!("Received: {}", arg)) } fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![my_command]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Basic esbuild Bundling (Command Line) Source: https://github.com/mindrally/skills/blob/main/esbuild-bundler/SKILL.md Demonstrates basic esbuild command-line usage for bundling a TypeScript entry point into a JavaScript file. Includes options for production builds with minification and source maps, and watch mode for continuous rebuilding. ```bash # Basic bundle esbuild src/index.ts --bundle --outfile=dist/bundle.js # Production build esbuild src/index.ts --bundle --minify --sourcemap --outfile=dist/bundle.js # Watch mode esbuild src/index.ts --bundle --watch --outfile=dist/bundle.js ``` -------------------------------- ### Redis Hash Data Structure Examples Source: https://github.com/mindrally/skills/blob/main/redis-best-practices/SKILL.md Shows how to use Redis Hashes for storing objects with multiple fields, enabling efficient partial updates and retrieval. Includes examples for setting, getting, and incrementing fields. ```redis # Store user profile HSET user:1234 name "John Doe" email "john@example.com" created_at "2024-01-15" # Get specific fields HGET user:1234 email HMGET user:1234 name email # Increment numeric fields HINCRBY user:1234 login_count 1 # Get all fields HGETALL user:1234 ``` -------------------------------- ### Vite CSS Handling: Preprocessors (TypeScript) Source: https://github.com/mindrally/skills/blob/main/vite/SKILL.md Explains that Vite automatically handles CSS preprocessors like Sass when the corresponding package is installed. ```typescript // Automatically handled with package installed // npm install -D sass import './styles.scss'; ``` -------------------------------- ### Blazor Virtualization Example Source: https://github.com/mindrally/skills/blob/main/blazor/SKILL.md Shows how to implement virtualization in Blazor to efficiently render large lists of items, improving performance by only rendering visible elements. ```razor
@item.Name
``` -------------------------------- ### Basic HTTP Server with Deno.serve Source: https://github.com/mindrally/skills/blob/main/deno-typescript/SKILL.md A simple example of creating an HTTP server using Deno's built-in `Deno.serve` API. It demonstrates handling different URL paths and HTTP methods. ```typescript // Simple HTTP server Deno.serve({ port: 8000 }, (req) => { const url = new URL(req.url); if (url.pathname === "/api/users" && req.method === "GET") { return Response.json({ users: [] }); } return new Response("Not Found", { status: 404 }); }); ``` -------------------------------- ### Vite Manual Hot Module Replacement (TypeScript) Source: https://github.com/mindrally/skills/blob/main/vite/SKILL.md Provides an example of manually handling Hot Module Replacement (HMR) for modules that do not natively support it. ```typescript // For libraries without HMR support if (import.meta.hot) { import.meta.hot.accept('./module.ts', (newModule) => { // Handle the updated module console.log('Module updated:', newModule); }); import.meta.hot.dispose(() => { // Cleanup before module is replaced }); } ``` -------------------------------- ### Alpine.js Integration for Interactive Elements Source: https://github.com/mindrally/skills/blob/main/ghost/SKILL.md Provides an example of integrating Alpine.js into a Handlebars template to create interactive UI elements, such as a toggleable navigation menu. ```handlebars
``` -------------------------------- ### Basic esbuild Bundling (JavaScript API) Source: https://github.com/mindrally/skills/blob/main/esbuild-bundler/SKILL.md Shows how to use the esbuild JavaScript API to perform a basic bundle operation. This example configures entry points, bundling, minification, source maps, and the output file path. ```javascript import * as esbuild from 'esbuild'; await esbuild.build({ entryPoints: ['src/index.ts'], bundle: true, minify: true, sourcemap: true, outfile: 'dist/bundle.js' }); ``` -------------------------------- ### CSS Main Entry Point Example Source: https://github.com/mindrally/skills/blob/main/postcss-best-practices/SKILL.md Shows an example of a main CSS file (`main.css`) that imports other CSS files using the `@import` rule. This approach allows for a modular CSS architecture, with variables and base styles imported first, followed by layout, components, and utilities. ```css /* main.css */ /* Variables first */ @import 'variables.css'; /* Reset and base styles */ @import 'base/reset.css'; @import 'base/typography.css'; @import 'base/base.css'; /* Layout */ @import 'layout/grid.css'; @import 'layout/header.css'; @import 'layout/footer.css'; /* Components */ @import 'components/buttons.css'; @import 'components/cards.css'; @import 'components/forms.css'; @import 'components/navigation.css'; /* Utilities (last for specificity) */ @import 'utilities/spacing.css'; @import 'utilities/colors.css'; @import 'utilities/display.css'; ``` -------------------------------- ### Ionic Native Camera Plugin Example Source: https://github.com/mindrally/skills/blob/main/ionic/SKILL.md Shows how to integrate the Ionic Native Camera plugin to capture images within an Ionic application. This requires the camera plugin to be installed. ```typescript import { Camera } from '@ionic-native/camera/ngx'; async takePicture() { const image = await this.camera.getPicture(options); return image; } ``` -------------------------------- ### Context Propagation Example Source: https://github.com/mindrally/skills/blob/main/go-backend-microservices/SKILL.md Shows how to use Go's `context` package for managing request-scoped values, deadlines, and cancellations. It highlights passing `context` as the first parameter and respecting cancellation signals in long-running operations. ```go import ( "context" "time" ) func processRequest(ctx context.Context, data string) error { select { case <-ctx.Done(): return ctx.Err() // Return context error if cancelled or timed out case <-time.After(5 * time.Second): // Simulate a long-running operation // Process data fmt.Println("Processing data:", data) return nil } } ``` -------------------------------- ### Component Testing with Vitest in Svelte Source: https://github.com/mindrally/skills/blob/main/sveltekit/SKILL.md Provides an example of unit testing a Svelte component using Vitest and @testing-library/svelte. It demonstrates rendering a Button component and asserting its text content. ```typescript // Component testing with Vitest import { render, screen } from '@testing-library/svelte'; import { expect, test } from 'vitest'; import Button from './Button.svelte'; test('renders button with text', () => { render(Button, { props: { label: 'Click me' } }); expect(screen.getByRole('button')).toHaveTextContent('Click me'); }); ``` -------------------------------- ### Bootstrap Grid System Example (HTML) Source: https://github.com/mindrally/skills/blob/main/web-development/SKILL.md Demonstrates the use of Bootstrap's grid system for creating responsive layouts. It shows how to structure columns that adapt to different screen sizes (col-12, col-md-6, col-lg-4). ```html
Column 1
Column 2
Column 3
``` -------------------------------- ### Auth0 Action Structure and Best Practices (JavaScript) Source: https://github.com/mindrally/skills/blob/main/auth0-authentication/SKILL.md Provides an example of an Auth0 Action's structure, demonstrating best practices for the `onExecutePostLogin` event. It includes early returns, using secrets, minimizing external calls, and adding custom claims. ```javascript exports.onExecutePostLogin = async (event, api) => { // 1. Early returns for efficiency if (!event.user.email_verified) { api.access.deny('Please verify your email before logging in.'); return; } // 2. Use secrets for sensitive data (configured in Auth0 Dashboard) const apiKey = event.secrets.EXTERNAL_API_KEY; // 3. Minimize external calls - they affect login latency // 4. Never log sensitive information console.log(`User logged in: ${event.user.user_id}`); // 5. Add custom claims sparingly api.idToken.setCustomClaim('https://myapp.com/roles', event.authorization?.roles || []); api.accessToken.setCustomClaim('https://myapp.com/roles', event.authorization?.roles || []); }; ``` -------------------------------- ### SvelteKit Server-Side Error Handling Source: https://github.com/mindrally/skills/blob/main/sveltekit/SKILL.md Shows how to handle errors on the server-side in a SvelteKit application using the 'error' function from '@sveltejs/kit'. This example demonstrates throwing a 404 error if a post is not found. ```typescript // +page.server.ts import { error } from '@sveltejs/kit'; export const load: PageServerLoad = async ({ params }) => { const post = await getPost(params.slug); if (!post) { throw error(404, 'Post not found'); } return { post }; }; ``` -------------------------------- ### Ghost Handlebars Loop Helpers Source: https://github.com/mindrally/skills/blob/main/ghost/SKILL.md Illustrates the use of loop helpers like `foreach` and `get` to iterate over posts and retrieve specific sets of posts based on filters. ```handlebars {{#foreach posts}} {{!-- Access loop variables --}} {{#if @first}}
{{/if}} {{> post-card}} {{#if @first}}
{{/if}} {{/foreach}} {{!-- Get posts with specific tag --}} {{#get "posts" filter="tag:featured" limit="3"}} {{#foreach posts}} {{> post-card}} {{/foreach}} {{/get}} ``` -------------------------------- ### Fastify Route Organization Example Source: https://github.com/mindrally/skills/blob/main/fastify-typescript/SKILL.md Demonstrates how to organize routes by resource using Fastify plugins. It defines GET, POST, PUT, and DELETE endpoints for users, specifying request/response schemas. ```typescript import { FastifyPluginAsync } from 'fastify'; const usersRoutes: FastifyPluginAsync = async (fastify) => { fastify.get('/', { schema: listUsersSchema }, listUsersHandler); fastify.get('/:id', { schema: getUserSchema }, getUserHandler); fastify.post('/', { schema: createUserSchema }, createUserHandler); fastify.put('/:id', { schema: updateUserSchema }, updateUserHandler); fastify.delete('/:id', { schema: deleteUserSchema }, deleteUserHandler); }; export default usersRoutes; ``` -------------------------------- ### esbuild Multiple Entry Points with Code Splitting Source: https://github.com/mindrally/skills/blob/main/esbuild-bundler/SKILL.md Demonstrates configuring esbuild to handle multiple entry points and enable code splitting for optimized loading. This setup is ideal for applications with distinct code modules or dynamic imports. ```javascript await esbuild.build({ entryPoints: ['src/index.ts', 'src/worker.ts'], bundle: true, outdir: 'dist', splitting: true, format: 'esm' }); ``` -------------------------------- ### Svelte Component Props and Events with TypeScript Source: https://github.com/mindrally/skills/blob/main/sveltekit/SKILL.md Shows how to define props for a Svelte component and handle custom events using `createEventDispatcher`. This example includes type safety for props and event payloads. ```svelte ``` -------------------------------- ### SvelteKit Project Structure Overview Source: https://github.com/mindrally/skills/blob/main/sveltekit/SKILL.md Illustrates the typical directory structure for a SvelteKit project, including directories for components, server utilities, stores, shared utilities, routes, and the main HTML template. ```text src/ ├── lib/ │ ├── components/ # Reusable Svelte components │ ├── server/ # Server-only utilities │ ├── stores/ # Svelte stores │ └── utils/ # Shared utilities ├── routes/ │ ├── +layout.svelte # Root layout │ ├── +page.svelte # Home page │ └── api/ # API routes ├── app.html # HTML template └── app.css # Global styles ``` -------------------------------- ### Input Validation Example Source: https://github.com/mindrally/skills/blob/main/go-backend-microservices/SKILL.md Demonstrates basic input validation in Go, a crucial security practice for sanitizing external inputs before processing. This helps prevent common vulnerabilities like injection attacks. ```go import ( "errors" "strings" ) func validateInput(input string) error { if strings.Contains(input, "