OrgPad logo

Supported languages in OrgPad

Created by Pavel Klavík

Examples how different languages are highlighted in OrgPad. All examples here were generated by ChatGPT.

#OrgPad, #code, #examples, #highlighting

Supported languages in OrgPad

5. Arrays

public class Arrays {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};

// Access elements
System.out.println("First element: " + numbers[0]);

// Iterate through an array
for (int num : numbers) {
System.out.println("Number: " + num);
}
}
}

10. Interfaces

interface Greetable {
void greet();
}

class Person implements Greetable {
public void greet() {
System.out.println("Hello!");
}
}

public class Interfaces {
public static void main(String[] args) {
Greetable greeter = new Person();
greeter.greet();
}
}

17. Lambda Expressions

import java.util.function.Function;

public class Lambdas {
public static void main(String[] args) {
Function<Integer, Integer> square = x -> x * x;

System.out.println("Square of 4: " + square.apply(4));
}
}

11. Enums

enum Shape {
CIRCLE, RECTANGLE, TRIANGLE
}

public class Enums {
public static void main(String[] args) {
Shape myShape = Shape.CIRCLE;
System.out.println("Selected shape: " + myShape);
}
}

12. Generics

class Box<T> {
private T value;

public Box(T value) {
this.value = value;
}

public T getValue() {
return value;
}
}

public class Generics {
public static void main(String[] args) {
Box<Integer> intBox = new Box<>(42);
Box<String> strBox = new Box<>("Hello");

System.out.println("Int Value: " + intBox.getValue());
System.out.println("String Value: " + strBox.getValue());
}
}

8. Static Methods

class MathUtils {
public static int square(int x) {
return x * x;
}
}

public class StaticMethods {
public static void main(String[] args) {
System.out.println("Square of 4: " + MathUtils.square(4));
}
}

4. Loops

public class Loops {
public static void main(String[] args) {
// For loop
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}

// While loop
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
}
}

2. Variables

public class Variables {
public static void main(String[] args) {
String name = "Alice"; // Immutable variable
int age = 30; // Mutable variable
age += 1;

System.out.println("Name: " + name + ", Age: " + age);
}
}

2. Variables

#include <iostream>

int main() {
int age = 30;
std::string name = "Alice";

std::cout << "Name: " << name << ", Age: " << age << std::endl;
return 0;
}

2. Variables

#include <stdio.h>

int main() {
int age = 30;
char name[] = "Alice";

printf("Name: %s, Age: %d\n", name, age);
return 0;
}

6. Pointers and References

#include <iostream>

void increment(int &value) {
value++;
}

int main() {
int num = 42;
increment(num);
std::cout << "Incremented value: " << num << std::endl;
return 0;
}

Text comparison

=IF(A1>10, "Greater", "Smaller or Equal")

Explanation: Checks if the value in A1 is greater than 10. Returns "Greater" if true, otherwise "Smaller or Equal".

Sum

=SUM(A1:A10)

Explanation: Adds all numbers in the range A1:A10.

Length

=LEN(A1)

Explanation: Returns the length of the text in A1.

Triming spaces

=TRIM(A1)

Explanation: Removes all extra spaces from the text in A1, leaving only single spaces between words.

Transposition

=TRANSPOSE(A1:A5)

Explanation: Converts the vertical range A1:A5 into a horizontal range.

15. Higher-Order Functions

fun applyOperation(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}

fun main() {
val result = applyOperation(3, 5) { a, b -> a + b }
println("Result: $result")
}

Java

Monthly payment for a loan

=PMT(5%/12, 60, -10000)

Explanation: Calculates the monthly payment for a loan with an annual interest rate of 5%, a term of 60 months, and a loan amount of 10,000.

18. File Handling

import java.io.File

fun main() {
val fileName = "example.txt"
File(fileName).writeText("Hello, File!")

val content = File(fileName).readText()
println(content)
}

Number check

=ISNUMBER(A1)

Explanation: Checks if the value in A1 is a number.

Count for condition

=COUNTIF(A1:A10, ">10")

Explanation: Counts how many values in A1:A10 are greater than 10.

14. Extension Functions

fun String.toTitleCase(): String {
return this.split(" ").joinToString(" ") { it.capitalize() }
}

fun main() {
val text = "hello kotlin"
println(text.toTitleCase())
}

11. Inheritance

using System;

class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal makes a sound");
}
}

class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof!");
}
}

class Program
{
static void Main()
{
Animal myDog = new Dog();
myDog.Speak();
}
}

1. Basic Syntax

using System;

class Program
{
static void Main()
{
// Print to the console
Console.WriteLine("Hello, C#!");

// Simple arithmetic
int x = 5 + 3;
int y = x * 2;
Console.WriteLine($"The result is: {y}");
}
}

19. Reflection

using System;
using System.Reflection;

class Program
{
static void Main()
{
Type type = typeof(string);
Console.WriteLine($"Type: {type.Name}");

foreach (MethodInfo method in type.GetMethods())
{
Console.WriteLine($"Method: {method.Name}");
}
}
}

8. Properties

using System;

class Rectangle
{
public double Width { get; set; }
public double Height { get; set; }

public double Area => Width * Height;
}

class Program
{
static void Main()
{
Rectangle rect = new Rectangle { Width = 5, Height = 10 };
Console.WriteLine($"Area: {rect.Area}");
}
}

6. Methods

public class Methods {
public static int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {
int result = add(3, 5);
System.out.println("Sum: " + result);
}
}

19. Collections

import java.util.ArrayList;

public class Collections {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

for (String fruit : fruits) {
System.out.println(fruit);
}
}
}

5. STL Containers

#include <iostream>
#include <vector>

int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};

for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;

return 0;
}

1. Basic Syntax

#include <iostream>

int main() {
std::cout << "Hello, C++!" << std::endl;
return 0;
}

Excel

20. JSON Handling with kotlinx.serialization

import kotlinx.serialization.*
import kotlinx.serialization.json.*

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

fun main() {
val alice = Person("Alice", 30)

// Serialize to JSON
val json = Json.encodeToString(alice)
println(json)

// Deserialize from JSON
val decoded = Json.decodeFromString<Person>(json)
println(decoded)
}

7. Using Razor Helpers

@helper FormatDate(DateTime date)
{
<span>@date.ToString("MMMM dd, yyyy")</span>
}

<!DOCTYPE html>
<html>
<body>
@FormatDate(DateTime.Now)
</body>
</html>

16. Threads

class MyThread extends Thread {
public void run() {
System.out.println("Hello from thread!");
}
}

public class Threads {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}

9. Inheritance

class Animal {
void speak() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {
@Override
void speak() {
System.out.println("Woof!");
}
}

public class Inheritance {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.speak();
}
}

3. Conditional Statements

using System;

class Program
{
static void Main()
{
int age = 25;

if (age < 18)
{
Console.WriteLine("Minor");
}
else if (age >= 18 && age < 65)
{
Console.WriteLine("Adult");
}
else
{
Console.WriteLine("Senior");
}
}
}

C++

Horizontal lookup

=HLOOKUP(50, A1:D5, 2, FALSE)

Explanation: Searches for 50 in the first row of A1:D5 and returns the value from the second row in the matching column.

Truncation

=LEFT(A1, 5)

Explanation: Extracts the first 5 characters from the text in A1.

5. Conditional Statements

fun main() {
val age = 25

val status = if (age < 18) {
"Minor"
} else if (age in 18..64) {
"Adult"
} else {
"Senior"
}

println("Status: $status")
}

15. Combining AJAX with Razor

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$.get("/Home/GetData", function (data) {
$("#result").html(data);
});
});
</script>

<div id="result"></div>

15. File Handling

import java.io.*;

public class FileHandling {
public static void main(String[] args) throws IOException {
// Write to a file
BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));
writer.write("Hello, File!");
writer.close();

// Read from a file
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
String content = reader.readLine();
System.out.println(content);
reader.close();
}
}

Combining values

=TEXT(A1, "MM/DD/YYYY") & " - " & B1

Explanation: Combines a formatted date from A1 and the value in B1 with a dash.

Average

=AVERAGE(B1:B10)

Explanation: Calculates the average of numbers in the range B1:B10.

10. Data Classes

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

fun main() {
val alice = Person("Alice", 30)
println(alice)
}

8. Maps

fun main() {
val person = mapOf("name" to "Alice", "age" to 30)

println("Name: ${person["name"]}")
println("Age: ${person["age"]}")
}

C

18. Reflection

import java.lang.reflect.Method;

public class Reflection {
public static void main(String[] args) {
Method[] methods = String.class.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
}
}

Current date and time

=NOW()

Explanation: Returns the current date and time.

Concatenation

=CONCATENATE(A1, " ", B1)

Explanation: Combines the values of A1 and B1 with a space in between.

Unique values

=UNIQUE(A1:A10)

Explanation: Extracts unique values from the range A1:A10 (available in Excel 365/2021).

11. Razor Sections

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
@RenderSection("Scripts", required: false)
</head>
<body>
<main>
@RenderBody()
</main>
</body>
</html>

Index.cshtml

@section Scripts {
<script>
console.log("This is a custom script for Index page.");
</script>
}
<h2>Content for Index Page</h2>

13. Error Handling

public class ErrorHandling {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

3. Conditional Statements

public class Conditional {
public static void main(String[] args) {
int age = 25;

if (age < 18) {
System.out.println("Minor");
} else if (age >= 18 && age < 65) {
System.out.println("Adult");
} else {
System.out.println("Senior");
}
}
}

5. Functions

#include <stdio.h>

int add(int a, int b) {
return a + b;
}

int main() {
int result = add(3, 5);
printf("Sum: %d\n", result);
return 0;
}

Absolute value

=ABS(A1)

Explanation: Returns the absolute value of the number in A1.

17. Delegates

using System;

delegate int Operation(int a, int b);

class Program
{
static void Main()
{
Operation add = (a, b) => a + b;
Console.WriteLine($"Sum: {add(3, 5)}");
}
}

14. LINQ

using System;
using System.Linq;

class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };

var evens = numbers.Where(n => n % 2 == 0);

foreach (int num in evens)
{
Console.WriteLine($"Even: {num}");
}
}
}

18. File Handling

using System;
using System.IO;

class Program
{
static void Main()
{
File.WriteAllText("example.txt", "Hello, File!");

string content = File.ReadAllText("example.txt");
Console.WriteLine(content);
}
}

3. Loops

@{
var items = new[] { "Apple", "Banana", "Cherry" };
}
<!DOCTYPE html>
<html>
<body>
<ul>
@foreach (var item in items)
{
<li>@item</li>
}
</ul>
</body>
</html>

1. Basic Syntax

#include <stdio.h>

int main() {
printf("Hello, C!\n");
return 0;
}

3. Classes

#include <iostream>

class Person {
public:
std::string name;
int age;

Person(std::string name, int age) : name(name), age(age) {}

void greet() {
std::cout << "Hi, I'm " << name << " and I'm " << age << " years old." << std::endl;
}
};

int main() {
Person alice("Alice", 30);
alice.greet();
return 0;
}

Vertical lookup

=VLOOKUP(101, A1:C10, 2, FALSE)

Explanation: Searches for 101 in the first column of A1:C10 and returns the corresponding value from the second column.

17. Generics

class Box<T>(val value: T) {
fun getValue(): T = value
}

fun main() {
val intBox = Box(42)
val strBox = Box("Hello")

println(intBox.getValue())
println(strBox.getValue())
}

9. Classes

class Person(val name: String, var age: Int) {
fun greet() {
println("Hi, I'm $name and I'm $age years old.")
}
}

fun main() {
val alice = Person("Alice", 30)
alice.greet()
}

Kotlin

15. Async and Await

using System;
using System.Threading.Tasks;

class Program
{
static async Task<string> FetchDataAsync()
{
await Task.Delay(1000);
return "Data fetched!";
}

static async Task Main()
{
Console.WriteLine("Fetching...");
string data = await FetchDataAsync();
Console.WriteLine(data);
}
}

Rounding

=ROUND(A1, 2)

Explanation: Rounds the value in A1 to two decimal places.

12. Sealed Classes

sealed class Shape {
data class Circle(val radius: Double) : Shape()
data class Rectangle(val width: Double, val height: Double) : Shape()
}

fun area(shape: Shape): Double {
return when (shape) {
is Shape.Circle -> Math.PI * shape.radius * shape.radius
is Shape.Rectangle -> shape.width * shape.height
}
}

fun main() {
val circle = Shape.Circle(5.0)
println("Circle area: ${area(circle)}")
}

5. Arrays

using System;

class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };

// Access elements
Console.WriteLine(numbers[0]);

// Iterate through an array
foreach (int num in numbers)
{
Console.WriteLine($"Number: {num}");
}
}
}

13. Using Tag Helpers

<!DOCTYPE html>
<html>
<body>
<form asp-controller="Home" asp-action="Submit" method="post">
<label asp-for="Name"></label>
<input asp-for="Name" />
<button type="submit">Submit</button>
</form>
</body>
</html>

Capitalize words

=PROPER(A1)

Explanation: Capitalizes the first letter of each word in the text of A1.

C#

Searching

=INDEX(C1:C10, MATCH(50, A1:A10, 0))

Explanation: Finds the row where 50 appears in A1:A10 and retrieves the corresponding value from C1:C10.

7. Classes and Objects

class Person {
String name;
int age;

Person(String name, int age) {
this.name = name;
this.age = age;
}

void greet() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}
}

public class Classes {
public static void main(String[] args) {
Person alice = new Person("Alice", 30);
alice.greet();
}
}

14. Streams

import java.util.Arrays;

public class Streams {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};

Arrays.stream(numbers)
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
}
}

20. JSON Handling (Using Gson)

import com.google.gson.Gson;

class Person {
String name;
int age;

Person(String name, int age) {
this.name = name;
this.age = age;
}
}

public class JsonHandling {
public static void main(String[] args) {
Gson gson = new Gson();

// Serialize
Person alice = new Person("Alice", 30);
String json = gson.toJson(alice);
System.out.println(json);

// Deserialize
Person person = gson.fromJson(json, Person.class);
System.out.println(person.name + ", " + person.age);
}
}

1. Basic Syntax

public class HelloWorld {
public static void main(String[] args) {
// Print to the console
System.out.println("Hello, Java!");
}
}

2. Variables

fun main() {
val name = "Alice" // Immutable variable
var age = 30 // Mutable variable
age += 1

println("Name: $name, Age: $age")
}

6. Including Partial Views

_PartialView.cshtml

<h3>This is a partial view.</h3>

MainView.cshtml

<!DOCTYPE html>
<html>
<body>
@Html.Partial("_PartialView")
</body>
</html>

5. Inline C# Code

<!DOCTYPE html>
<html>
<body>
@for (int i = 1; i <= 5; i++)
{
<p>Number: @i</p>
}
</body>
</html>

C# HTML

4. Templates

#include <iostream>

template <typename T>
T square(T x) {
return x * x;
}

int main() {
std::cout << "Square of 5: " << square(5) << std::endl;
std::cout << "Square of 4.5: " << square(4.5) << std::endl;
return 0;
}

4. Pointers

#include <stdio.h>

int main() {
int num = 42;
int *ptr = &num;

printf("Value: %d, Address: %p\n", *ptr, ptr);
return 0;
}

3. Arrays

#include <stdio.h>

int main() {
int numbers[3] = {1, 2, 3};

for (int i = 0; i < 3; i++) {
printf("Number: %d\n", numbers[i]);
}

return 0;
}

19. Exception Handling

fun main() {
try {
val result = 10 / 0
} catch (e: ArithmeticException) {
println("Error: ${e.message}")
}
}

3. Functions

fun add(a: Int, b: Int): Int {
return a + b
}

fun main() {
val result = add(3, 5)
println("Sum: $result")
}

4. Lambda Functions

fun main() {
val square: (Int) -> Int = { x -> x * x }
println("Square of 4: ${square(4)}")
}

13. Null Safety

fun main() {
val name: String? = null

val length = name?.length ?: 0
println("Length: $length")
}

12. Interfaces

using System;

interface IGreetable
{
void Greet();
}

class Person : IGreetable
{
public void Greet()
{
Console.WriteLine("Hello!");
}
}

class Program
{
static void Main()
{
IGreetable greeter = new Person();
greeter.Greet();
}
}

10. Enums

using System;

enum Shape
{
Circle,
Rectangle,
Triangle
}

class Program
{
static void Main()
{
Shape myShape = Shape.Circle;
Console.WriteLine($"Selected shape: {myShape}");
}
}

13. Error Handling

using System;

class Program
{
static void Main()
{
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}

2. Variables and Constants

using System;

class Program
{
static void Main()
{
const string name = "Alice"; // Immutable constant
int age = 30; // Mutable variable
age += 1;

Console.WriteLine($"Name: {name}, Age: {age}");
}
}

7. Classes and Objects

using System;

class Person
{
public string Name { get; set; }
public int Age { get; set; }

public void Greet()
{
Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
}
}

class Program
{
static void Main()
{
Person alice = new Person { Name = "Alice", Age = 30 };
alice.Greet();
}
}

4. Using Layouts

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
<title>@ViewData["Title"]</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<main>
@RenderBody()
</main>
</body>
</html>

Index.cshtml

@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewData["Title"] = "Home Page";
}
<h2>Welcome to the home page!</h2>

1. Basic Syntax

fun main() {
// Print to the console
println("Hello, Kotlin!")

// Simple arithmetic
val x = 5 + 3
val y = x * 2
println("The result is: $y")
}

7. Lists

fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")

// Access elements
println(fruits[0])

// Iterate through the list
for (fruit in fruits) {
println("Fruit: $fruit")
}
}

9. Using ViewData and ViewBag

@{
ViewBag.Message = "Welcome to Razor!";
ViewData["Date"] = DateTime.Now.ToString("MMMM dd, yyyy");
}
<!DOCTYPE html>
<html>
<body>
<h1>@ViewBag.Message</h1>
<p>Today's date is @ViewData["Date"]</p>
</body>
</html>

