Code Blocks

Code Examples

Plain text

Plain text...

CSS

body {
  font-family: 'Arial', sans-serif;
  color: #333;
  margin: 0;
  padding: 20px;
  background: linear-gradient(to right, #f5f7fa, #c3cfe2);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

Django

{% extends "base.html" %}

{% block title %}My Page{% endblock %}

{% block content %}
  <h1>{{ page_title }}</h1>
  <ul>
    {% for item in items %}
      <li>{{ item.name }} - {{ item.price }}</li>
    {% endfor %}
  </ul>
{% endblock %}

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sample Page</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="container">
    <h1>Welcome to our website</h1>
    <p>This is a sample HTML document.</p>
  </div>
  <script src="script.js"></script>
</body>
</html>

JSON

{
  "course": {
    "title": "Introduction to Programming",
    "instructor": "John Doe",
    "duration": 8,
    "modules": [
      {
        "id": 1,
        "title": "Getting Started",
        "lessons": ["Setup", "Basic Concepts"]
      },
      {
        "id": 2,
        "title": "Core Concepts",
        "lessons": ["Variables", "Functions", "Control Flow"]
      }
    ]
  }
}

Mermaid Diagram

graph TD
    A[Start] --> B{Is it working?}
    B -->|Yes| C[Great!]
    B -->|No| D[Debug]
    D --> B
    C --> E[Deploy]

XML

<?xml version="1.0" encoding="UTF-8"?>
<courses>
 <course id="101">
   <title>Web Development Fundamentals</title>
   <instructor>Jane Smith</instructor>
   <duration>10 weeks</duration>
   <topics>
     <topic>HTML</topic>
     <topic>CSS</topic>
     <topic>JavaScript</topic>
   </topics>
 </course>
</courses>

YAML

course:
  title: Data Science Basics
  instructor: Alex Johnson
  duration: 6 weeks
  modules:
    - name: Introduction
      lessons:
        - Python Basics
        - Jupyter Notebooks
    - name: Data Analysis
      lessons:
        - NumPy
        - Pandas
    - name: Visualization
      lessons:
        - Matplotlib
        - Seaborn

Programming Languages

C

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    
    int numbers[5] = {1, 2, 3, 4, 5};
    int sum = 0;
    
    for (int i = 0; i < 5; i++) {
        sum += numbers[i];
    }
    
    printf("Sum: %d\n", sum);
    return 0;
}

C++

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 9};
    
    std::sort(numbers.begin(), numbers.end());
    
    std::cout << "Sorted numbers: ";
    for (const auto& num : numbers) {
        std::cout << num << " ";
    }
    
    return 0;
}

C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace Example {
    class Program {
        static void Main(string[] args) {
            List<int> numbers = new List<int> {5, 2, 8, 1, 9};
            
            var sortedNumbers = numbers.OrderBy(n => n);
            
            Console.WriteLine("Sorted numbers: " + string.Join(", ", sortedNumbers));
        }
    }
}

Dart

void main() {
  var list = [5, 2, 8, 1, 9];
  list.sort();
  
  print('Sorted numbers: $list');
  
  final person = Person('John', 30);
  print(person);
}

class Person {
  final String name;
  final int age;
  
  Person(this.name, this.age);
  
  @override
  String toString() => 'Person($name, $age)';
}

Go

package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{5, 2, 8, 1, 9}
    sort.Ints(numbers)
    
    fmt.Printf("Sorted numbers: %v\n", numbers)
}

Java

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 8, 1, 9};
        Arrays.sort(numbers);
        
        System.out.print("Sorted numbers: ");
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}

JavaScript

const numbers = [5, 2, 8, 1, 9];
numbers.sort((a, b) => a - b);

console.log("Sorted numbers:", numbers);

// Arrow function
const add = (a, b) => a + b;

// Async/await example
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

Kotlin

fun main() {
    val numbers = mutableListOf(5, 2, 8, 1, 9)
    numbers.sort()
    
    println("Sorted numbers: $numbers")
    
    // Data class example
    val person = Person("Alice", 28)
    println(person)
}

data class Person(val name: String, val age: Int)

MATLAB

% Create and sort an array
numbers = [5, 2, 8, 1, 9];
sortedNumbers = sort(numbers);

disp('Sorted numbers:');
disp(sortedNumbers);

% Create a simple plot
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y);
title('Sine Wave');
xlabel('x');
ylabel('sin(x)');

Perl

#!/usr/bin/perl
use strict;
use warnings;

my @numbers = (5, 2, 8, 1, 9);
my @sorted = sort { $a <=> $b } @numbers;

print "Sorted numbers: @sorted\n";

# Hash example
my %person = (
    name => "David",
    age => 35,
    city => "New York"
);

foreach my $key (keys %person) {
    print "$key: $person{$key}\n";
}

PHP

<?php
$numbers = [5, 2, 8, 1, 9];
sort($numbers);

echo "Sorted numbers: ";
foreach ($numbers as $num) {
    echo "$num ";
}

// Associative array
$person = [
    'name' => 'Michael',
    'age' => 32,
    'city' => 'Boston'
];

// Functions
function greet($name) {
    return "Hello, $name!";
}

echo greet($person['name']);
?>

Python

def sort_numbers():
    numbers = [5, 2, 8, 1, 9]
    numbers.sort()
    print(f"Sorted numbers: {numbers}")

sort_numbers()

# Class example
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, my name is {self.name}"

person = Person("Sarah", 29)
print(person.greet())

R

# Create and sort a vector
numbers <- c(5, 2, 8, 1, 9)
sorted_numbers <- sort(numbers)

cat("Sorted numbers:", sorted_numbers, "\n")

# Create a data frame
df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  age = c(25, 30, 35),
  city = c("New York", "Boston", "Chicago")
)