1. Basic Razor Syntax

@{
var message = "Hello, CSHTML!";
}
<!DOCTYPE html>
<html>
<head>
<title>CSHTML Example</title>
</head>
<body>
<h1>@message</h1>
</body>
</html>

11. Enums

enum class Shape {
Circle, Rectangle, Triangle
}

fun main() {
val myShape = Shape.Circle
println("Selected shape: $myShape")
}

6. Loops

fun main() {
// For loop
for (i in 1..5) {
println("Iteration: $i")
}

// While loop
var count = 0
while (count < 3) {
println("Count: $count")
count++
}
}

16. Coroutines

import kotlinx.coroutines.*

fun main() = runBlocking {
val job = launch {
delay(1000L)
println("Coroutine done!")
}
println("Waiting...")
job.join()
}

14. Including Static Files

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>CSHTML with CSS</h1>
<script src="scripts.js"></script>
</body>
</html>

20. Dart Packages

// Add http to pubspec.yaml:
// dependencies:
// http: ^0.15.0

import 'package:http/http.dart' as http;

void main() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
print(response.body);
} else {
print('Failed to fetch data');
}
}

7. Maps

void main() {
// Define a map
Map<String, int> person = {'Alice': 30, 'Bob': 25};

// Access elements
print('Alice\'s age: ${person['Alice']}');

// Add a new key-value pair
person['Charlie'] = 35;
print(person);
}

2. Variables

void main() {
// Immutable variable
final String name = 'Alice';

// Mutable variable
var age = 30;
age = 31;

print('Name: $name, Age: $age');
}

14. Inheritance

class Animal {
void speak() {
print('Animal makes a sound');
}
}

class Dog extends Animal {
@override
void speak() {
print('Woof!');
}
}

void main() {
Dog myDog = Dog();
myDog.speak();
}

16. Generics

fn square<T: std::ops::Mul<Output = T> + Copy>(x: T) -> T {
x * x
}

fn main() {
println!("Square of 4: {}", square(4));
println!("Square of 4.5: {}", square(4.5));
}

9. Generics

using System;

class Box<T>
{
public T Value { get; set; }
}

class Program
{
static void Main()
{
Box<int> intBox = new Box<int> { Value = 42 };
Box<string> strBox = new Box<string> { Value = "Hello" };

Console.WriteLine($"Int Value: {intBox.Value}");
Console.WriteLine($"String Value: {strBox.Value}");
}
}

10. Error Handling

void main() {
try {
int result = 10 ~/ 0; // Integer division by zero
} catch (e) {
print('Error: $e');
}
}

6. Methods

using System;

class Program
{
static int Add(int a, int b)
{
return a + b;
}

static void Main()
{
int result = Add(3, 5);
Console.WriteLine($"Sum: {result}");
}
}

4. Loops

using System;

class Program
{
static void Main()
{
// For loop
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Iteration: {i}");
}

// While loop
int count = 0;
while (count < 3)
{
Console.WriteLine($"Count: {count}");
count++;
}
}
}

16. Events

using System;

class Button
{
public event Action Clicked;

public void Click()
{
Clicked?.Invoke();
}
}

class Program
{
static void Main()
{
Button button = new Button();
button.Clicked += () => Console.WriteLine("Button clicked!");

button.Click();
}
}

20. Extension Methods

using System;

static class StringExtensions
{
public static string ToTitleCase(this string str)
{
return char.ToUpper(str[0]) + str.Substring(1).ToLower();
}
}

class Program
{
static void Main()
{
string text = "hello";
Console.WriteLine(text.ToTitleCase());
}
}

12. Razor with Models

Model: Product.cs

public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}

View: ProductList.cshtml

@model IEnumerable<Product>

<!DOCTYPE html>
<html>
<body>
<ul>
@foreach (var product in Model)
{
<li>@product.Name - $@product.Price</li>
}
</ul>
</body>
</html>

20. Iterators

fn main() {
let numbers = vec![1, 2, 3, 4, 5];

let doubled: Vec<_> = numbers.iter().map(|x| x * 2).collect();
println!("Doubled: {:?}", doubled);
}

8. Forms and Input

<!DOCTYPE html>
<html>
<body>
<form method="post" action="/Home/Submit">
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
<button type="submit">Submit</button>
</form>
</body>
</html>

2. Conditional Rendering

@{
var isLoggedIn = true;
var username = "Alice";
}
<!DOCTYPE html>
<html>
<body>
@if (isLoggedIn)
{
<h1>Welcome, @username!</h1>
}
else
{
<h1>Please log in.</h1>
}
</body>
</html>

10. Combining JavaScript with Razor

@{
var username = "Alice";
}
<!DOCTYPE html>
<html>
<body>
<script>
var user = "@username";
console.log("Welcome, " + user);
</script>
</body>
</html>

11. Enums

enum Shape {
Circle(f64),
Rectangle(f64, f64),
}

fn area(shape: Shape) -> f64 {
match shape {
Shape::Circle(radius) => std::f64::consts::PI * radius.powi(2),
Shape::Rectangle(width, height) => width * height,
}
}

fn main() {
let circle = Shape::Circle(5.0);
println!("Circle area: {}", area(circle));
}

10. Structs

struct Person {
name: String,
age: u8,
}

fn main() {
let alice = Person {
name: String::from("Alice"),
age: 30,
};

println!("Name: {}, Age: {}", alice.name, alice.age);
}

9. Tuples

fn main() {
let point = (3, 4);
let (x, y) = point;

println!("Point: ({}, {})", x, y);
}

3. Functions

int add(int a, int b) {
return a + b;
}

void main() {
int result = add(3, 5);
print('Sum: $result');
}

12. Futures and Async-Await

Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return 'Data fetched!';
}

void main() async {
print('Fetching data...');
String data = await fetchData();
print(data);
}

11. Anonymous Functions

void main() {
List<int> numbers = [1, 2, 3, 4];

// Using an anonymous function
numbers.forEach((num) {
print(num * num);
});
}

5. Loops

void main() {
// For loop
for (int i = 1; i <= 5; i++) {
print('Iteration: $i');
}

// While loop
int count = 0;
while (count < 3) {
print('Count: $count');
count++;
}
}

4. Conditional Statements

void main() {
int age = 25;

if (age < 18) {
print('Minor');
} else if (age >= 18 && age < 65) {
print('Adult');
} else {
print('Senior');
}
}

18. Null Safety

void main() {
String? nullableString = null;

if (nullableString == null) {
print('The string is null');
} else {
print('The string is $nullableString');
}
}

20. Threads

threads = []

5.times do |i|
threads << Thread.new do
puts "Thread #{i} is running"
end
end

threads.each(&:join)

19. Iterators

# Custom iterator
def countdown(start)
while start > 0
yield start
start -= 1
end
end

countdown(5) { |n| puts n }

4. Loops

# For loop
(1..5).each do |i|
puts "Iteration: #{i}"
end

# While loop
count = 0
while count < 3
puts "Count: #{count}"
count += 1
end

7. Methods

def greet(name)
"Hello, #{name}!"
end

puts greet("Alice")

17. Lambdas

# Define a lambda
square = ->(x) { x * x }

puts square.call(5)

5. Arrays

fruits = ["Apple", "Banana", "Cherry"]

# Access elements
puts fruits[0]

# Iterate through an array
fruits.each do |fruit|
puts "Fruit: #{fruit}"
end

6. Loops

fn main() {
// For loop
for i in 1..=5 {
println!("Iteration: {}", i);
}

// While loop
let mut count = 0;
while count < 3 {
println!("Count: {}", count);
count += 1;
}
}

10. String Manipulation

text = "Hello, Python!"

print(text.upper())
print(text.lower())
print(text.replace("Python", "World"))

15. Traits

trait Greet {
fn greet(&self);
}

struct Person {
name: String,
}

impl Greet for Person {
fn greet(&self) {
println!("Hi, I'm {}", self.name);
}
}

fn main() {
let bob = Person {
name: String::from("Bob"),
};
bob.greet();
}

4. Conditional Statements

age = 25

if age < 18:
print("Minor")
elif 18 <= age < 65:
print("Adult")
else:
print("Senior")

19. Async/Await

import asyncio

async def fetch_data():
await asyncio.sleep(1)
return "Data fetched!"

async def main():
print("Fetching...")
data = await fetch_data()
print(data)

asyncio.run(main())

1. Basic Syntax

fn main() {
// Print a message
println!("Hello, Rust!");

// Simple arithmetic
let x = 5 + 3;
let y = x * 2;
println!("The result is: {}", y);
}

Dart

8. Classes

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old."

# Create an instance
alice = Person("Alice", 30)
print(alice.greet())

7. Arrays and Vectors

fn main() {
// Array
let arr = [1, 2, 3];
println!("First element: {}", arr[0]);

// Vector
let mut vec = vec![4, 5, 6];
vec.push(7);
println!("Vector: {:?}", vec);
}

12. Option and Result

fn divide(a: i32, b: i32) -> Option<i32> {
if b == 0 {
None
} else {
Some(a / b)
}
}

fn main() {
match divide(10, 2) {
Some(result) => println!("Result: {}", result),
None => println!("Cannot divide by zero"),
}
}

15. Extensions

extension StringExtension on String {
String toTitleCase() {
return this[0].toUpperCase() + this.substring(1).toLowerCase();
}
}

void main() {
String text = 'hello';
print(text.toTitleCase()); // Output: Hello
}

11. Regular Expressions

text = "The quick brown fox"
if text =~ /quick/
puts "Match found!"
end

puts text.gsub(/fox/, "dog")

Rust

8. Classes

class Person {
String name;
int age;

Person(this.name, this.age);

void greet() {
print('Hi, I\'m $name and I\'m $age years old.');
}
}

void main() {
Person alice = Person('Alice', 30);
alice.greet();
}

1. Basic Syntax

# Print to the console
puts "Hello, Ruby!"

# Simple arithmetic
x = 5 + 3
y = x * 2
puts "The result is: #{y}"

6. Lists

void main() {
// Define a list
List<String> fruits = ['Apple', 'Banana', 'Cherry'];

// Access elements
print(fruits[0]); // Output: Apple

// Iterate through a list
for (String fruit in fruits) {
print('Fruit: $fruit');
}
}

1. Basic Syntax

void main() {
// Print to the console
print('Hello, Dart!');

// Simple arithmetic
int x = 5 + 3;
int y = x * 2;
print('The result is: $y');
}

20. NumPy Example

import numpy as np

# Create a NumPy array
array = np.array([1, 2, 3, 4, 5])

# Perform operations
print(array * 2)
print(array.mean())

18. Mixins

module Greetable
def greet
"Hello!"
end
end

class Person
include Greetable
end

alice = Person.new
puts alice.greet

14. Modules

module MathUtils
def self.square(x)
x * x
end
end

puts MathUtils.square(5)

13. Error Handling

begin
result = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
end

13. Error Handling

try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")

Ruby

3. Constants

const PI: f64 = 3.14159;

fn main() {
println!("Value of Pi: {}", PI);
}

17. Ownership and Borrowing

fn print_string(s: &String) {
println!("{}", s);
}

fn main() {
let s = String::from("Hello");
print_string(&s); // Borrowing
println!("{}", s); // Still accessible
}

17. Iterators and Generators

# Generator function
def countdown(n):
while n > 0:
yield n
n -= 1

for number in countdown(5):
print(number)

12. File Handling

# Write to a file
with open("example.txt", "w") as file:
file.write("Hello, File!")

# Read from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)

7. Arrays

// Define an array
const fruits = ["Apple", "Banana", "Cherry"];

// Access elements
console.log(fruits[0]);

// Iterate through an array
fruits.forEach((fruit) => {
console.log(`Fruit: ${fruit}`);
});

20. Classes with Inheritance

class Animal {
speak() {
return "Animal makes a sound";
}
}

class Dog extends Animal {
speak() {
return "Woof!";
}
}

const myDog = new Dog();
console.log(myDog.speak());

9. Classes

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greet() {
return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
}
}

const alice = new Person("Alice", 30);
console.log(alice.greet());

19. DOM Manipulation

const header: HTMLElement | null = document.querySelector("h1");
if (header) {
header.textContent = "Hello, DOM!";
}

6. Load and Store Example

        AREA LOAD_STORE, CODE, READONLY
ENTRY

LDR R0, =value ; Load address of 'value'
LDR R1, [R0] ; Load the value at address R0 into R1
ADD R1, R1, #10 ; R1 = R1 + 10
STR R1, [R0] ; Store R1 back to memory address R0

B end

value DCD 5 ; Define a word (5)

end
END

4. Loops

        AREA LOOP_EXAMPLE, CODE, READONLY
ENTRY

MOV R0, #0 ; Counter = 0
MOV R1, #5 ; Limit = 5

loop
ADD R0, R0, #1 ; Counter += 1
CMP R0, R1 ; Compare Counter to Limit
BLT loop ; Branch if less than (BLT)

END

13. Pattern Matching

fn main() {
let x = Some(5);

match x {
Some(value) => println!("Value: {}", value),
None => println!("No value"),
}
}

8. Strings

fn main() {
let s = String::from("Hello");
let s_with_world = format!("{}, World!", s);

println!("{}", s_with_world);
}

2. Variables

fn main() {
let immutable_var = "I can't change";
let mut mutable_var = "I can change";
mutable_var = "I've changed!";

println!("{}", immutable_var);
println!("{}", mutable_var);
}

14. Modules

# Import math module
import math

print(f"Pi value: {math.pi}")

5. Interfaces

interface Person {
name: string;
age: number;
}

const alice: Person = { name: "Alice", age: 30 };
console.log(`Name: ${alice.name}, Age: ${alice.age}`);

2. Variables

# Immutable variable
name = "Alice"

# Mutable variable
age = 30
age += 1

print(f"Name: {name}, Age: {age}")

Python

10. Promises

const fetchData = () =>
new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 1000);
});

fetchData().then((data) => console.log(data));

18. keyof and Mapped Types

interface Person {
name: string;
age: number;
}

type PersonKeys = keyof Person; // "name" | "age"

const key: PersonKeys = "name";
console.log(key);

12. Type Aliases

type ID = string | number;

let userId: ID = "123";
console.log(`User ID: ${userId}`);

userId = 456;
console.log(`User ID: ${userId}`);

2. Arithmetic Operations

        AREA ARITHMETIC, CODE, READONLY
ENTRY

MOV R1, #10 ; Load 10 into R1
MOV R2, #5 ; Load 5 into R2

ADD R0, R1, R2 ; R0 = R1 + R2
SUB R3, R1, R2 ; R3 = R1 - R2
MUL R4, R1, R2 ; R4 = R1 * R2
MOV R5, R1, LSR #1 ; R5 = R1 >> 1 (logical shift right)

END

3. Conditional Statements

age = 25

if age < 18
puts "Minor"
elsif age >= 18 && age < 65
puts "Adult"
else
puts "Senior"
end

2. Variables

name = "Alice"
age = 30
is_active = true

puts "Name: #{name}, Age: #{age}, Active: #{is_active}"

12. File Handling

# Write to a file
File.open("example.txt", "w") do |file|
file.puts "Hello, File!"
end

# Read from a file
File.open("example.txt", "r") do |file|
puts file.read
end

15. Enumerable Methods

numbers = [1, 2, 3, 4, 5]

# Map
squared = numbers.map { |n| n * n }
puts "Squared: #{squared}"

# Select
evens = numbers.select { |n| n.even? }
puts "Evens: #{evens}"

17. Streams

Stream<int> countStream(int to) async* {
for (int i = 1; i <= to; i++) {
await Future.delayed(Duration(milliseconds: 500));
yield i;
}
}

void main() async {
await for (int count in countStream(5)) {
print('Count: $count');
}
}

16. Symbols

# Using symbols as keys
person = { name: "Alice", age: 30 }

puts person[:name]

13. Generics

class Box<T> {
T value;

Box(this.value);

void printValue() {
print('Value: $value');
}
}

void main() {
Box<int> intBox = Box(42);
intBox.printValue();

Box<String> strBox = Box('Hello');
strBox.printValue();
}

16. Mixins

mixin Flyable {
void fly() {
print('I can fly!');
}
}

class Bird with Flyable {}

void main() {
Bird bird = Bird();
bird.fly();
}

9. Enums

enum Shape { Circle, Rectangle, Triangle }

void main() {
Shape myShape = Shape.Circle;

switch (myShape) {
case Shape.Circle:
print('Circle selected');
break;
case Shape.Rectangle:
print('Rectangle selected');
break;
case Shape.Triangle:
print('Triangle selected');
break;
}
}

19. JSON Handling

import 'dart:convert';

void main() {
// JSON encoding
Map<String, dynamic> user = {'name': 'Alice', 'age': 30};
String jsonString = jsonEncode(user);
print(jsonString);

// JSON decoding
String data = '{"name": "Bob", "age": 25}';
Map<String, dynamic> userMap = jsonDecode(data);
print(userMap['name']);
}

9. Optional and Default Parameters

function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}

console.log(greet("Alice"));
console.log(greet("Bob", "Hi"));

5. Function Example (Subroutine Call)

        AREA FUNCTION_CALL, CODE, READONLY
ENTRY

MOV R0, #5 ; Input: R0 = 5
BL factorial ; Call factorial function
; R0 contains result

B end

factorial
CMP R0, #1
MOVLE R0, #1 ; Base case: factorial(1) = 1
BXLE LR ; Return if less or equal to 1

PUSH {R1, LR} ; Save R1 and LR on stack
MOV R1, R0 ; R1 = current value of R0
SUB R0, R0, #1 ; R0 -= 1
BL factorial ; Recursive call
MUL R0, R1, R0 ; R0 = R1 * factorial(R0)
POP {R1, LR} ; Restore R1 and LR
BX LR ; Return

end
END

15. Regular Expressions

import re

text = "The quick brown fox"
pattern = r"quick"

if re.search(pattern, text):
print("Pattern found!")

18. DOM Manipulation

// Add content to the DOM
document.body.innerHTML = "<h1>Hello, DOM!</h1>";

// Change an element's style
const header = document.querySelector("h1");
header.style.color = "blue";

5. Conditional Statements

const age = 25;

if (age < 18) {
console.log("Minor");
} else if (age >= 18 && age < 65) {
console.log("Adult");
} else {
console.log("Senior");
}

14. Error Handling

use std::fs::File;

fn main() {
match File::open("nonexistent.txt") {
Ok(_) => println!("File opened successfully"),
Err(e) => println!("Error opening file: {}", e),
}
}

4. Functions

fn add(a: i32, b: i32) -> i32 {
a + b
}

fn main() {
let result = add(3, 5);
println!("Sum: {}", result);
}

18. Concurrency with Threads

use std::thread;

fn main() {
let handle = thread::spawn(|| {
println!("Hello from a thread!");
});

handle.join().unwrap();
}

5. Conditional Statements

fn main() {
let age = 25;

if age < 18 {
println!("Minor");
} else if age >= 18 && age < 65 {
println!("Adult");
} else {
println!("Senior");
}
}

16. Decorators

def greet_decorator(func):
def wrapper(name):
return f"Hello, {func(name)}!"
return wrapper

@greet_decorator
def get_name(name):
return name

print(get_name("Alice"))

7. Dictionaries

# Define a dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}

# Access values
print(f"Name: {person['name']}")

# Add a new key-value pair
person["country"] = "USA"
print(person)

18. JSON Handling

import json

# Convert dictionary to JSON
person = {"name": "Alice", "age": 30}
json_string = json.dumps(person)
print(json_string)

# Convert JSON to dictionary
decoded_person = json.loads(json_string)
print(decoded_person["name"])

10. Union and Intersection Types

type Circle = { radius: number };
type Rectangle = { width: number; height: number };
type Shape = Circle | Rectangle;

function area(shape: Shape): number {
if ("radius" in shape) {
return Math.PI * shape.radius ** 2;
} else {
return shape.width * shape.height;
}
}

console.log(area({ radius: 5 }));
console.log(area({ width: 4, height: 6 }));

9. Blocks and Procs

# Using a block
[1, 2, 3].each { |n| puts n * n }

# Using a proc
square = Proc.new { |x| x * x }
puts square.call(4)

11. List Comprehensions

# Generate squares of numbers from 1 to 5
squares = [x**2 for x in range(1, 6)]
print(squares)

15. Map and Filter

const numbers = [1, 2, 3, 4, 5];

// Map
const squared = numbers.map((n) => n * n);
console.log(squared);

// Filter
const evens = numbers.filter((n) => n % 2 === 0);
console.log(evens);

1. Basic Syntax

// Print to the console
console.log("Hello, JavaScript!");

// Simple arithmetic
let x = 5 + 3;
let y = x * 2;
console.log(`The result is: ${y}`);

20. Decorators

function Log(target: any, propertyKey: string) {
console.log(`Property "${propertyKey}" was accessed.`);
}

class Example {
@Log
message: string = "Hello!";
}

const example = new Example();
console.log(example.message);

Asm

6. Hashes

person = { name: "Alice", age: 30, city: "New York" }

# Access values
puts person[:name]

# Add a new key-value pair
person[:country] = "USA"
puts person

19. Channels

use std::sync::mpsc;
use std::thread;

fn main() {
let (tx, rx) = mpsc::channel();

thread::spawn(move || {
tx.send("Hello from thread!").unwrap();
});

let message = rx.recv().unwrap();
println!("{}", message);
}

11. Async/Await

const fetchData = async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 1000);
});
};

(async () => {
console.log("Fetching...");
const data = await fetchData();
console.log(data);
})();

7. Enums

enum Shape {
Circle,
Rectangle,
Triangle,
}

const myShape: Shape = Shape.Circle;
console.log(`Selected shape: ${Shape[myShape]}`);

4. Arrow Functions

const multiply = (a: number, b: number): number => a * b;

console.log(`Product: ${multiply(4, 5)}`);

9. Stack Operations

        AREA STACK_OPS, CODE, READONLY
ENTRY

MOV R0, #10 ; Push R0 onto the stack
PUSH {R0}

MOV R0, #20 ; Push R0 again
PUSH {R0}

POP {R1} ; Pop into R1
POP {R2} ; Pop into R2

END

3. Conditional Execution

        AREA CONDITIONAL, CODE, READONLY
ENTRY

MOV R0, #5 ; Load 5 into R0
CMP R0, #10 ; Compare R0 to 10
BGE greater_equal ; Branch if R0 >= 10
MOV R1, #0 ; R1 = 0 (if less than 10)
B end

greater_equal
MOV R1, #1 ; R1 = 1 (if greater or equal to 10)

end
END

10. String Manipulation

text = "Hello, Ruby!"
puts text.upcase
puts text.downcase
puts text.gsub("Ruby", "World")

8. Classes

class Person
attr_accessor :name, :age

def initialize(name, age)
@name = name
@age = age
end

def greet
"Hi, I'm #{@name} and I'm #{@age} years old."
end
end

alice = Person.new("Alice", 30)
puts alice.greet

13. Error Handling

try {
throw new Error("Something went wrong!");
} catch (error) {
console.log(`Error: ${error.message}`);
}

5. Loops

# For loop
for i in range(1, 6):
print(f"Iteration: {i}")

# While loop
count = 0
while count < 3:
print(f"Count: {count}")
count += 1

1. Basic Syntax

# Print to the console
print("Hello, Python!")

# Simple arithmetic
x = 5 + 3
y = x * 2
print(f"The result is: {y}")

3. Functions

# Define a function
def add(a, b):
return a + b

# Call the function
result = add(3, 5)
print(f"Sum: {result}")

9. Lambda Functions

# Define a lambda function
square = lambda x: x * x

# Call the lambda function
print(f"Square of 4: {square(4)}")

JavaScript

8. Objects

// Define an object
const person = { name: "Alice", age: 30, city: "New York" };

// Access properties
console.log(`Name: ${person.name}`);

// Add a new property
person.country = "USA";
console.log(person);

11. Tuples

let point: [number, number] = [3, 4];
console.log(`Point: (${point[0]}, ${point[1]})`);

6. Lists

# Define a list
fruits = ["Apple", "Banana", "Cherry"]

# Access elements
print(fruits[0])

# Iterate through a list
for fruit in fruits:
print(f"Fruit: {fruit}")

6. Loops

// For loop
for (let i = 1; i <= 5; i++) {
console.log(`Iteration: ${i}`);
}

// While loop
let count = 0;
while (count < 3) {
console.log(`Count: ${count}`);
count++;
}

2. Variables with Types

let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;

console.log(`Name: ${name}, Age: ${age}, Active: ${isActive}`);

16. Regular Expressions

const text = "The quick brown fox";
const pattern = /quick/;

if (pattern.test(text)) {
console.log("Match found!");
}

console.log(text.replace(/fox/, "dog"));

2. Variables

// Immutable variable
const name = "Alice";

// Mutable variable
let age = 30;
age += 1;

console.log(`Name: ${name}, Age: ${age}`);

Typescript

6. Classes

class Person {
name: string;
age: number;

constructor(name: string, age: number) {
this.name = name;
this.age = age;
}

greet(): string {
return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
}
}

const bob = new Person("Bob", 25);
console.log(bob.greet());

1. Basic "Hello World" Program

        AREA RESET, CODE, READONLY
ENTRY

MOV R0, #1 ; File descriptor (stdout)
LDR R1, =msg ; Load address of message into R1
MOV R2, #13 ; Length of message
MOV R7, #4 ; Syscall: write
SWI 0 ; Software interrupt

MOV R7, #1 ; Syscall: exit
SWI 0

msg DCB "Hello, World!", 0xA, 0
END

8. Array Traversal

        AREA ARRAY_TRAVERSAL, CODE, READONLY
ENTRY

LDR R0, =array ; Load base address of array
MOV R1, #0 ; Index = 0

loop
LDR R2, [R0, R1, LSL #2] ; Load array element (4 bytes per element)
ADD R1, R1, #1 ; Index++
CMP R1, #5 ; Check if end of array
BLT loop ; Repeat until done

END

array DCD 1, 2, 3, 4, 5 ; Define an array with 5 elements

7. Bitwise Operations

        AREA BITWISE_OPS, CODE, READONLY
ENTRY

MOV R0, #0b1100 ; Binary: 1100
MOV R1, R0, LSL #1 ; Left shift R0 by 1 -> 11000
MOV R2, R0, LSR #1 ; Right shift R0 by 1 -> 0110
EOR R3, R0, #0b1010 ; XOR R0 with 1010 -> 0110
AND R4, R0, #0b1010 ; AND R0 with 1010 -> 1000
ORR R5, R0, #0b0011 ; OR R0 with 0011 -> 1111

END

14. String Manipulation

const text = "Hello, JavaScript!";
console.log(text.toUpperCase());
console.log(text.toLowerCase());
console.log(text.replace("JavaScript", "World"));

17. Interfaces with Optional Properties

interface User {
id: number;
name: string;
email?: string; // Optional property
}

const user: User = { id: 1, name: "Alice" };
console.log(user);

8. Generics

function identity<T>(value: T): T {
return value;
}

console.log(identity<number>(42));
console.log(identity<string>("Hello"));

1. Basic Syntax

// Print to the console
console.log("Hello, TypeScript!");

// Simple arithmetic
let x: number = 5 + 3;
let y: number = x * 2;
console.log(`The result is: ${y}`);

10. Software Interrupt (SWI) Example

        AREA SWI_EXAMPLE, CODE, READONLY
ENTRY

MOV R7, #1 ; Syscall number for exit (Linux)
MOV R0, #0 ; Exit code = 0
SWI 0 ; Trigger system call

END

4. Arrow Functions

const multiply = (a, b) => a * b;

console.log(`Product: ${multiply(4, 5)}`);

11. Collections (List)

Imports System.Collections.Generic

Module Collections
Sub Main()
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}

' Add an item
numbers.Add(6)

' Iterate through the list
For Each number As Integer In numbers
Console.WriteLine($"Number: {number}")
Next
End Sub
End Module

16. Type Assertions

let value: unknown = "Hello, TypeScript!";
let strLength: number = (value as string).length;

console.log(`String length: ${strLength}`);

3. Functions

// Define a function
function add(a, b) {
return a + b;
}

// Call the function
const result = add(3, 5);
console.log(`Sum: ${result}`);

17. Modules

// math.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

// main.js
import { add, multiply } from "./math.js";

console.log(add(3, 5));
console.log(multiply(4, 5));

12. JSON Handling

const person = { name: "Alice", age: 30 };

// Convert object to JSON
const jsonString = JSON.stringify(person);
console.log(jsonString);

// Convert JSON back to object
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name);

15. Classes

type Person(name: string, age: int) =
member this.Name = name
member this.Age = age
member this.Greet() = printfn "Hi, I'm %s and I'm %d years old." this.Name this.Age

let bob = Person("Bob", 25)
bob.Greet()

19. Fetch API

fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));

15. Extensions

extension Int {
func squared() -> Int {
return self * self
}
}

print("Square of 5: \(5.squared())")

8. Pattern Matching

let describePoint point =
match point with
| (0, 0) -> "Origin"
| (0, _) -> "On the Y-axis"
| (_, 0) -> "On the X-axis"
| _ -> "Elsewhere"

let description = describePoint (3, 0)
printfn "%s" description

15. Modules

// math.ts
export const add = (a: number, b: number): number => a + b;
export const multiply = (a: number, b: number): number => a * b;

// main.ts
import { add, multiply } from "./math";

console.log(add(3, 5));
console.log(multiply(4, 5));

14. Async Programming

open System.Threading.Tasks

let asyncExample () =
async {
do! Async.Sleep 1000
printfn "Hello from async!"
}

Async.Start(asyncExample ())

10. Error Handling

Module ErrorHandling
Sub Main()
Try
Dim result As Integer = 10 \ 0 ' Division by zero
Catch ex As DivideByZeroException
Console.WriteLine("Error: Division by zero!")
Finally
Console.WriteLine("Operation complete.")
End Try
End Sub
End Module

16. Generics

func swapValues<T>(a: inout T, b: inout T) {
let temp = a
a = b
b = temp
}

var x = 5, y = 10
swapValues(a: &x, b: &y)
print("x: \(x), y: \(y)")

12. Events

Public Class Button
Public Event Clicked()

Public Sub SimulateClick()
RaiseEvent Clicked()
End Sub
End Class

Module EventsExample
Sub Main()
Dim btn As New Button()

' Add event handler
AddHandler btn.Clicked, Sub() Console.WriteLine("Button clicked!")
btn.SimulateClick()
End Sub
End Module

13. Promises

function fetchData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve("Data fetched!"), 1000);
});
}

fetchData().then((data) => console.log(data));

2. Vectors

# Create a vector
numbers <- c(1, 2, 3, 4, 5)

# Access elements
print(numbers[1]) # Output: 1

# Perform operations
squared <- numbers^2
print(squared) # Output: 1, 4, 9, 16, 25

19. Codable Protocol

import Foundation

struct Person: Codable {
let name: String
let age: Int
}

let alice = Person(name: "Alice", age: 30)
if let jsonData = try? JSONEncoder().encode(alice),
let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}

6. Arrays

let fruits = ["Apple", "Banana", "Cherry"]
print("First fruit: \(fruits[0])")

for fruit in fruits {
print("Fruit: \(fruit)")
}

5. Lists

// Define a list
let numbers = [1; 2; 3; 4; 5]

// Perform operations
let squared = List.map (fun x -> x * x) numbers
printfn "Squared numbers: %A" squared

let evens = List.filter (fun x -> x % 2 = 0) numbers
printfn "Even numbers: %A" evens

14. String Manipulation

# Concatenate strings
greeting <- paste("Hello", "World", sep = ", ")
print(greeting)

# String length
print(nchar(greeting)) # Output: 12

14. Async/Await

async function fetchData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve("Data fetched!"), 1000);
});
}

(async () => {
console.log("Fetching...");
const data = await fetchData();
console.log(data);
})();

3. Functions

function add(a: number, b: number): number {
return a + b;
}

const result: number = add(3, 5);
console.log(`Sum: ${result}`);

13. Mutable State

let mutable counter = 0

counter <- counter + 1
printfn "Counter: %d" counter

19. Generic Functions

let identity x = x

printfn "Int: %d" (identity 42)
printfn "String: %s" (identity "Hello")

5. Arrays

Module Arrays
Sub Main()
Dim fruits As String() = {"Apple", "Banana", "Cherry"}

' Access elements
Console.WriteLine(fruits(0)) ' Output: Apple

' Iterate through the array
For Each fruit As String In fruits
Console.WriteLine($"Fruit: {fruit}")
Next
End Sub
End Module

18. Regular Expressions

# Match a pattern
text <- "The quick brown fox"
matches <- grepl("quick", text)
print(matches) # Output: TRUE

2. Variables

package main

import "fmt"

func main() {
// Declare variables
var name string = "Alice"
var age int = 30
salary := 45000.5

// Print variables
fmt.Printf("Name: %s, Age: %d, Salary: %.2f\n", name, age, salary)
}

10. Classes and Inheritance

class Animal {
func speak() {
print("Animal sound")
}
}

class Dog: Animal {
override func speak() {
print("Woof!")
}
}

let myDog = Dog()
myDog.speak()

17. Exception Handling

try
let result = 10 / 0
printfn "Result: %d" result
with
| :? System.DivideByZeroException -> printfn "Cannot divide by zero!"

14. LINQ (Query Syntax)

Imports System.Linq

Module LINQExample
Sub Main()
Dim numbers As Integer() = {1, 2, 3, 4, 5, 6}

' Query even numbers
Dim evens = From n In numbers Where n Mod 2 = 0 Select n

For Each number In evens
Console.WriteLine($"Even number: {number}")
Next
End Sub
End Module

3. Functions

func add(a: Int, b: Int) -> Int {
return a + b
}

let result = add(a: 3, b: 5)
print("Sum: \(result)")

2. Variables and Constants

let constantVar = "I cannot change"
var mutableVar = "I can change"
mutableVar = "I've changed!"

print(constantVar)
print(mutableVar)

4. Loops

// For loop
for i in 1 .. 5 do
printfn "Iteration: %d" i

// While loop
let mutable count = 0
while count < 3 do
printfn "Count: %d" count
count <- count + 1

16. Modules

module Math =
let add x y = x + y
let multiply x y = x * y

printfn "Sum: %d" (Math.add 3 5)
printfn "Product: %d" (Math.multiply 3 5)

8. String Manipulation

Module StringManipulation
Sub Main()
Dim text As String = "Hello, VB.NET"
Dim upperText As String = text.ToUpper()
Dim replacedText As String = text.Replace("VB.NET", "World")

Console.WriteLine($"Uppercase: {upperText}")
Console.WriteLine($"Replaced: {replacedText}")
End Sub
End Module

13. Error Handling

# Try-Catch block
result <- tryCatch(
{
10 / 0
},
warning = function(w) {
print("This is a warning")
},
error = function(e) {
print("An error occurred")
}
)
print(result)

4. Data Frames

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

# Access columns
print(df$name) # Output: Alice, Bob

# Filter rows
filtered <- df[df$age > 25, ]
print(filtered)

1. Basic Syntax

# Print to console
print("Hello, R!")

# Basic arithmetic
x <- 5 + 3
y <- x * 2
print(y)

16. Statistical Functions

# Summary statistics
numbers <- c(1, 2, 3, 4, 5)
mean_value <- mean(numbers)
sd_value <- sd(numbers)
print(mean_value) # Output: 3
print(sd_value) # Output: 1.581139

5. Lists

# Create a list
my_list <- list(
name = "Alice",
age = 30,
scores = c(90, 85, 88)
)

# Access elements
print(my_list$name)
print(my_list$scores[2]) # Output: 85