# Plot example
plot(mtcars$wt, mtcars$mpg, 
     xlab = "Weight", 
     ylab = "Miles per Gallon", 
     main = "Car Weight vs MPG")

Ruby

# Sort an array
numbers = [5, 2, 8, 1, 9]
sorted = numbers.sort

puts "Sorted numbers: #{sorted}"

# Class example
class Person
  attr_reader :name, :age
  
  def initialize(name, age)
    @name = name
    @age = age
  end
  
  def greet
    "Hello, my name is #{@name}"
  end
end

person = Person.new("Emily", 27)
puts person.greet

Rust

fn main() {
    let mut numbers = vec![5, 2, 8, 1, 9];
    numbers.sort();
    
    println!("Sorted numbers: {:?}", numbers);
    
    // Struct example
    struct Person {
        name: String,
        age: u32,
    }
    
    let person = Person {
        name: String::from("James"),
        age: 31,
    };
    
    println!("{} is {} years old", person.name, person.age);
}

Scala

object Example {
  def main(args: Array[String]): Unit = {
    val numbers = List(5, 2, 8, 1, 9)
    val sortedNumbers = numbers.sorted
    
    println(s"Sorted numbers: $sortedNumbers")
    
    // Case class example
    case class Person(name: String, age: Int)
    val person = Person("Thomas", 33)
    
    println(s"${person.name} is ${person.age} years old")
  }
}

Swift

import Foundation

// Sort an array
var numbers = [5, 2, 8, 1, 9]
numbers.sort()

print("Sorted numbers: \(numbers)")

// Struct example
struct Person {
    let name: String
    let age: Int
    
    func greet() -> String {
        return "Hello, my name is \(name)"
    }
}

let person = Person(name: "Lisa", age: 26)
print(person.greet())

TypeScript

// Define an interface
interface Person {
    name: string;
    age: number;
    greet(): string;
}

// Implement the interface
class Employee implements Person {
    constructor(public name: string, public age: number, private role: string) {}
    
    greet(): string {
        return `Hello, I'm ${this.name}, the ${this.role}`;
    }
}

const numbers: number[] = [5, 2, 8, 1, 9];
numbers.sort((a, b) => a - b);

console.log(`Sorted numbers: ${numbers}`);

const employee = new Employee("Mark", 34, "Developer");
console.log(employee.greet());

Database Languages

PostgreSQL

-- Create a table
CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    department VARCHAR(50),
    salary NUMERIC(10, 2)
);

-- Insert data
INSERT INTO employees (name, department, salary)
VALUES 
    ('John Smith', 'Engineering', 85000.00),
    ('Sarah Johnson', 'Marketing', 72000.00),
    ('Michael Brown', 'Engineering', 92000.00);

-- Query with joins and aggregation
SELECT 
    department, 
    COUNT(*) as employee_count,
    AVG(salary) as average_salary
FROM employees
GROUP BY department
ORDER BY average_salary DESC;

SQL

-- Create a table
CREATE TABLE customers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE,
    city VARCHAR(50),
    signup_date DATE
);

-- Insert data
INSERT INTO customers (name, email, city, signup_date)
VALUES 
    ('Alice Smith', 'alice@example.com', 'New York', '2023-01-15'),
    ('Bob Johnson', 'bob@example.com', 'Chicago', '2023-02-20'),
    ('Carol Davis', 'carol@example.com', 'Boston', '2023-03-05');

-- Query with conditions
SELECT 
    name,
    email,
    DATEDIFF(CURRENT_DATE, signup_date) as days_since_signup
FROM customers
WHERE city = 'New York'
ORDER BY signup_date DESC;

System & Tools

Bash

#!/bin/bash

# Function definition
backup_files() {
    echo "Starting backup of $1"
    tar -czf backup_$(date +%Y%m%d).tar.gz "$1"
    echo "Backup completed"
}

# Process command line arguments
if [ $# -eq 0 ]; then
    echo "Usage: $0 <directory_to_backup>"
    exit 1
fi

# Check if directory exists
if [ ! -d "$1" ]; then
    echo "Error: Directory $1 not found"
    exit 2
fi

# Call function
backup_files "$1"

# Loop example
echo "Files in current directory:"
for file in $(ls); do
    echo "- $file"
done

Diff

--- file1.txt    2023-05-20 10:00:00
+++ file2.txt    2023-05-25 14:30:00
@@ -1,7 +1,8 @@
 # Configuration file
 
 # Server settings
-port=8080
+# Changed port to 8443 for HTTPS
+port=8443
 hostname=example.com
-debug=true
+debug=false
 
@@ -15,4 +16,5 @@
 # Database configuration
 db.host=localhost
 db.user=admin
+db.password=secure_password
 db.name=app_database

Dockerfile

FROM node:18-alpine AS build

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build

FROM nginx:alpine

COPY --from=build /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80

# Health check
HEALTHCHECK --interval=30s --timeout=3s \
  CMD wget -q -O /dev/null http://localhost/ || exit 1

CMD ["nginx", "-g", "daemon off;"]

Verilog

module counter (
    input wire clk,
    input wire reset,
    output reg [3:0] count
);

    always @(posedge clk or posedge reset) begin
        if (reset) begin
            count <= 4'b0000;
        end else begin
            count <= count + 1;
        end
    end

endmodule

module counter_tb;
    reg clk;
    reg reset;
    wire [3:0] count;
    
    counter dut (
        .clk(clk),
        .reset(reset),
        .count(count)
    );
    
    initial begin
        clk = 0;
        forever #5 clk = ~clk;
    end
    
    initial begin
        reset = 1;
        #15 reset = 0;
        #100 $finish;
    end
    
    initial begin
        $monitor("Time=%0t: Count=%b", $time, count);
    end
endmodule