9. Apply Functions

# Use apply on a matrix
matrix_data <- matrix(1:9, nrow = 3)
row_sums <- apply(matrix_data, 1, sum)
print(row_sums)

# Use lapply on a list
numbers <- list(a = 1:5, b = 6:10)
result <- lapply(numbers, sum)
print(result)

17. Slices and Range

package main

import "fmt"

func main() {
numbers := []int{1, 2, 3, 4, 5}

for i, num := range numbers {
fmt.Printf("Index: %d, Value: %d\n", i, num)
}
}

1. Basic Syntax

package main

import "fmt"

func main() {
fmt.Println("Hello, Go!")
}

11. Enumerations

enum Shape {
case circle(radius: Double)
case rectangle(width: Double, height: Double)

func area() -> Double {
switch self {
case .circle(let radius):
return .pi * radius * radius
case .rectangle(let width, let height):
return width * height
}
}
}

let circle = Shape.circle(radius: 5)
print("Circle area: \(circle.area())")

18. Sequences

let numbers = seq { 1 .. 10 }

let squares = numbers |> Seq.map (fun x -> x * x)
printfn "Squares: %A" squares

7. Records

// Define a record type
type Person = { Name: string; Age: int }

// Create a record
let alice = { Name = "Alice"; Age = 30 }
printfn "Name: %s, Age: %d" alice.Name alice.Age

7. Classes and Objects

Public Class Person
Public Name As String
Public Age As Integer

Public Sub Greet()
Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.")
End Sub
End Class

Module Program
Sub Main()
Dim alice As New Person()
alice.Name = "Alice"
alice.Age = 30
alice.Greet()
End Sub
End Module

Visual Basic

6. Functions

Module Functions
Function Square(ByVal x As Integer) As Integer
Return x * x
End Function

Sub Main()
Dim result As Integer = Square(4)
Console.WriteLine($"Square of 4 is: {result}")
End Sub
End Module

10. Maps

package main

import "fmt"

func main() {
// Define a map
person := map[string]int{"Alice": 30, "Bob": 25}

// Access elements
fmt.Println("Alice's age:", person["Alice"])

// Add a new key-value pair
person["Charlie"] = 35
fmt.Println("Updated map:", person)
}

17. Optionals with Nil-Coalescing

let username: String? = nil
let defaultUsername = "Guest"
let currentUsername = username ?? defaultUsername

print("Current username: \(currentUsername)")

F#

1. Basic Syntax

-- Print to console
print("Hello, Lua!")

-- Simple arithmetic
local x = 5 + 3
local y = x * 2
print("Result:", y)

3. Matrices

# Create a matrix
matrix_data <- matrix(1:9, nrow = 3, ncol = 3)
print(matrix_data)

# Access an element
print(matrix_data[1, 2]) # Output: 2

14. Protocols

protocol Greetable {
func greet()
}

class Greeter: Greetable {
func greet() {
print("Hello!")
}
}

let greeter = Greeter()
greeter.greet()

1. Basic Syntax

import Foundation

print("Hello, Swift!")

// Simple arithmetic
let x = 5 + 3
let y = x * 2
print("The result is: \(y)")

Swift

2. Functions

// Define a function
let square x = x * x

// Call the function
let result = square 4
printfn "Square of 4 is: %d" result

9. File Handling

Imports System.IO

Module FileHandling
Sub Main()
' Write to a file
File.WriteAllText("example.txt", "Hello, File!")

' Read from a file
Dim content As String = File.ReadAllText("example.txt")
Console.WriteLine(content)
End Sub
End Module

20. Pipe Operator

# Using the pipe operator
library(dplyr)

result <- mtcars %>%
filter(mpg > 20) %>%
select(mpg, cyl)

print(result)

6. Functions

# Define a function
square <- function(x) {
return(x * x)
}

# Call the function
print(square(4)) # Output: 16

R

19. Packages

# Install and load a package
install.packages("ggplot2")
library(ggplot2)

# Use ggplot for plotting
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
ggtitle("Displacement vs Highway MPG")

6. Tables

-- Create a table
local person = {
name = "Alice",
age = 30
}

-- Access table elements
print("Name:", person.name)
print("Age:", person.age)

-- Add a new key-value pair
person.city = "New York"
print("City:", person.city)

12. Modules

-- Define a module (saved as mymodule.lua)
local M = {}

function M.greet(name)
return "Hello, " .. name
end

return M

-- Use the module
local mymodule = require("mymodule")
print(mymodule.greet("Alice"))

18. Registry Manipulation

# Get registry keys
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion"

# Set a registry key
Set-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Setting" -Value "Enabled"

9. Pointers

package main

import "fmt"

func updateValue(num *int) {
*num = 20
}

func main() {
x := 10
fmt.Println("Before:", x)
updateValue(&x)
fmt.Println("After:", x)
}

9. Option Types

// Safe division using option type
let safeDivide a b =
if b = 0 then None else Some (a / b)

match safeDivide 10 2 with
| Some result -> printfn "Result: %d" result
| None -> printfn "Cannot divide by zero"

12. Higher-Order Functions

// Function that takes another function as a parameter
let applyFunc f x = f x

let doubled = applyFunc (fun x -> x * 2) 5
printfn "Doubled: %d" doubled

15. Scheduled Tasks

# Create a new scheduled task
$action = New-ScheduledTaskAction -Execute "notepad.exe"
$trigger = New-ScheduledTaskTrigger -Daily -At "9:00AM"
Register-ScheduledTask -TaskName "OpenNotepad" -Action $action -Trigger $trigger

# Get a list of tasks
Get-ScheduledTask

4. Arrays and Slices

package main

import "fmt"

func main() {
// Array
var arr [3]int = [3]int{1, 2, 3}
fmt.Println("Array:", arr)

// Slice
slice := []int{4, 5, 6}
slice = append(slice, 7)
fmt.Println("Slice:", slice)
}

13. Channels

package main

import "fmt"

func sendMessage(ch chan string) {
ch <- "Hello, Channel!"
}

func main() {
ch := make(chan string)
go sendMessage(ch)
msg := <-ch
fmt.Println(msg)
}

7. Dictionaries

var person = ["name": "Alice", "age": "30"]
print("Name: \(person["name"]!)")

person["city"] = "New York"
print(person)

9. Structs

struct Person {
let name: String
let age: Int

func greet() {
print("Hi, I'm \(name) and I'm \(age) years old.")
}
}

let alice = Person(name: "Alice", age: 30)
alice.greet()

1. Basic Syntax

' Print a message to the console
Module HelloWorld
Sub Main()
Console.WriteLine("Hello, VB.NET!")
End Sub
End Module

3. Conditional Statements

let age = 25

if age < 18 then
printfn "Minor"
elif age >= 18 && age < 65 then
printfn "Adult"
else
printfn "Senior"

2. Variables and Data Types

Module Variables
Sub Main()
Dim name As String = "Alice"
Dim age As Integer = 30
Dim salary As Double = 45000.5
Dim isActive As Boolean = True

Console.WriteLine($"Name: {name}, Age: {age}, Salary: {salary}, Active: {isActive}")
End Sub
End Module

10. Plotting

# Basic plot
x <- 1:10
y <- x^2
plot(x, y, type = "b", col = "blue", main = "Basic Plot", xlab = "X", ylab = "Y^2")

11. Factors

# Create a factor
gender <- factor(c("Male", "Female", "Male"))
print(gender)

# Levels
print(levels(gender))

12. Reading and Writing Files

# Write a CSV file
write.csv(df, "data.csv", row.names = FALSE)

# Read a CSV file
new_df <- read.csv("data.csv")
print(new_df)

8. Metatables

-- Define a metatable for custom behavior
local myTable = {x = 10, y = 20}
local meta = {
__add = function(a, b)
return {x = a.x + b.x, y = a.y + b.y}
end
}

setmetatable(myTable, meta)

local result = myTable + {x = 5, y = 15}
print("x:", result.x, "y:", result.y)

11. Interfaces

package main

import "fmt"

// Define an interface
type Shape interface {
Area() float64
}

// Define a struct
type Circle struct {
Radius float64
}

// Implement the interface
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}

func main() {
var s Shape = Circle{Radius: 5}
fmt.Printf("Circle Area: %.2f\n", s.Area())
}

8. Optionals

var possibleNumber: Int? = 42
if let number = possibleNumber {
print("Number: \(number)")
} else {
print("No number")
}

4. Conditional Statements

local age = 25

if age < 18 then
print("Minor")
elseif age >= 18 and age < 65 then
print("Adult")
else
print("Senior")
end

4. Conditional Statements

let age = 25

if age < 18 {
print("Minor")
} else if age < 65 {
print("Adult")
} else {
print("Senior")
}

20. LINQ Queries

open System.Linq

let numbers = [| 1; 2; 3; 4; 5 |]

let evenNumbers =
query {
for n in numbers do
where (n % 2 = 0)
select n
}

printfn "Even numbers: %A" evenNumbers

11. Pipelines

let numbers = [1; 2; 3; 4; 5]

let result =
numbers
|> List.map (fun x -> x * x)
|> List.filter (fun x -> x > 10)

printfn "Filtered squares: %A" result

8. Loops

# For loop
for (i in 1:5) {
print(paste("Iteration:", i))
}

# While loop
count <- 0
while (count < 3) {
print(paste("Count:", count))
count <- count + 1
}

9. File Handling

-- Write to a file
local file = io.open("example.txt", "w")
file:write("Hello, File!")
file:close()

-- Read from a file
file = io.open("example.txt", "r")
local content = file:read("*a")
file:close()

print(content)

12. Error Handling

# Try-Catch block
try {
Get-Content non_existent_file.txt
} catch {
Write-Output "An error occurred: $_"
}

5. Conditional Statements

# If-Else statement
$age = 25

if ($age -lt 18) {
Write-Output "Minor"
} elseif ($age -ge 18 -and $age -lt 65) {
Write-Output "Adult"
} else {
Write-Output "Senior"
}

11. Using Cmdlets

# Get a list of running processes
Get-Process

# Stop a specific process
# Stop-Process -Name "notepad"

# Get current directory
Get-Location

1. Basic Syntax

// Print to the console
printfn "Hello, F#!"

// Basic arithmetic
let x = 5 + 3
let y = x * 2
printfn "The result is: %d" y

11. Coroutines

-- Define a coroutine
local co = coroutine.create(function()
for i = 1, 5 do
print("Coroutine:", i)
coroutine.yield()
end
end)

-- Resume the coroutine
while coroutine.status(co) ~= "dead" do
coroutine.resume(co)
end

16. Remote Execution

# Run a command on a remote machine
Invoke-Command -ComputerName "Server01" -ScriptBlock { Get-Process }

# Start a remote session
Enter-PSSession -ComputerName "Server01"

4. Loops

Module Loops
Sub Main()
' For loop
For i As Integer = 1 To 5
Console.WriteLine($"Iteration: {i}")
Next

' While loop
Dim count As Integer = 0
While count < 3
Console.WriteLine($"Count: {count}")
count += 1
End While
End Sub
End Module

14. Error Handling

package main

import (
"errors"
"fmt"
)

func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}

func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}

5. Loops

// For loop
for i in 1...5 {
print("Iteration: \(i)")
}

// While loop
var count = 0
while count < 3 {
print("Count: \(count)")
count += 1
}

13. Inheritance

Public Class Animal
Public Overridable Sub Speak()
Console.WriteLine("Animal sound")
End Sub
End Class

Public Class Dog
Inherits Animal

Public Overrides Sub Speak()
Console.WriteLine("Woof!")
End Sub
End Class

Module Program
Sub Main()
Dim myDog As New Dog()
myDog.Speak() ' Output: Woof!
End Sub
End Module

7. Conditional Statements

# If-Else statement
x <- 10
if (x > 5) {
print("x is greater than 5")
} else {
print("x is 5 or less")
}

Go

18. Lazy Properties

struct Data {
lazy var expensiveCalculation: Int = {
print("Calculating...")
return 42
}()
}

var data = Data()
print("Before accessing")
print("Value: \(data.expensiveCalculation)")

6. Tuples

// Define a tuple
let point = (3, 4)

// Access tuple elements
let x, y = point
printfn "Point: (%d, %d)" x y

10. Discriminated Unions

// Define a union type
type Shape =
| Circle of float
| Rectangle of float * float

// Function to calculate area
let area shape =
match shape with
| Circle radius -> System.Math.PI * radius ** 2.0
| Rectangle (width, height) -> width * height

printfn "Circle area: %f" (area (Circle 5.0))
printfn "Rectangle area: %f" (area (Rectangle (4.0, 6.0)))

3. Conditional Statements

Module Conditionals
Sub Main()
Dim number As Integer = 10

If number > 0 Then
Console.WriteLine("Positive number")
ElseIf number < 0 Then
Console.WriteLine("Negative number")
Else
Console.WriteLine("Zero")
End If
End Sub
End Module

15. Asynchronous Programming

Imports System.Threading.Tasks

Module AsyncExample
Async Function FetchDataAsync() As Task(Of String)
Await Task.Delay(1000) ' Simulate delay
Return "Data fetched!"
End Function

Sub Main()
Dim task As Task(Of String) = FetchDataAsync()
task.Wait()
Console.WriteLine(task.Result)
End Sub
End Module

17. Custom Classes

# Define a custom class
Person <- setClass(
"Person",
slots = list(name = "character", age = "numeric")
)

# Create an object
alice <- Person(name = "Alice", age = 25)
print(alice@name)
print(alice@age)

15. Date and Time

# Get the current date
current_date <- Sys.Date()
print(current_date)

# Format a date
formatted_date <- format(current_date, "%B %d, %Y")
print(formatted_date)

4. Hashtables

# Define a hashtable
$user = @{
Name = "Alice"
Age = 30
City = "New York"
}

# Access values
Write-Output $user["Name"] # Output: Alice

# Add a new key-value pair
$user["Country"] = "USA"
Write-Output $user

1. Basic Syntax

# Output to console
Write-Output "Hello, PowerShell!"

7. Functions

package main

import "fmt"

// Function with parameters and return value
func add(a int, b int) int {
return a + b
}

func main() {
result := add(3, 5)
fmt.Printf("Sum: %d\n", result)
}

17. Iterators

-- Custom iterator
local function counter(max)
local i = 0
return function()
i = i + 1
if i <= max then
return i
end
end
end

for value in counter(5) do
print(value)
end

20. Working with Services

# Get the status of a service
Get-Service -Name "wuauserv"

# Stop a service
Stop-Service -Name "wuauserv"

# Start a service
Start-Service -Name "wuauserv"

20. Concurrency

import Foundation

func fetchData() async -> String {
try? await Task.sleep(nanoseconds: 1_000_000_000) // Simulate delay
return "Data fetched!"
}

Task {
let data = await fetchData()
print(data)
}

13. Error Handling

enum DivisionError: Error {
case divisionByZero
}

func divide(a: Int, b: Int) throws -> Int {
if b == 0 {
throw DivisionError.divisionByZero
}
return a / b
}

do {
let result = try divide(a: 10, b: 0)
print("Result: \(result)")
} catch {
print("Error: \(error)")
}

Lua

10. Error Handling

-- Protected call with pcall
local function riskyFunction()
error("An intentional error!")
end

local status, err = pcall(riskyFunction)
if not status then
print("Error caught:", err)
end

Powershell

16. Debugging

-- Debugging with debug library
local function debugExample()
local x = 10
print(debug.traceback("Stack trace:"))
end

debugExample()

12. Closures

let square = { (x: Int) -> Int in
return x * x
}

print("Square of 4: \(square(4))")

8. Structs

package main

import "fmt"

// Define a struct
type Person struct {
Name string
Age int
}

func main() {
// Create an instance
alice := Person{Name: "Alice", Age: 30}
fmt.Printf("Name: %s, Age: %d\n", alice.Name, alice.Age)
}

6. Conditional Statements

package main

import "fmt"

func main() {
age := 25

if age < 18 {
fmt.Println("Minor")
} else if age >= 18 && age < 65 {
fmt.Println("Adult")
} else {
fmt.Println("Senior")
}
}

17. Modules and Functions

# Create a reusable module
function Add-Numbers {
param (
[int]$a,
[int]$b
)
return $a + $b
}

# Save this function to a .psm1 file for reuse

16. Defer

package main

import "fmt"

func main() {
defer fmt.Println("Deferred message")
fmt.Println("Main function message")
}

19. Running Scripts

# Save a script as script.ps1
# To run it:
.\script.ps1

8. Working with Files

# Write to a file
"Hello, PowerShell!" > example.txt

# Read from a file
$content = Get-Content example.txt
Write-Output $content

7. Functions

# Define a function
function Greet {
param ($name)
Write-Output "Hello, $name!"
}

# Call the function
Greet "Alice"

15. File Handling

package main

import (
"fmt"
"os"
)

func main() {
// Write to a file
file, _ := os.Create("example.txt")
file.WriteString("Hello, File!")
file.Close()

// Read from a file
data, _ := os.ReadFile("example.txt")
fmt.Println(string(data))
}

14. Modules

# Import a module
Import-Module MyModule

# List available modules
Get-Module -ListAvailable

3. Functions

-- Define a function
function greet(name)
return "Hello, " .. name .. "!"
end

-- Call the function
local message = greet("Alice")
print(message)

5. Loops

-- While loop
local count = 1
while count <= 5 do
print("Count:", count)
count = count + 1
end

-- For loop
for i = 1, 5 do
print("Iteration:", i)
end

7. Arrays

-- Define an array
local fruits = {"Apple", "Banana", "Cherry"}

-- Access array elements
print(fruits[1]) -- Lua arrays are 1-based

-- Iterate through an array
for i, fruit in ipairs(fruits) do
print("Fruit " .. i .. ":", fruit)
end

15. Strings

-- String manipulation
local text = "Hello, Lua!"
print("Uppercase:", string.upper(text))
print("Substring:", string.sub(text, 1, 5))
print("Replaced:", string.gsub(text, "Lua", "World"))

6. File Handling

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

# Write to a file
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
print $fh "This is a test file.\n";
close($fh);

# Read from a file
open(my $rfh, '<', 'output.txt') or die "Cannot open file: $!";
while (my $line = <$rfh>) {
print $line;
}
close($rfh);

3. Arrays

# Define an array
$numbers = @(1, 2, 3, 4)

# Access elements
Write-Output $numbers[0] # Output: 1

# Iterate over an array
foreach ($num in $numbers) {
Write-Output "Number: $num"
}

10. Working with JSON

# Convert a hashtable to JSON
$user = @{
Name = "Alice"
Age = 30
}
$json = $user | ConvertTo-Json
Write-Output $json

# Convert JSON back to a hashtable
$userObject = $json | ConvertFrom-Json
Write-Output $userObject.Name # Output: Alice

6. Loops

# For loop
for ($i = 1; $i -le 5; $i++) {
Write-Output "Iteration: $i"
}

# While loop
$count = 0
while ($count -lt 3) {
Write-Output "Count: $count"
$count++
}

2. Variables

# Define variables
$name = "Alice"
$age = 30

# Print variables
Write-Output "Name: $name, Age: $age"

3. Constants

package main

import "fmt"

const Pi = 3.14159

func main() {
fmt.Printf("Value of Pi: %.5f\n", Pi)
}

9. String Manipulation

# String concatenation
$firstName = "Alice"
$lastName = "Smith"
$fullName = "$firstName $lastName"
Write-Output $fullName # Output: Alice Smith

# Replace text
$text = "Hello, World!"
$newText = $text -replace "World", "PowerShell"
Write-Output $newText # Output: Hello, PowerShell!

18. Packages

// mathutils/mathutils.go
package mathutils

func Add(a, b int) int {
return a + b
}

// main.go
package main

import (
"fmt"
"mathutils"
)

func main() {
fmt.Println("Sum:", mathutils.Add(3, 5))
}

5. Loops

package main

import "fmt"

func main() {
// For loop
for i := 1; i <= 5; i++ {
fmt.Println("Iteration:", i)
}

// While-like loop
count := 0
for count < 3 {
fmt.Println("Count:", count)
count++
}
}

9. Typeclasses and Instances

-- Define a typeclass for equality
class Eq (α : Type) where
eq : α → α → Bool

-- Provide an instance for Nat
instance : Eq Nat where
eq x y := x = y

-- Use the instance
#eval Eq.eq 3 3 -- Output: true

14. Using Option and Result

-- Define a safe division function
def safeDiv (a b : Nat) : Option Nat :=
if b = 0 then none else some (a / b)

#eval safeDiv 10 2 -- Output: some 5
#eval safeDiv 10 0 -- Output: none

13. Error Handling with eval

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

eval {
die "An error occurred!";
};
if ($@) {
print "Caught error: $@\n";
}

14. Math Functions

-- Math operations
local x = math.sqrt(16)
local y = math.pi * 2

print("Square root of 16:", x)
print("2 * pi:", y)

2. Variables

-- Global variable
globalVar = "I'm global!"

-- Local variable
local localVar = "I'm local!"

print(globalVar)
print(localVar)

13. Object-Oriented Programming

-- Define a class-like structure
local Person = {}
Person.__index = Person

function Person:new(name, age)
local obj = setmetatable({}, self)
obj.name = name
obj.age = age
return obj
end

function Person:greet()
return "Hi, I'm " .. self.name .. " and I'm " .. self.age .. " years old."
end

-- Create an instance
local alice = Person:new("Alice", 30)
print(alice:greet())

20. Mutex for Synchronization

package main

import (
"fmt"
"sync"
)

var counter int
var mu sync.Mutex

func increment(wg *sync.WaitGroup) {
mu.Lock()
counter++
mu.Unlock()
wg.Done()
}

func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go increment(&wg)
}
wg.Wait()
fmt.Println("Counter:", counter)
}

12. Goroutines

package main

import (
"fmt"
"time"
)

func sayHello() {
fmt.Println("Hello from goroutine!")
}

func main() {
go sayHello()
time.Sleep(time.Second) // Wait for the goroutine to complete
fmt.Println("Main function finished")
}

15. Packages

(defpackage :my-package
(:use :common-lisp)
(:export :greet))

(in-package :my-package)

(defun greet ()
(print "Hello from my-package!"))

(in-package :common-lisp-user)
(my-package:greet) ; Prints: Hello from my-package!

10. Object-Oriented Programming

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

package Person;

sub new {
my ($class, $name, $age) = @_;
my $self = { name => $name, age => $age };
bless $self, $class;
return $self;
}

sub greet {
my $self = shift;
return "Hi, I'm $self->{name} and I'm $self->{age} years old.";
}

package main;

my $person = Person->new("Alice", 30);
print $person->greet() . "\n";

13. Pipelining

# Use a pipeline to filter processes
Get-Process | Where-Object { $_.CPU -gt 100 } | Select-Object -Property Name, CPU

19. JSON Handling

package main

import (
"encoding/json"
"fmt"
)

func main() {
data := `{"name": "Alice", "age": 30}`
var person map[string]interface{}

json.Unmarshal([]byte(data), &person)
fmt.Println(person["name"], person["age"])
}

5. Lists

-- Define a list
numbers :: [Int]
numbers = [1, 2, 3, 4]

-- List operations
sumOfNumbers = sum numbers
doubled = map (*2) numbers

main :: IO ()
main = do
print sumOfNumbers -- Output: 10
print doubled -- Output: [2, 4, 6, 8]

3. Functions

; Define a function
(defun greet (name)
(format t "Hello, ~a!~%" name))

; Call the function
(greet "Alice") ; Prints: Hello, Alice!

2. Defining Variables

(setq x 10)  ; Set x to 10
(setq y (+ x 20)) ; y becomes 30
(print y) ; Prints 30

16. Simple Import and Usage

import Lean.Data.Json

-- Parse JSON
def parseJson : Option Lean.Json :=
Lean.Json.parse "{ \"name\": \"Lean\", \"version\": 4 }"

#eval parseJson

3. Pattern Matching

-- Pattern matching with tuples
describePoint :: (Int, Int) -> String
describePoint (0, 0) = "Origin"
describePoint (0, _) = "On the Y-axis"
describePoint (_, 0) = "On the X-axis"
describePoint _ = "Elsewhere"

main :: IO ()
main = putStrLn (describePoint (3, 0))

11. Inductive Proofs

-- Define natural numbers
inductive MyNat
| zero : MyNat
| succ : MyNat → MyNat

-- Define addition
def add : MyNat → MyNat → MyNat
| MyNat.zero, b => b
| MyNat.succ a, b => MyNat.succ (add a b)

-- Prove addition is commutative
theorem add_comm : ∀ a b : MyNat, add a b = add b a := by
intros a b
induction a with
| zero => rw [add]
| succ a ih => rw [add, ih]

15. Tuples

-- Working with tuples
def pair : Nat × String := (42, "Hello")
#eval pair.1 -- Output: 42
#eval pair.2 -- Output: "Hello"

3. Conditional Statements

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

my $num = 10;

if ($num > 0) {
print "Positive\n";
} elsif ($num < 0) {
print "Negative\n";
} else {
print "Zero\n";
}

8. Higher-Order Functions

-- Using map and filter
incremented = map (+1) [1, 2, 3, 4]
evens = filter even [1, 2, 3, 4]

main :: IO ()
main = do
print incremented -- Output: [2, 3, 4, 5]
print evens -- Output: [2, 4]

11. Typeclasses

-- Define a typeclass
class Describable a where
describe :: a -> String

-- Implement the typeclass for Int
instance Describable Int where
describe x = "This is the number " ++ show x

main :: IO ()
main = putStrLn (describe 42)

8. Using Structure

-- Define a structure
structure Point where
x : Int
y : Int

-- Create an instance
def origin : Point := { x := 0, y := 0 }

-- Access fields
#eval origin.x -- Output: 0

14. Multi-line Strings

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

my $multiline = <<"END";
This is a
multi-line
string in Perl.
END

print $multiline;

13. Defining Classes and Methods

(defclass person ()
((name :initarg :name :accessor person-name)
(age :initarg :age :accessor person-age)))

(defmethod introduce ((p person))
(format t "Hi, I'm ~a and I'm ~a years old.~%" (person-name p) (person-age p)))

; Create an instance and call a method
(setq alice (make-instance 'person :name "Alice" :age 25))
(introduce alice) ; Prints: Hi, I'm Alice and I'm 25 years old.

10. Symbols and Keywords

; Symbols
(setq my-symbol 'hello)
(eq my-symbol 'hello) ; Returns T

; Keywords
(eq :key :key) ; Returns T

6. Recursion

; Recursive function to calculate factorial
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))

(factorial 5) ; Returns 120

16. Threading (Common Lisp)

For multithreading support, you may use Bordeaux-Threads or other libraries:

(require 'bordeaux-threads)

(defun worker ()
(print "Worker is running!"))

(bt:make-thread #'worker) ; Starts a new thread

4. Loops

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

# For loop
for (my $i = 0; $i < 5; $i++) {
print "Iteration $i\n";
}

# While loop
my $count = 0;
while ($count < 3) {
print "Count: $count\n";
$count++;
}

# Foreach loop
my @colors = ("red", "green", "blue");
foreach my $color (@colors) {
print "Color: $color\n";
}

8. Let Bindings

; Local bindings with `let`
(let ((x 5)
(y 10))
(+ x y)) ; Returns 15

2. Inductive Types

-- Define a simple inductive type
inductive Color
| red
| green
| blue

-- Function using the type
def isRed (c : Color) : Bool :=
match c with
| Color.red => true
| _ => false

7. Maybe and Pattern Matching

-- Safe division using Maybe
safeDivide :: Int -> Int -> Maybe Int
safeDivide _ 0 = Nothing
safeDivide a b = Just (a `div` b)

main :: IO ()
main = do
print (safeDivide 10 2) -- Output: Just 5
print (safeDivide 10 0) -- Output: Nothing

12. Monads and do Notation

-- Using Maybe as a Monad
addMaybe :: Maybe Int -> Maybe Int -> Maybe Int
addMaybe mx my = do
x <- mx
y <- my
return (x + y)

main :: IO ()
main = print (addMaybe (Just 3) (Just 5)) -- Output: Just 8

16. Custom Modules

-- MyModule.hs
module MyModule (greet) where

greet :: String -> String
greet name = "Hello, " ++ name ++ "!"

-- Main.hs
import MyModule

main :: IO ()
main = putStrLn (greet "Alice")

7. Proofs with Tactics

-- Prove commutativity of addition
theorem add_comm (a b : Nat) : a + b = b + a := by
rw [Nat.add_comm]

-- Prove associativity of addition
theorem add_assoc (a b c : Nat) : (a + b) + c = a + (b + c) := by
rw [Nat.add_assoc]

4. Pattern Matching

-- Define a function using pattern matching
def sign : Int → String
| n if n > 0 => "positive"
| n if n < 0 => "negative"
| _ => "zero"

-- Test the function
#eval sign 10 -- Output: "positive"

2. Variables

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

# Scalar variable
my $name = "Alice";
my $age = 30;

# Array variable
my @fruits = ("apple", "banana", "cherry");

# Hash variable
my %user = (name => "Bob", age => 25);

print "Name: $name, Age: $age\n";
print "First fruit: $fruits[0]\n";
print "User name: $user{name}\n";

9. Lambda Expressions

-- Lambda function to square a number
square = \x -> x * x

main :: IO ()
main = print (square 5) -- Output: 25

Lean

Perl

MATLAB

% Define and use an anonymous function
square = @(x) x^2;
result = square(5);
disp(['Square of 5: ', num2str(result)]);

11. Using Modules

#!/usr/bin/perl
use strict;
use warnings;
use Math::Complex;

my $result = Math::Complex::sqrt(-4);
print "Square root of -4: $result\n";

9. Macros

; Define a macro
(defmacro unless (condition &body body)
`(if (not ,condition)
(progn ,@body)))

; Use the macro
(unless nil
(print "Condition was false!")) ; Prints: Condition was false!

7. Lists

; Create a list
(setq my-list '(1 2 3 4))

; Access elements
(first my-list) ; Returns 1
(second my-list) ; Returns 2

; Append to a list
(append my-list '(5 6)) ; Returns (1 2 3 4 5 6)

; Map a function over a list
(mapcar #'(lambda (x) (* x x)) my-list) ; Returns (1 4 9 16)

Lisp

MATLAB

% Generate data
x = 0:0.1:10;
y = sin(x);

% Plot the sine wave
figure;
plot(x, y, 'r--', 'LineWidth', 2);
title('Sine Wave');
xlabel('x');
ylabel('sin(x)');
grid on;

Haskell

2. Functions

-- Define a function
square :: Int -> Int
square x = x * x

-- Call the function
result :: Int
result = square 4

12. File Handling

; Write to a file
(with-open-file (stream "output.txt" :direction :output :if-exists :supersede)
(format stream "Hello, File!~%"))

; Read from a file
(with-open-file (stream "output.txt" :direction :input)
(loop for line = (read-line stream nil)
while line do
(print line)))

6. Dependent Types

-- A vector type with length
inductive Vector (α : Type) : Nat → Type
| nil : Vector α 0
| cons : α → Vector α n → Vector α (n + 1)

-- A function operating on vectors
def head {α : Type} {n : Nat} : Vector α (n + 1) → α
| Vector.cons x _ => x

1. Basic Definitions and Theorems

-- Define a simple function
def add (a b : Nat) : Nat :=
a + b

-- Prove a basic theorem
theorem add_comm (a b : Nat) : add a b = add b a :=
Nat.add_comm a b

MATLAB

% Create a cell array
data = {'Alice', 25; 'Bob', 30; 'Charlie', 22};

% Access cell elements
disp(['Name: ', data{1, 1}, ', Age: ', num2str(data{1, 2})]);

% Iterate over a cell array
for i = 1:size(data, 1)
disp(['Name: ', data{i, 1}, ', Age: ', num2str(data{i, 2})]);
end

4. Recursion

-- Recursive factorial function
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)

main :: IO ()
main = print (factorial 5) -- Output: 120

14. Algebraic Data Types

-- Define a binary tree
data Tree a = Empty | Node a (Tree a) (Tree a)

-- Insert an element into the tree
insert :: Ord a => a -> Tree a -> Tree a
insert x Empty = Node x Empty Empty
insert x (Node v left right)
| x < v = Node v (insert x left) right
| otherwise = Node v left (insert x right)

main :: IO ()
main = print (insert 5 (insert 3 (insert 7 Empty)))

13. Inline Lambdas and Anonymous Functions

-- Lambda expression to double a number
def double := fun x : Nat => x * 2

#eval double 4 -- Output: 8

14. Multiple Documents

---
environment: development
debug: true
---
environment: production
debug: false

4. Mixed Lists and Dictionaries

employees:
- name: Bob
position: Manager
- name: Carol
position: Developer
- name: Eve
position: Designer

13. Lazy Evaluation

-- Infinite list of numbers
numbers = [1..]

-- Take the first 5 numbers
main :: IO ()
main = print (take 5 numbers) -- Output: [1, 2, 3, 4, 5]

12. Command-Line Arguments

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

my $num_args = @ARGV;

if ($num_args < 1) {
print "Usage: $0 <arguments>\n";
exit;
}

foreach my $arg (@ARGV) {
print "Argument: $arg\n";
}

MATLAB

% Save this as a script (mainScript.m)

% Call an external function
result = factorialOfNumber(5);
disp(['Factorial of 5: ', num2str(result)]);

% External function (save this as factorialOfNumber.m)
function y = factorialOfNumber(n)
y = 1;
for i = 1:n
y = y * i;
end
end

Bash

#!/bin/bash

# Define a function
greet() {
local name=$1
echo "Hello, $name!"
}

# Call the function
greet "Alice"
greet "Bob"

Bash

#!/bin/bash

# Check if a number is positive or negative
num=-5

if [ $num -gt 0 ]; then
echo "Positive number"
elif [ $num -lt 0 ]; then
echo "Negative number"
else
echo "Zero"
fi

Bash

#!/bin/bash

# Declare variables
name="Alice"
age=25

# Print variables
echo "Name: $name"
echo "Age: $age"

Bash

#!/bin/bash

# Run a process in the background
sleep 10 &
process_id=$!

# Show the process ID
echo "Background process ID: $process_id"

# Wait for the process to finish
wait $process_id
echo "Process completed!"

11. References and Anchors in Nested Structures

server: &server_defaults
host: localhost
port: 8080

environments:
development:
<<: *server_defaults
debug: true
production:
<<: *server_defaults
debug: false
port: 80

9. Tags

custom_types:
timestamp: !!timestamp "2023-10-25T10:30:00Z"
binary_data: !!binary |
VGhpcyBpcyBhIHRlc3Qgc3RyaW5nLg==
integer_as_string: !!str 42

14. Property Lists

(setq my-plist '(:name "Alice" :age 30))

; Access properties
(getf my-plist :name) ; Returns "Alice"
(getf my-plist :age) ; Returns 30

12. Using Lean.Meta (Metaprogramming)

import Lean.Meta

-- Define a simple meta-program
def printGoal : MetaM Unit := do
let goal ← Lean.Meta.getMainGoal
IO.println s!"Current goal: {goal}"

-- Use the meta-program in a tactic
example (n : Nat) : n = n := by
printGoal
rfl

7. Regular Expressions

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

my $text = "The quick brown fox";

if ($text =~ /quick/) {
print "Match found!\n";
}

$text =~ s/fox/dog/;
print "Updated text: $text\n";

9. Hashes

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

my %person = (name => "Alice", age => 25, city => "New York");

# Access hash values
print "Name: $person{name}\n";

# Iterate through hash
while (my ($key, $value) = each %person) {
print "$key: $value\n";
}

4. Conditionals

; Using `if`
(defun positive-or-negative (x)
(if (> x 0)
"Positive"
"Negative or Zero"))

(positive-or-negative 10) ; Returns "Positive"
(positive-or-negative -5) ; Returns "Negative or Zero"

Matlab

6. Multiline Strings

description: >
This is a long description
that spans multiple lines.

note: |
This is a block literal.
Line breaks are preserved here.

1. Basic Syntax

-- Simple arithmetic
x = 5 + 3
y = x * 2

-- Print a value
main :: IO ()
main = putStrLn ("The result is: " ++ show y)

1. Basic Syntax

; Basic arithmetic
(+ 1 2 3) ; Addition
(* 2 3 4) ; Multiplication
(- 10 3 2) ; Subtraction

11. Error Handling

; Catch and handle errors
(handler-case
(/ 1 0) ; Division by zero
(division-by-zero ()
(print "Cannot divide by zero!")))

Square of sum

-- Define a function to compute the square of a number
def square (x : ℕ) : ℕ :=
x * x

-- Prove that the square of a sum follows the formula (a + b)^2 = a^2 + 2ab + b^2
theorem square_of_sum (a b : ℕ) : square (a + b) = square a + 2 * a * b + square b := by
calc
square (a + b) = (a + b) * (a + b) := rfl
_ = a * a + 2 * a * b + b * b := by ring

-- Example usage: Evaluate the square of a number
#eval square 5 -- Output: 25

-- Example usage: Evaluate the square of a sum
#eval square (3 + 4) -- Output: 49

10. Higher-Order Functions

-- Define a function that takes another function
def applyTwice (f : Nat → Nat) (x : Nat) : Nat :=
f (f x)

-- Example usage
#eval applyTwice (fun x => x + 2) 3 -- Output: 7

5. Lists and Operations

-- Create a list and map over it
def nums : List Nat := [1, 2, 3, 4]

-- Map a function over the list
def squares : List Nat := nums.map (fun x => x * x)

#eval squares -- Output: [1, 4, 9, 16]

8. Working with Arrays

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

my @numbers = (1, 2, 3, 4, 5);

# Access elements
print "First number: $numbers[0]\n";

# Iterate through array
foreach my $num (@numbers) {
print "Number: $num\n";
}

# Push and pop
push @numbers, 6;
my $last = pop @numbers;
print "Last number: $last\n";

MATLAB

% For loop
for i = 1:5
disp(['Iteration: ', num2str(i)]);
end

% While loop
count = 0;
while count < 5
disp(['Count: ', num2str(count)]);
count = count + 1;
end

15. IO Operations

-- Reading and writing to a file
main :: IO ()
main = do
writeFile "example.txt" "Hello, Haskell!"
content <- readFile "example.txt"
putStrLn content

15. YAML with Multiline Flow Style

users: [
{name: Alice, age: 25},
{name: Bob, age: 30},
{name: Charlie, age: 35}
]

10. Data Types

-- Define a custom data type
data Shape = Circle Float | Rectangle Float Float

-- Function to calculate area
area :: Shape -> Float
area (Circle r) = pi * r * r
area (Rectangle w h) = w * h

main :: IO ()
main = do
print (area (Circle 5)) -- Output: 78.53982
print (area (Rectangle 4 6)) -- Output: 24.0

6. Tuples

-- Define and access tuples
point :: (Int, Int)
point = (3, 4)

x = fst point
y = snd point

main :: IO ()
main = print (x, y) -- Output: (3, 4)

3. Recursive Functions

-- Define a factorial function
def factorial : Nat → Nat
| 0 => 1
| n + 1 => (n + 1) * factorial n

-- Evaluate the factorial of 5
#eval factorial 5 -- Output: 120

12. Documents with Explicit Start/End

---
app_name: ExampleApp
version: 1.0.0
dependencies:
- name: lib1
version: 2.1.0
- name: lib2
version: 3.3.7
...

5. Loops

; Using `loop`
(loop for i from 1 to 5 do
(print i)) ; Prints numbers 1 through 5

; Collecting results with `loop`
(loop for i from 1 to 5
collect (* i i)) ; Returns: (1 4 9 16 25)

1. Basic Perl Script

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

print "Hello, World!\n";

Bash

#!/bin/bash

# Declare an array
fruits=("Apple" "Banana" "Cherry")

# Access elements
echo "First fruit: ${fruits[0]}"

# Iterate over an array
for fruit in "${fruits[@]}"; do
echo "$fruit"
done

Bash

Bash

#!/bin/bash

# Prompt the user for input
read -p "Enter your name: " user_name
echo "Welcome, $user_name!"

Bash

#!/bin/bash

# Create a file and write to it
echo "Hello, File!" > myfile.txt

# Append to a file
echo "Appending a line." >> myfile.txt

# Read from a file
while read -r line; do
echo "Read line: $line"
done < myfile.txt

15. System Commands

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

# Run a system command
my $output = `ls -l`;
print "Command output:\n$output\n";

YAML

5. Functions

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

# Define a function
sub greet {
my ($name) = @_;
return "Hello, $name!";
}

# Call the function
my $message = greet("Alice");
print "$message\n";

MATLAB

% Variables and arithmetic operations
a = 5;
b = 3;
c = a + b; % Addition
d = a * b; % Multiplication
e = a^2; % Power

% Display results
disp(['Sum: ', num2str(c)]);
disp(['Product: ', num2str(d)]);
disp(['Square: ', num2str(e)]);

MATLAB

% Creating matrices
A = [1, 2; 3, 4];
B = [5, 6; 7, 8];

% Matrix addition, multiplication, and transpose
C = A + B;
D = A * B;
E = A';

disp('Matrix A:');
disp(A);
disp('Matrix B:');
disp(B);
disp('A + B:');
disp(C);
disp('A * B:');
disp(D);
disp('Transpose of A:');
disp(E);

8. Anchors and Aliases

defaults: &default_settings
log_level: debug
timeout: 30

development:
<<: *default_settings
debug_mode: true

production:
<<: *default_settings
log_level: error

MATLAB

% Define and use a function
function y = squareNumber(x)
y = x^2;
end

% Call the function
result = squareNumber(4);
disp(['Square of 4: ', num2str(result)]);

MATLAB

x = 10;

if x > 0
disp('x is positive');
elseif x == 0
disp('x is zero');
else
disp('x is negative');
end

7. Scalars with Different Data Types

boolean_value: true
integer_value: 42
float_value: 3.14
null_value: null

5. Inline Lists and Dictionaries

colors: [red, green, blue]
dimensions: {width: 1920, height: 1080}

Bash

#!/bin/bash

# For loop
for i in {1..5}; do
echo "Iteration $i"
done

# While loop
count=0
while [ $count -lt 5 ]; do
echo "Count: $count"
((count++))
done

10. Complex Keys

? [first_key, second_key]
: value for complex key

? |
Multiline
Key
: Multiline Value

Bash

#!/bin/bash

text="Hello, Bash Scripting!"

# Get substring
echo "Substring: ${text:7:4}"

# Replace a word
new_text=${text/Bash/Shell}
echo "Replaced: $new_text"

Bash

#!/bin/bash

# Get the current date and time
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "Current time: $current_time"

Bash

#!/bin/bash

# Declare an associative array
declare -A user_info
user_info[name]="Alice"
user_info[age]=30

# Access and iterate over the array
echo "Name: ${user_info[name]}"
echo "Age: ${user_info[age]}"

for key in "${!user_info[@]}"; do
echo "$key: ${user_info[$key]}"
done

1. Basic Key-Value Pairs

name: John Doe
age: 30
email: johndoe@example.com

2. Nested Structures

person:
name: Alice
address:
street: 123 Main St
city: Springfield
zip: 12345

13. YAML with Comments

# This is a comment explaining the file
database:
host: localhost # The database server
port: 5432 # Default PostgreSQL port
username: admin # Database username
password: secret # Database password

3. Lists

shopping_list:
- apples
- bananas
- oranges

1. Basic Syntax

(* Simple arithmetic *)
let x = 5 + 3
let y = x * 2

(* Print a value *)
print_endline ("The result is: " ^ string_of_int y)

9. Variants

(* Define a variant type *)
type shape =
| Circle of float
| Rectangle of float * float

(* Function to calculate area *)
let area = function
| Circle radius -> 3.14 *. radius ** 2.0
| Rectangle (width, height) -> width *. height

let () =
Printf.printf "Circle area: %.2f\n" (area (Circle 5.0));
Printf.printf "Rectangle area: %.2f\n" (area (Rectangle (4.0, 6.0)))

11. Defining Operators

% Define a new operator
:- op(500, xfx, 'is_related_to').

% Facts using the operator
john is_related_to mary.
mary is_related_to alice.

% Query: Who is related to Alice?
% ?- X is_related_to alice.

2. Functions

(* Define a function *)
let square x = x * x

(* Call the function *)
let result = square 4
let () = Printf.printf "Square of 4 is: %d\n" result

4. Lists

% Facts about lists
member(X, [X|_]).
member(X, [_|Tail]) :- member(X, Tail).

% Query: Is 3 in the list?
% ?- member(3, [1, 2, 3, 4]).

7. Pattern Matching

% Facts
person(john, male).
person(mary, female).

% Query: Who is a male?
% ?- person(X, male).

2. Nested Elements with Attributes

<library>
<book id="1" genre="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
<book id="2" genre="non-fiction">
<title>A Brief History of Time</title>
<author>Stephen Hawking</author>
<year>1988</year>
</book>
</library>

3. XML with Namespaces

<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://example.com/catalog" xmlns:media="http://example.com/media">
<book>
<title>1984</title>
<author>George Orwell</author>
</book>
<media:movie>
<title>Inception</title>
<director>Christopher Nolan</director>
</media:movie>
</catalog>

11. Config File Example

<?xml version="1.0" encoding="UTF-8"?>
<config>
<database>
<host>localhost</host>
<port>3306</port>
<username>root</username>
<password>password</password>
</database>
<application>
<name>SampleApp</name>
<version>1.0.0</version>
<log-level>debug</log-level>
</application>
</config>

1. Basic XML Structure

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Alice</to>
<from>Bob</from>
<message>Hello, XML World!</message>
<sent date="2024-01-01" time="10:00:00"/>
</note>

12. Higher-Order Functions

(* Map function *)
let increment x = x + 1
let incremented_list = List.map increment [1; 2; 3; 4]

let () =
Printf.printf "Incremented list: [%s]\n"
(String.concat "; " (List.map string_of_int incremented_list))

7. Namespaces

(ns my-app.core)

(defn say-hello []
(println "Hello from my-app.core!"))

(say-hello)

3. Reagent Example

(ns app.components
(:require [reagent.core :as r]))

(defn counter []
(let [count (r/atom 0)]
(fn []
[:div
[:h1 "Counter: " @count]
[:button {:on-click #(swap! count inc)} "Increment"]])))

3. Variables and Anonymous Variables

% Facts
likes(john, pizza).
likes(john, pasta).
likes(mary, pizza).

% Query: What does John like?
% ?- likes(john, X).

% Query: Who likes pizza?
% ?- likes(_, pizza).

12. Complex Example with Deep Nesting

<?xml version="1.0" encoding="UTF-8"?>
<organization>
<department name="Engineering">
<team name="Backend">
<member role="Lead">Alice</member>
<member role="Developer">Bob</member>
</team>
<team name="Frontend">
<member role="Lead">Charlie</member>
<member role="Developer">Dana</member>
</team>
</department>
<department name="Marketing">
<team name="Social Media">
<member role="Manager">Eve</member>
</team>
</department>
</organization>

8. Records

(* Define a record *)
type person = {
name : string;
age : int;
}

(* Create a record *)
let alice = { name = "Alice"; age = 30 }

(* Access record fields *)
let () =
Printf.printf "Name: %s, Age: %d\n" alice.name alice.age

15. Mutable State

(* Use ref for mutable state *)
let counter = ref 0

let () =
counter := !counter + 1;
Printf.printf "Counter: %d\n" !counter

3. Higher-Order Functions

;; Using map
(defn square [x]
(* x x))

(map square [1 2 3 4]) ;; (1 4 9 16)

;; Using filter
(filter odd? [1 2 3 4]) ;; (1 3)

1. Basic Syntax

;; A simple function
(defn greet [name]
(str "Hello, " name "!"))

;; Call the function
(greet "Alice")

9. Backtracking

% Facts
color(red).
color(blue).
color(green).

% Query: Generate all colors
% ?- color(X).

2. Rules

% Rules
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).

% Query: Who are Alice's grandparents?
% ?- grandparent(X, alice).

16. Meta-Predicates

% Meta-predicate example
apply_twice(Predicate, Arg) :-
call(Predicate, Arg),
call(Predicate, Arg).

% Query: Apply write/1 twice
% ?- apply_twice(write, 'Hello!').

12. Using Cuts

% Cut example
max(A, B, A) :- A >= B, !.
max(_, B, B).

% Query: What is the maximum of 3 and 7?
% ?- max(3, 7, Result).

4. Comments and Processing Instructions

<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a comment explaining the purpose of this XML -->
<data>
<?php echo "This is a PHP processing instruction"; ?>
<item>Sample item</item>
</data>

4. CSS Variables

:root {
--primary-color: #ff5722;
--secondary-color: #795548;
--font-size: 16px;
}

body {
font-size: var(--font-size);
color: var(--primary-color);
}

button {
background-color: var(--secondary-color);
color: white;
}

9. Custom Fonts and Shadows

/* Import a Google Font */
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

body {
font-family: 'Roboto', sans-serif;
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
}

h1 {
text-shadow: 3px 3px 10px #999;
}

4. Adding Metadata with Labels

# Base image
FROM python:3.9

# Add metadata
LABEL maintainer="example@example.com"
LABEL version="1.0"
LABEL description="A simple Python application"

# Install dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy application files
COPY . /app

# Set the working directory and entrypoint
WORKDIR /app
ENTRYPOINT ["python", "app.py"]

10. Dockerfile with Comments

# Use a lightweight base image
FROM alpine:3.15

# Update and install dependencies
RUN apk add --no-cache \
curl \
bash

# Add metadata
LABEL maintainer="example@example.com"

# Expose a port
EXPOSE 8080

# Set a default command
CMD ["sh"]

1. Basic Dockerfile

# Use a base image
FROM ubuntu:20.04

# Set a working directory
WORKDIR /app

# Copy files into the container
COPY . /app

# Run a command to install dependencies
RUN apt-get update && apt-get install -y \
curl \
git \
vim

# Default command
CMD ["echo", "Hello, Docker!"]

4. Recursion

(defn factorial [n]
(if (<= n 1)
1
(* n (factorial (dec n)))))

(factorial 5) ;; 120

6. Self-Closing Tags

<?xml version="1.0" encoding="UTF-8"?>
<image-gallery>
<image src="image1.jpg" alt="A beautiful sunrise" />
<image src="image2.jpg" alt="A serene landscape" />
</image-gallery>

8. Using ENTRYPOINT and CMD

# Base image
FROM alpine:latest

# Copy script
COPY entrypoint.sh /usr/local/bin/

# Make the script executable
RUN chmod +x /usr/local/bin/entrypoint.sh

# Set entrypoint and default command
ENTRYPOINT ["entrypoint.sh"]
CMD ["default-arg"]

1. Basic Syntax

(ns app.core
(:require ["dart:io" :as io]))

(defn main []
(io/print "Hello from ClojureDart!"))

XML/HTML

6. Tuples

(* Define a tuple *)
let point = (3, 4)

(* Access tuple elements *)
let x = fst point
let y = snd point

let () = Printf.printf "Point: (%d, %d)\n" x y

14. Lazy Evaluation

(* Define a lazy value *)
let lazy_value = lazy (2 + 2)

let () =
Printf.printf "Value: %d\n" (Lazy.force lazy_value)

1. Basic Syntax

(ns app.core)

;; Print to the browser console
(js/console.log "Hello, ClojureScript!")

19. Unification

% Unification
same(X, X).

% Query: Are 3 and 3 the same?
% ?- same(3, 3).

18. Sorting

% Sort a list
sort_list(Unsorted, Sorted) :- msort(Unsorted, Sorted).

% Query: Sort [3, 1, 2, 4]
% ?- sort_list([3, 1, 2, 4], Result).

7. Grid and Flexbox Layout

/* Grid container */
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}

.grid-item {
background-color: #007bff;
color: white;
text-align: center;
padding: 20px;
}

/* Flexbox container */
.flex-container {
display: flex;
justify-content: space-between;
align-items: center;
}

.flex-item {
padding: 10px;
background-color: #17a2b8;
color: white;
}

JSON

{
"id": "chatcmpl-t1bu330d4hn6x1ll0sh6uh",
"object": "chat.completion",
"created": 1732474408,
"model": "llama-3.2-3b-instruct",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{\"joke\":\"A man walked into a library and asked the librarian, \"}"
},
"logprobs": null,
"something": true,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 47,
"completion_tokens": 19,
"total_tokens": 66
},
"system_fingerprint": "llama-3.2-3b-instruct"
}

3. Pattern Matching

(* Pattern matching with tuples *)
let describe_point (x, y) =
match (x, y) with
| (0, 0) -> "Origin"
| (0, _) -> "On the Y-axis"
| (_, 0) -> "On the X-axis"
| _ -> "Elsewhere"

let description = describe_point (3, 0)
let () = print_endline description

1. Facts and Queries

% Facts
parent(john, mary).
parent(mary, alice).

% Query: Who are Mary's parents?
% ?- parent(X, mary).

Example HTML Document

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Syntax Highlighting Test</title>
<!-- Inline CSS -->
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
.container {
margin: 20px auto;
padding: 20px;
max-width: 600px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 8px;
}
.highlight {
color: #d9534f;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1 style="text-align: center; color: #5bc0de;">Welcome to the Syntax Test</h1>
<p>This is a sample <span class="highlight">HTML</span> document.</p>

<!-- Nested list -->
<ul>
<li>Point 1</li>
<li>Point 2
<ul>
<li>Subpoint 2.1</li>
<li>Subpoint 2.2</li>
</ul>
</li>
<li>Point 3</li>
</ul>

<!-- Form example -->
<form id="testForm" onsubmit="return validateForm();">
<label for="username">Username:</label>
<input type="text" id="username" name="username" style="margin-bottom: 10px;">
<button type="submit" style="background-color: #5cb85c; color: white;">Submit</button>
</form>

<!-- Table -->
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<thead>
<tr style="background-color: #d9edf7;">
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alice</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
<td>Los Angeles</td>
</tr>
</tbody>
</table>
</div>

<!-- Inline JavaScript -->
<script>
function validateForm() {
const username = document.getElementById("username").value;
if (!username) {
alert("Username cannot be empty!");
return false;
}
alert("Form submitted successfully!");
return true;
}

// Example of DOM manipulation
document.addEventListener("DOMContentLoaded", () => {
const highlight = document.querySelector(".highlight");
highlight.style.backgroundColor = "#f9e79f";
});
</script>
</body>
</html>

3. Dart Interop

(ns app.dart-interop
(:require ["dart:math" :as math]))

(defn random-number []
(let [rand (math/Random.)]
(.nextInt rand 100))) ;; Generates a random number between 0 and 99

Clojure

2. Interoperability with JavaScript

;; Calling a JavaScript function
(.log js/console "This is JavaScript interop")

;; Accessing object properties
(defn get-element-by-id [id]
(.getElementById js/document id))

Prolog

14. Dynamic Predicates

% Declare dynamic predicate
:- dynamic fact/1.

% Add a fact
add_fact(X) :- assertz(fact(X)).

% Query: Add and verify a fact
% ?- add_fact(new_fact), fact(new_fact).

Dockerfile

Ocaml

5. CDATA Section

<?xml version="1.0" encoding="UTF-8"?>
<code>
<![CDATA[
<script>
console.log("This is raw JavaScript inside CDATA");
</script>
]]>
</code>

5. Arithmetic Operations

% Arithmetic
add(A, B, Sum) :- Sum is A + B.
multiply(A, B, Product) :- Product is A * B.

% Query: What is the sum of 5 and 7?
% ?- add(5, 7, Result).

7. XML with Mixed Content

<?xml version="1.0" encoding="UTF-8"?>
<article>
<title>Learning XML</title>
<content>
XML is a <strong>markup language</strong> used to store and transport data.
</content>
</article>

12. Running Shell Commands

# Use base image
FROM ubuntu:20.04

# Run multiple shell commands
RUN apt-get update && \
apt-get install -y curl && \
curl -fsSL https://example.com/install.sh | bash

10. Logic Operations

% Logical conjunction (and)
adult(X) :- age(X, Y), Y >= 18.

% Logical disjunction (or)
happy(X) :- rich(X); healthy(X).

% Query: Who is an adult?
% ?- adult(john).

% Query: Who is happy?
% ?- happy(jane).

2. Pseudo-classes and Pseudo-elements

/* Hover and focus pseudo-classes */
button:hover {
background-color: #0056b3;
color: white;
}

input:focus {
outline: 2px solid #80bdff;
}

/* First-child and before pseudo-elements */
ul li:first-child {
font-weight: bold;
}

blockquote::before {
content: "“";
font-size: 24px;
color: #ccc;
}

CSS

10. Clipping and Masking

/* Clipping an element */
.clip-circle {
width: 100px;
height: 100px;
background-color: #28a745;
clip-path: circle(50%);
}

/* Masking an image */
.image-mask {
width: 200px;
height: 200px;
background-image: url('example.jpg');
mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
-webkit-mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
}

1. Basic Selectors and Properties

/* Basic element, class, and ID selectors */
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}

.container {
max-width: 800px;
margin: 20px auto;
padding: 15px;
border: 1px solid #ccc;
}

#header {
background-color: #007bff;
color: white;
text-align: center;
padding: 10px;
}

5. Using ARG for Build-Time Variables

# Base image
FROM nginx:alpine

# Define build arguments
ARG APP_VERSION=latest
ARG CONFIG_PATH=/etc/nginx/conf.d/

# Use build arguments
LABEL app.version="$APP_VERSION"
COPY ./nginx.conf "$CONFIG_PATH"

# Expose the web server port
EXPOSE 80

7. Healthcheck Example

# Base image
FROM mysql:8.0

# Set environment variables
ENV MYSQL_ROOT_PASSWORD=rootpassword

# Add a healthcheck
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD mysqladmin ping -h localhost || exit 1

# Expose the database port
EXPOSE 3306

4. Recursive Functions

(* Factorial using recursion *)
let rec factorial n =
if n <= 1 then 1 else n * factorial (n - 1)

let () = Printf.printf "Factorial of 5 is: %d\n" (factorial 5)

13. Exceptions

(* Define and raise an exception *)
exception Division_by_zero

let safe_divide a b =
if b = 0 then raise Division_by_zero else a / b

let () =
try
let result = safe_divide 10 0 in
Printf.printf "Result: %d\n" result
with Division_by_zero ->
print_endline "Cannot divide by zero"

4. Async Example with go Blocks

(ns app.async
(:require [cljs.core.async :refer [go <!]]))

(defn fetch-data []
(go
(let [response (<! (js/fetch "/api/data"))]
(js/console.log "Data fetched:" response))))

15. File Handling

% Writing to a file
write_to_file(Filename, Text) :-
open(Filename, write, Stream),
write(Stream, Text),
close(Stream).

% Query: Write 'Hello, Prolog!' to a file
% ?- write_to_file('output.txt', 'Hello, Prolog!').

10. Large Dataset Example

<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="101">
<name>Jane Doe</name>
<position>Software Engineer</position>
<salary>90000</salary>
</employee>
<employee id="102">
<name>John Smith</name>
<position>Data Scientist</position>
<salary>95000</salary>
</employee>
<employee id="103">
<name>Emily Davis</name>
<position>Product Manager</position>
<salary>105000</salary>
</employee>
</employees>

8. String and Atom Operations

% String operations
concatenate(Str1, Str2, Result) :- atom_concat(Str1, Str2, Result).

% Query: Concatenate 'hello' and 'world'
% ?- concatenate('hello', 'world', Result).

3. Multi-Stage Build

# Stage 1: Build
FROM maven:3.8.6-openjdk-11 AS builder
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn package -DskipTests

# Stage 2: Runtime
FROM openjdk:11-jre-slim
WORKDIR /app
COPY --from=builder /app/target/myapp.jar .
CMD ["java", "-jar", "myapp.jar"]

11. Polymorphism

(* A polymorphic function *)
let identity x = x

let () =
let int_result = identity 42 in
let string_result = identity "Hello" in
Printf.printf "Int: %d, String: %s\n" int_result string_result

10. Modules

(* Define a module *)
module Math = struct
let add x y = x + y
let multiply x y = x * y
end

(* Use the module *)
let () =
let sum = Math.add 3 5 in
let product = Math.multiply 3 5 in
Printf.printf "Sum: %d, Product: %d\n" sum product

8. XML with DTD (Document Type Definition)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE greeting [
<!ELEMENT greeting (#PCDATA)>
]>
<greeting>Hello, World!</greeting>

15. Using SHELL Instruction

# Base image
FROM alpine:latest

# Change shell to Bash
SHELL ["/bin/bash", "-c"]

# Run a Bash script
RUN echo "Hello from Bash!"

6. Onbuild Triggers

# Base image
FROM node:16 AS base

# Add ONBUILD instructions
ONBUILD COPY . /app
ONBUILD RUN npm install
ONBUILD CMD ["node", "index.js"]

6. Threading Macros

(->> [1 2 3 4]
(filter odd?)
(map #(* % %))) ;; (1 9)

(-> {:a 1 :b 2}
(assoc :c 3)
(dissoc :a)) ;; {:b 2, :c 3}

2. Data Structures

;; Vectors
(def my-vector [1 2 3 4])

;; Maps
(def my-map {:name "Alice" :age 30})

;; Sets
(def my-set #{1 2 3 4})

;; Lists
(def my-list '(1 2 3 4))

2. Flutter App Example

(ns app.flutter
(:require ["package:flutter/material.dart" :as flutter]))

(defn my-app []
(flutter/createStatelessWidget
{:build
(fn [_]
(flutter/Scaffold
{:appBar (flutter/AppBar {:title (flutter/Text "ClojureDart Example")})
:body (flutter/Center {:child (flutter/Text "Hello, Flutter!")})}))}))

13. Fail Predicate

% Print all numbers from 1 to 5
print_numbers(5) :- write(5), nl.
print_numbers(N) :-
N < 5,
write(N), nl,
N1 is N + 1,
print_numbers(N1).

% Query: Start printing numbers
% ?- print_numbers(1).

6. Recursion

% Factorial
factorial(0, 1).
factorial(N, F) :-
N > 0,
N1 is N - 1,
factorial(N1, F1),
F is N * F1.

% Query: What is the factorial of 5?
% ?- factorial(5, Result).

9. XML with Schema

<?xml version="1.0" encoding="UTF-8"?>
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="person.xsd">
<name>John Doe</name>
<age>30</age>
<email>johndoe@example.com</email>
</person>

6. Keyframes and Animations

/* Define animation keyframes */
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}

/* Apply animation to an element */
.alert {
animation: fadeIn 2s ease-in-out;
background-color: #ffcccb;
padding: 15px;
border: 1px solid #ff0000;
}

JSON

9. Using Volumes

# Base image
FROM nginx:latest

# Set a volume for persistent data
VOLUME ["/var/cache/nginx", "/var/log/nginx"]

# Copy configuration file
COPY nginx.conf /etc/nginx/nginx.conf

5. Macros

(defmacro unless [condition & body]
`(if (not ~condition)
(do ~@body)))

(unless false
(println "Condition is false!"))

11. COPY vs ADD

# Use base image
FROM debian:buster

# Copy files
COPY myapp /usr/local/myapp

# Add files (supports extracting archives)
ADD myapp.tar.gz /usr/local/myapp

13. Multi-Architecture Dockerfile

# Base image
FROM --platform=$TARGETPLATFORM debian:buster

# Set environment variables
ENV APP_ENV=production

# Run platform-specific commands
RUN if [ "$(uname -m)" = "x86_64" ]; then \
echo "Building for x86_64"; \
else \
echo "Building for ARM"; \
fi

5. Lists

(* Define a list *)
let numbers = [1; 2; 3; 4]

(* List operations *)
let sum = List.fold_left (+) 0 numbers
let doubled = List.map (fun x -> x * 2) numbers

let () =
Printf.printf "Sum: %d\n" sum;
Printf.printf "Doubled: [%s]\n"
(String.concat "; " (List.map string_of_int doubled))

17. Negation

% Negation
not_member(_, []).
not_member(X, [Y|Tail]) :-
X \= Y,
not_member(X, Tail).

% Query: Check if 3 is not in the list
% ?- not_member(3, [1, 2, 4]).

8. Transition and Transform

/* Button with transition and transform */
button {
transition: background-color 0.3s ease, transform 0.3s ease;
}

button:hover {
background-color: #0056b3;
transform: scale(1.1);
}

3. Advanced Selectors

/* Descendant, child, and adjacent sibling selectors */
nav ul li a {
text-decoration: none;
color: #333;
}

.container > .item {
border: 1px solid #ddd;
}

h1 + p {
font-style: italic;
color: gray;
}

5. Media Queries

/* Responsive design with media queries */
@media (max-width: 600px) {
.container {
padding: 10px;
font-size: 14px;
}

#header {
font-size: 20px;
}
}

2. Exposing Ports and Environment Variables

# Base image
FROM node:16

# Set environment variables
ENV NODE_ENV=production \
PORT=3000

# Install dependencies
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production

# Copy application files
COPY . .

# Expose a port
EXPOSE 3000

# Command to start the application
CMD ["node", "server.js"]

14. Chaining Commands with Escape Characters

# Base image
FROM ubuntu:20.04

# Long RUN command with backslashes
RUN apt-get update && apt-get install -y \
git \
curl \
vim && \
rm -rf /var/lib/apt/lists/*

7. Options

(* Using option types *)
let divide a b =
if b = 0 then None else Some (a / b)

let result = divide 10 2

let () =
match result with
| Some value -> Printf.printf "Result: %d\n" value
| None -> print_endline "Cannot divide by zero"

10. Classes

// Define a class
class Person(val name: String, val age: Int) {
def greet(): String = s"Hi, I'm $name and I'm $age years old."
}

// Create an instance
val alice = new Person("Alice", 30)
println(alice.greet()) // Output: Hi, I'm Alice and I'm 30 years old.

15. Futures (Asynchronous Programming)

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

val future = Future {
Thread.sleep(1000)
"Hello from the future!"
}

future.foreach(println) // Output: Hello from the future!
Thread.sleep(1100) // Wait for the future to complete

13. Companion Objects

class Person(val name: String)

object Person {
def apply(name: String): Person = new Person(name)
}

val bob = Person("Bob")
println(bob.name) // Output: Bob

3. Functions

// Define a function
def square(x: Int): Int = x * x

// Call the function
println(square(4)) // Output: 16

13. Agents for State Management

# Start an agent
{:ok, agent} = Agent.start(fn -> 0 end)

# Update and read the state
Agent.update(agent, &(&1 + 10))
IO.puts(Agent.get(agent, & &1)) # Output: 10

2. Pattern Matching

# Matching values
{a, b, c} = {1, 2, 3}
IO.puts("a = #{a}, b = #{b}, c = #{c}")

# Matching in functions
defmodule Matcher do
def describe({:ok, result}), do: "Success: #{result}"
def describe({:error, reason}), do: "Error: #{reason}"
end

IO.puts(Matcher.describe({:ok, "All good"}))
IO.puts(Matcher.describe({:error, "Something went wrong"}))

3. Conditionals

# Using `if`
x = 10
if x > 5 do
IO.puts("x is greater than 5")
else
IO.puts("x is 5 or less")
end

# Using `case`
case {1, 2, 3} do
{1, 2, 3} -> IO.puts("Matched tuple!")
_ -> IO.puts("No match")
end

5. Using Libraries

model SpringDamperSystem
import Modelica.Mechanics.Translational.Components.Spring;
import Modelica.Mechanics.Translational.Components.Damper;
import Modelica.Mechanics.Translational.Components.Mass;

Spring spring(c=100);
Damper damper(d=10);
Mass mass(m=1);

equation
connect(spring.flange_b, damper.flange_a);
connect(damper.flange_b, mass.flange_a);
end SpringDamperSystem;

3. Connectors for Electrical Components

model SimpleCircuit
Resistor R1(R=100);
Capacitor C1(C=0.001);
Inductor L1(L=0.01);
VoltageSourceAC V1(V=220, freqHz=50);
Ground G;

equation
connect(V1.p, R1.p);
connect(R1.n, C1.p);
connect(C1.n, L1.p);
connect(L1.n, V1.n);
connect(V1.n, G.p);
end SimpleCircuit;

12. Model with External Function

function externalFunctionExample
input Real inputValue;
output Real outputValue;

external "C"
outputValue = externalCFunction(inputValue);
end externalFunctionExample;

model UseExternalFunction
Real result;

equation
result = externalFunctionExample(2.0);
end UseExternalFunction;

SQL

-- Create a table
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
position VARCHAR(50),
salary DECIMAL(10, 2),
hire_date DATE DEFAULT CURRENT_DATE
);

-- Insert values into the table
INSERT INTO employees (name, position, salary)
VALUES
('Alice', 'Developer', 70000),
('Bob', 'Designer', 65000),
('Charlie', 'Manager', 90000);

SQL

-- Select with INNER JOIN and aggregate functions
SELECT
e.name AS employee_name,
d.department_name,
AVG(e.salary) OVER (PARTITION BY d.id) AS avg_salary
FROM
employees e
INNER JOIN
departments d ON e.department_id = d.id
WHERE
e.salary > 60000
ORDER BY
e.salary DESC;

SQL

-- Update rows conditionally
UPDATE employees
SET salary = salary * 1.1
WHERE position = 'Developer';

-- Delete rows with a condition
DELETE FROM employees
WHERE salary < 50000;

SQL

-- Pivoting data (MySQL example with JSON_ARRAYAGG)
SELECT
department_id,
JSON_ARRAYAGG(name) AS employee_names
FROM
employees
GROUP BY
department_id;

SQL

-- Create an index on the employees table
CREATE INDEX idx_salary ON employees(salary);

-- Composite index
CREATE INDEX idx_name_position ON employees(name, position);

13. Working with Databases (PDO)

<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
$user = $stmt->fetch();
echo "User: " . $user['name'];
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>

5. Loops

<?php
// For loop
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i\n";
}

// While loop
$count = 0;
while ($count < 3) {
echo "Count: $count\n";
$count++;
}

// Foreach loop
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "Color: $color\n";
}
?>

2. Variables and Data Types

<?php
$name = "Alice"; // String
$age = 30; // Integer
$price = 19.99; // Float
$isAvailable = true; // Boolean

echo "Name: $name, Age: $age, Price: $price, Available: $isAvailable";
?>

5. Lists and List Operations

# Define a list
list = [1, 2, 3, 4]

# Prepend to a list
new_list = [0 | list]
IO.inspect(new_list) # Output: [0, 1, 2, 3, 4]

# Using Enum
squared = Enum.map(list, fn x -> x * x end)
IO.inspect(squared) # Output: [1, 4, 9, 16]

filtered = Enum.filter(list, fn x -> rem(x, 2) == 0 end)
IO.inspect(filtered) # Output: [2, 4]

LaTeX math

A = \bigl\{a_0, a_1, \$\$, a_2, \dots, a_{n-1}\bigr\}.
B = \bigl\{b^0, b^1, b^2, \dots, b^{n-1}\bigr\}.

$$e^{i\pi}$$

$a^2 + b^2 = c^2$

19. Regex

val pattern = "Scala (.*)".r
val str = "Scala is awesome"

str match {
case pattern(word) => println(s"Matched: $word") // Output: Matched: is awesome
case _ => println("No match")
}

5. Loops

// For loop
for (i <- 1 to 5) {
println(s"Iteration: $i")
}

// While loop
var count = 0
while (count < 3) {
println(s"Count: $count")
count += 1
}

12. Traits

trait Shape {
def area: Double
}

class Circle(radius: Double) extends Shape {
def area: Double = Math.PI * radius * radius
}

val circle = new Circle(5)
println(circle.area) // Output: 78.53981633974483

18. Modules

// Define an object
object Utils {
def greet(name: String): String = s"Hello, $name!"
}

// Call a method from the object
println(Utils.greet("Alice")) // Output: Hello, Alice!

13. Discrete Systems

model DiscreteSystem
discrete Real counter(start=0);

equation
when sample(0, 1) then
counter = pre(counter) + 1;
end when;
end DiscreteSystem;

BibTeX file

@book{latexcompanion,
author = {Frank Mittelbach and Michel Goossens},
title = {The LaTeX Companion},
year = {2004},
publisher = {Addison-Wesley}
}

16. Date and Time

<?php
echo "Current date: " . date("Y-m-d");
echo "Current time: " . date("H:i:s");
?>

11. Concurrency with spawn

# Spawn a new process
spawn(fn -> IO.puts("Hello from a new process!") end)

LaTeX

\documentclass[12pt]{article}

\title{Introduction to LaTeX}
\author{John Doe}
\date{\today}

\begin{document}

\maketitle

\section{Introduction}
This is an example document demonstrating various LaTeX features.

\section{Content}
\subsection{Why Use LaTeX?}
LaTeX is widely used for typesetting complex documents, especially those with:
\begin{itemize}
\item Mathematical expressions
\item Tables and figures
\item Bibliographies and references
\end{itemize}

\end{document}

SQL

-- Ranking employees by salary within their department
SELECT
name,
department_id,
salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank
FROM
employees;

SQL

-- Temporary table example
CREATE TEMPORARY TABLE temp_high_salaries AS
SELECT * FROM employees WHERE salary > 80000;

-- CTE example
WITH high_earners AS (
SELECT name, salary FROM employees WHERE salary > 80000
)
SELECT * FROM high_earners;

14. Sessions

<?php
session_start();
$_SESSION['username'] = 'Alice';
echo "Session username: " . $_SESSION['username'];
?>

1. Basic Syntax

# Simple arithmetic
x = 5 + 3
y = x * 2

# String interpolation
name = "Alice"
greeting = "Hello, #{name}!"
IO.puts(greeting)

10. Pipe Operator

# Using the pipe operator
list = [1, 2, 3, 4]

list
|> Enum.map(&(&1 * 2))
|> Enum.filter(&(&1 > 4))
|> IO.inspect() # Output: [6, 8]

14. ETS (Erlang Term Storage)

# Create an ETS table
:ets.new(:my_table, [:set, :protected, :named_table])

# Insert and lookup
:ets.insert(:my_table, {:key, "value"})
IO.inspect(:ets.lookup(:my_table, :key)) # Output: [key: "value"]

10. Partial Models

partial model ThermalComponent
parameter Real k;
Real temperature;

equation
der(temperature) = k;
end ThermalComponent;

model Heater
extends ThermalComponent(k=0.5);

equation
temperature = temperature + 10.0;
end Heater;

14. Array Operations

model ArrayExample
parameter Integer n = 3;
Real a[n] = {1, 2, 3};
Real b[n];

equation
for i in 1:n loop
b[i] = a[i] * 2;
end for;
end ArrayExample;

SQL

-- Using CASE for conditional logic
SELECT
name,
salary,
CASE
WHEN salary > 80000 THEN 'High'
WHEN salary BETWEEN 50000 AND 80000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM
employees;

SQL

-- Subquery to find employees with above-average salary
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

-- Correlated subquery
SELECT name, salary
FROM employees e1
WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e1.position = e2.position);

10. Error Handling

<?php
try {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "Cleanup resources";
}
?>

9. Anonymous Functions

// Using an anonymous function
val increment = (x: Int) => x + 1
println(increment(5)) // Output: 6

1. Basic Syntax

// Print to the console
println("Hello, Scala!")

// Simple arithmetic
val x = 5 + 3
val y = x * 2
println(s"The result is: $y")

14. Collections and Functional Programming

val numbers = List(1, 2, 3, 4, 5)

// Filter even numbers
val evens = numbers.filter(_ % 2 == 0)
println(evens) // Output: List(2, 4)

// Map to square each number
val squares = numbers.map(x => x * x)
println(squares) // Output: List(1, 4, 9, 16, 25)

// Reduce to find the sum
val sum = numbers.reduce(_ + _)
println(sum) // Output: 15

12. Task for Concurrency

# Using Task for asynchronous operations
task = Task.async(fn -> :timer.sleep(1000); "Finished task!" end)
IO.puts("Waiting for task...")
IO.puts(Task.await(task)) # Output: "Finished task!" after 1 second

Modelica

SQL

1. Basic PHP Syntax

<?php
// Simple PHP script
echo "Hello, World!";
?>

8. File Handling

<?php
// Write to a file
file_put_contents("example.txt", "This is a test file.");

// Read from a file
$content = file_get_contents("example.txt");
echo $content;
?>

20. Generics

// Define a generic class
class Box[T](val value: T) {
def get: T = value
}

val intBox = new Box(42)
println(intBox.get) // Output: 42

val strBox = new Box("Hello")
println(strBox.get) // Output: Hello

LaTeX math equations

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\section*{Mathematical Examples}

Inline equation: \( E = mc^2 \).

Displayed equation:
\[
\int_{0}^{\infty} x^2 e^{-x} \, dx = 2
\]

Aligned equations:
\begin{align*}
a + b &= c \\
x - y &= z
\end{align*}

\end{document}

TeX

PHP

Scala

Elixir

9. Multi-body System

model Pendulum
import Modelica.Mechanics.MultiBody;

MultiBody.Parts.Body body(m=1);
MultiBody.Joints.Revolute revolute;
MultiBody.World world;

equation
connect(world.frame_b, revolute.frame_a);
connect(revolute.frame_b, body.frame_a);
end Pendulum;

LaTeX verbatim

\documentclass{article}

\begin{document}

\section*{Verbatim Example}

The \texttt{verbatim} environment allows you to display code or text exactly as it is:

\begin{verbatim}
#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!" << endl;
return 0;
}
\end{verbatim}

You can also use the \texttt{\textbackslash verb} command for inline verbatim text, like this:
\verb|inline code example here|.

\end{document}

7. Classes and Objects

<?php
class User {
public $name;
public $age;

public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

public function greet() {
return "Hi, I'm $this->name and I'm $this->age years old.";
}
}

$user = new User("Charlie", 28);
echo $user->greet();
?>

17. Lazy Evaluation

lazy val expensiveComputation = {
println("Computing...")
42
}

println("Before accessing lazy val")
println(expensiveComputation) // Computes and prints 42

9. Modules and Functions

defmodule Math do
def add(a, b) do
a + b
end

def square(x), do: x * x
end

IO.puts(Math.add(3, 5)) # Output: 8
IO.puts(Math.square(4)) # Output: 16

16. Supervisors

defmodule MyApp.Supervisor do
use Supervisor

def start_link, do: Supervisor.start_link(__MODULE__, :ok, name: __MODULE__)

def init(:ok) do
children = [
{Counter, 0}
]

Supervisor.init(children, strategy: :one_for_one)
end
end

SQL

-- Dynamic SQL example
DELIMITER $$

CREATE PROCEDURE GetEmployeesByDepartment(IN dept_id INT)
BEGIN
SET @query = CONCAT('SELECT * FROM employees WHERE department_id = ', dept_id);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$

DELIMITER ;

9. Superglobals

<?php
// Access GET parameters
$name = $_GET['name'] ?? 'Guest';
echo "Hello, $name";

// Access POST parameters
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
echo "Welcome, $username";
}
?>

3. Arrays

<?php
// Indexed array
$fruits = ["Apple", "Banana", "Cherry"];
echo "First fruit: " . $fruits[0];

// Associative array
$user = ["name" => "Bob", "age" => 25];
echo "User's name: " . $user['name'];

// Multidimensional array
$matrix = [[1, 2], [3, 4]];
echo "Element: " . $matrix[1][0];
?>

11. Case Classes

// Define a case class
case class Point(x: Int, y: Int)

// Create instances and use pattern matching
val p = Point(1, 2)

val description = p match {
case Point(0, 0) => "Origin"
case Point(x, y) => s"Point($x, $y)"
}

println(description) // Output: Point(1, 2)

6. Tuples

# Define and access tuples
tuple = {:ok, "Success"}
IO.inspect(elem(tuple, 1)) # Output: "Success"

15. GenServer Example

defmodule Counter do
use GenServer

# Callbacks
def init(initial_value), do: {:ok, initial_value}

def handle_call(:get, _from, state), do: {:reply, state, state}
def handle_cast({:increment, value}, state), do: {:noreply, state + value}

# API
def start_link(initial_value), do: GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)
def get, do: GenServer.call(__MODULE__, :get)
def increment(value), do: GenServer.cast(__MODULE__, {:increment, value})
end

{:ok, _pid} = Counter.start_link(0)
Counter.increment(10)
IO.puts(Counter.get()) # Output: 10

8. Record for Data Structures

record Point
Real x;
Real y;
end Point;

model PointExample
Point p1(x=1.0, y=2.0);
Point p2;

equation
p2.x = p1.x + 1.0;
p2.y = p1.y + 2.0;
end PointExample;

SQL

-- Create a view
CREATE VIEW high_salary_employees AS
SELECT name, position, salary
FROM employees
WHERE salary > 80000;

-- Trigger to log salary changes
CREATE TRIGGER salary_update_log
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_log (employee_id, old_salary, new_salary, change_date)
VALUES (OLD.id, OLD.salary, NEW.salary, NOW());
END;

SQL

-- Transaction example
BEGIN TRANSACTION;

UPDATE accounts
SET balance = balance - 500
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 500
WHERE account_id = 2;

-- Commit the transaction
COMMIT;

15. Regular Expressions

<?php
$pattern = "/^hello/i";
$text = "Hello, World!";
if (preg_match($pattern, $text)) {
echo "Pattern matches!";
}
?>

2. Variables

// Immutable variable
val immutableVar = "I can't change"

// Mutable variable
var mutableVar = "I can change"
mutableVar = "I've changed!"

println(immutableVar)
println(mutableVar)

4. Functions

function add
input Real a;
input Real b;
output Real result;

algorithm
result := a + b;
end add;

SQL

-- Create a table with JSON and JSONB columns
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
details JSONB,
preferences JSON
);

-- Insert data into the table
INSERT INTO employees (name, details, preferences)
VALUES
('Alice', '{"age": 30, "position": "Developer", "skills": ["JavaScript", "SQL"]}', '{"theme": "dark", "notifications": true}'),
('Bob', '{"age": 40, "position": "Manager", "skills": ["Leadership", "Planning"]}', '{"theme": "light", "notifications": false}'),
('Charlie', '{"age": 25, "position": "Designer", "skills": ["Photoshop", "Illustrator"]}', '{"theme": "dark", "notifications": true}');

-- Query JSON data using operators and functions
-- 1. Accessing a JSON field
SELECT name, details->>'position' AS position
FROM employees;

-- 2. Accessing nested JSON fields
SELECT name, details->'skills'->>0 AS primary_skill
FROM employees;

-- 3. Filtering rows based on JSON fields
SELECT name
FROM employees
WHERE details->>'position' = 'Developer';

-- 4. Checking if a JSON key exists
SELECT name
FROM employees
WHERE details ? 'age';

-- 5. Using JSONB containment operator (@>)
SELECT name
FROM employees
WHERE details @> '{"skills": ["SQL"]}';

-- 6. Updating a JSON field
UPDATE employees
SET details = jsonb_set(details, '{age}', '35'::jsonb)
WHERE name = 'Alice';

-- 7. Adding a new key to a JSONB object
UPDATE employees
SET details = jsonb_set(details, '{department}', '"IT"'::jsonb)
WHERE name = 'Bob';

-- 8. Removing a key from a JSONB object
UPDATE employees
SET details = details - 'skills'
WHERE name = 'Charlie';

-- Aggregate JSON data
-- 9. Create a JSON object grouping all employees by their position
SELECT json_object_agg(name, details) AS employee_summary
FROM employees;

-- 10. Create a JSON array of all employee preferences
SELECT json_agg(preferences) AS all_preferences
FROM employees;

-- 11. Flatten JSON array values into rows using jsonb_array_elements
SELECT name, skill
FROM employees, jsonb_array_elements(details->'skills') AS skill;

-- Using a JSONB index for performance
-- 12. Create a GIN index for JSONB data
CREATE INDEX idx_details_jsonb ON employees USING GIN (details);

-- Query using the index
SELECT name
FROM employees
WHERE details @> '{"position": "Developer"}';

6. Collections

// Lists
val fruits = List("Apple", "Banana", "Cherry")
println(fruits.head) // Output: Apple
println(fruits.tail) // Output: List(Banana, Cherry)
println(fruits.map(_.toUpperCase)) // Output: List(APPLE, BANANA, CHERRY)

// Maps
val ages = Map("Alice" -> 25, "Bob" -> 30)
println(ages("Alice")) // Output: 25

// Sets
val numbers = Set(1, 2, 3, 3)
println(numbers) // Output: Set(1, 2, 3)

2. Model with Inheritance

model ParentModel
parameter Real baseValue = 1.0;
Real y;

equation
y = baseValue + time;
end ParentModel;

model ChildModel
extends ParentModel;
parameter Real extraValue = 2.0;

equation
y = y + extraValue;
end ChildModel;

7. Events and Conditional Equations

model BouncingBall
parameter Real g = 9.81;
parameter Real e = 0.8; // Coefficient of restitution
Real h(start=10);
Real v(start=0);

equation
der(h) = v;
der(v) = -g;

when h < 0 then
reinit(v, -e * v);
end when;
end BouncingBall;

12. Include and Require

<?php
// content.php
// <?php
// echo "This is included content.";

// Include a file
include 'content.php';

// Require a file
require 'content.php';
?>

4. Conditional Statements

<?php
$number = 10;

if ($number > 0) {
echo "Positive";
} elseif ($number < 0) {
echo "Negative";
} else {
echo "Zero";
}
?>

7. Pattern Matching

val x: Any = 42

val result = x match {
case 0 => "Zero"
case n: Int => s"Number: $n"
case s: String => s"String: $s"
case _ => "Unknown"
}

println(result) // Output: Number: 42

4. Conditional Statements

val age = 25

if (age < 18) {
println("Minor")
} else if (age >= 18 && age < 65) {
println("Adult")
} else {
println("Senior")
}

8. Recursion

defmodule Recursion do
def factorial(0), do: 1
def factorial(n), do: n * factorial(n - 1)
end

IO.puts(Recursion.factorial(5)) # Output: 120

4. Anonymous Functions

# Define an anonymous function
square = fn x -> x * x end
IO.puts(square.(4)) # Output: 16

# Shorthand syntax
add = &(&1 + &2)
IO.puts(add.(3, 5)) # Output: 8

SQL

-- Grouping data with HAVING
SELECT position, COUNT(*) AS num_employees, MAX(salary) AS max_salary
FROM employees
GROUP BY position
HAVING MAX(salary) > 80000;

7. Maps

# Define a map
map = %{"name" => "Alice", "age" => 30}

# Access values
IO.puts(map["name"]) # Output: Alice

# Using atom keys
person = %{name: "Bob", age: 25}
IO.puts(person.name) # Output: Bob

6. Parameterized Model

model ParameterizedModel
parameter Real k = 0.5;
parameter Real m = 1.0;
Real x(start=0.1, fixed=true);
Real v(start=0, fixed=true);
Real a;

equation
a = -k * x / m;
der(x) = v;
der(v) = a;
end ParameterizedModel;

TikZ

\documentclass{article}
\usepackage{tikz}

\begin{document}

\section*{TikZ Example}

\begin{tikzpicture}
\draw[thick,->] (0,0) -- (4,0) node[right] {$x$};
\draw[thick,->] (0,0) -- (0,3) node[above] {$y$};
\draw[blue] (0,0) circle(1cm);
\end{tikzpicture}

\end{document}

LaTeX tables

\documentclass{article}

\begin{document}

\section*{Table Example}

\begin{table}[h]
\centering
\begin{tabular}{|l|c|r|}
\hline
Item & Quantity & Price (\$) \\ \hline
Apples & 10 & 3.50 \\
Bananas & 5 & 2.75 \\
Cherries & 7 & 5.25 \\ \hline
\end{tabular}
\caption{Fruit Price Table}
\label{tab:fruits}
\end{table}

\end{document}

6. Functions

<?php
// Simple function
function greet($name) {
return "Hello, $name!";
}

echo greet("Alice");
?>

1. Simple Model with Equations

model SimpleModel
parameter Real a = 2.0;
parameter Real b = 3.0;
Real x;

equation
x = a + b;
end SimpleModel;

11. Working with JSON

<?php
// Encode to JSON
$data = ["name" => "Alice", "age" => 25];
$json = json_encode($data);
echo $json;

// Decode JSON
$decoded = json_decode($json, true);
echo $decoded['name'];
?>

16. Try-Catch

import scala.util.Try

val result = Try {
10 / 0
}.recover {
case _: ArithmeticException => "Division by zero!"
}

println(result) // Output: Division by zero!

11. Dynamic Simulation with Time

model DynamicSimulation
Real x(start=0);
Real y;

equation
der(x) = sin(time);
y = cos(time);
end DynamicSimulation;

8. Higher-Order Functions

// Function that takes another function as a parameter
def applyFunc(f: Int => Int, x: Int): Int = f(x)

// Example usage
val doubled = applyFunc(x => x * 2, 5)
println(doubled) // Output: 10