Created by Pavel Klavík
Examples how different languages are highlighted in OrgPad. All examples here were generated by ChatGPT.
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);
}
}
}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();
}
}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));
}
}
enum Shape {
CIRCLE, RECTANGLE, TRIANGLE
}
public class Enums {
public static void main(String[] args) {
Shape myShape = Shape.CIRCLE;
System.out.println("Selected shape: " + myShape);
}
}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());
}
}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));
}
}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++;
}
}
}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);
}
}#include <iostream>
int main() {
int age = 30;
std::string name = "Alice";
std::cout << "Name: " << name << ", Age: " << age << std::endl;
return 0;
}
#include <stdio.h>
int main() {
int age = 30;
char name[] = "Alice";
printf("Name: %s, Age: %d\n", name, age);
return 0;
}
#include <iostream>
void increment(int &value) {
value++;
}
int main() {
int num = 42;
increment(num);
std::cout << "Incremented value: " << num << std::endl;
return 0;
}
=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(A1:A10)
Explanation: Adds all numbers in the range A1:A10.
=LEN(A1)
Explanation: Returns the length of the text in A1.
=TRIM(A1)
Explanation: Removes all extra spaces from the text in A1, leaving only single spaces between words.
=TRANSPOSE(A1:A5)
Explanation: Converts the vertical range A1:A5 into a horizontal range.
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")
}=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.
import java.io.File
fun main() {
val fileName = "example.txt"
File(fileName).writeText("Hello, File!")
val content = File(fileName).readText()
println(content)
}
=ISNUMBER(A1)
Explanation: Checks if the value in A1 is a number.
=COUNTIF(A1:A10, ">10")
Explanation: Counts how many values in A1:A10 are greater than 10.
fun String.toTitleCase(): String {
return this.split(" ").joinToString(" ") { it.capitalize() }
}
fun main() {
val text = "hello kotlin"
println(text.toTitleCase())
}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();
}
}
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}");
}
}
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}");
}
}
}
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}");
}
}
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);
}
}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);
}
}
}
#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;
}
#include <iostream>
int main() {
std::cout << "Hello, C++!" << std::endl;
return 0;
}
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)
}
@helper FormatDate(DateTime date)
{
<span>@date.ToString("MMMM dd, yyyy")</span>
}
<!DOCTYPE html>
<html>
<body>
@FormatDate(DateTime.Now)
</body>
</html>
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();
}
}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();
}
}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");
}
}
}
=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.
=LEFT(A1, 5)
Explanation: Extracts the first 5 characters from the text in A1.
fun main() {
val age = 25
val status = if (age < 18) {
"Minor"
} else if (age in 18..64) {
"Adult"
} else {
"Senior"
}
println("Status: $status")
}<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>
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();
}
}
=TEXT(A1, "MM/DD/YYYY") & " - " & B1
Explanation: Combines a formatted date from A1 and the value in B1 with a dash.
=AVERAGE(B1:B10)
Explanation: Calculates the average of numbers in the range B1:B10.
data class Person(val name: String, val age: Int)
fun main() {
val alice = Person("Alice", 30)
println(alice)
}
fun main() {
val person = mapOf("name" to "Alice", "age" to 30)
println("Name: ${person["name"]}")
println("Age: ${person["age"]}")
}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());
}
}
}
=NOW()
Explanation: Returns the current date and time.
=CONCATENATE(A1, " ", B1)
Explanation: Combines the values of A1 and B1 with a space in between.
=UNIQUE(A1:A10)
Explanation: Extracts unique values from the range A1:A10 (available in Excel 365/2021).
_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>public class ErrorHandling {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}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");
}
}
}#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;
}
=ABS(A1)
Explanation: Returns the absolute value of the number in A1.
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)}");
}
}
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}");
}
}
}
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);
}
}
@{
var items = new[] { "Apple", "Banana", "Cherry" };
}
<!DOCTYPE html>
<html>
<body>
<ul>
@foreach (var item in items)
{
<li>@item</li>
}
</ul>
</body>
</html>#include <stdio.h>
int main() {
printf("Hello, C!\n");
return 0;
}
#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;
}
=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.
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())
}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()
}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);
}
}
=ROUND(A1, 2)
Explanation: Rounds the value in A1 to two decimal places.
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)}")
}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}");
}
}
}
<!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>
=PROPER(A1)
Explanation: Capitalizes the first letter of each word in the text of A1.
=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.
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();
}
}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);
}
}
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);
}
}
public class HelloWorld {
public static void main(String[] args) {
// Print to the console
System.out.println("Hello, Java!");
}
}fun main() {
val name = "Alice" // Immutable variable
var age = 30 // Mutable variable
age += 1
println("Name: $name, Age: $age")
}_PartialView.cshtml
<h3>This is a partial view.</h3>
MainView.cshtml
<!DOCTYPE html>
<html>
<body>
@Html.Partial("_PartialView")
</body>
</html>
<!DOCTYPE html>
<html>
<body>
@for (int i = 1; i <= 5; i++)
{
<p>Number: @i</p>
}
</body>
</html>
#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;
}
#include <stdio.h>
int main() {
int num = 42;
int *ptr = #
printf("Value: %d, Address: %p\n", *ptr, ptr);
return 0;
}
#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;
}
fun main() {
try {
val result = 10 / 0
} catch (e: ArithmeticException) {
println("Error: ${e.message}")
}
}fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
val result = add(3, 5)
println("Sum: $result")
}fun main() {
val square: (Int) -> Int = { x -> x * x }
println("Square of 4: ${square(4)}")
}fun main() {
val name: String? = null
val length = name?.length ?: 0
println("Length: $length")
}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();
}
}
using System;
enum Shape
{
Circle,
Rectangle,
Triangle
}
class Program
{
static void Main()
{
Shape myShape = Shape.Circle;
Console.WriteLine($"Selected shape: {myShape}");
}
}
using System;
class Program
{
static void Main()
{
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
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}");
}
}
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();
}
}
_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>fun main() {
// Print to the console
println("Hello, Kotlin!")
// Simple arithmetic
val x = 5 + 3
val y = x * 2
println("The result is: $y")
}fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
// Access elements
println(fruits[0])
// Iterate through the list
for (fruit in fruits) {
println("Fruit: $fruit")
}
}@{
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>@{
var message = "Hello, CSHTML!";
}
<!DOCTYPE html>
<html>
<head>
<title>CSHTML Example</title>
</head>
<body>
<h1>@message</h1>
</body>
</html>enum class Shape {
Circle, Rectangle, Triangle
}
fun main() {
val myShape = Shape.Circle
println("Selected shape: $myShape")
}fun main() {
// For loop
for (i in 1..5) {
println("Iteration: $i")
}
// While loop
var count = 0
while (count < 3) {
println("Count: $count")
count++
}
}import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
delay(1000L)
println("Coroutine done!")
}
println("Waiting...")
job.join()
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>CSHTML with CSS</h1>
<script src="scripts.js"></script>
</body>
</html>
// 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');
}
}
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);
}void main() {
// Immutable variable
final String name = 'Alice';
// Mutable variable
var age = 30;
age = 31;
print('Name: $name, Age: $age');
}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();
}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));
}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}");
}
}
void main() {
try {
int result = 10 ~/ 0; // Integer division by zero
} catch (e) {
print('Error: $e');
}
}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}");
}
}
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++;
}
}
}
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();
}
}
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());
}
}
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>
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let doubled: Vec<_> = numbers.iter().map(|x| x * 2).collect();
println!("Doubled: {:?}", doubled);
}<!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>
@{
var isLoggedIn = true;
var username = "Alice";
}
<!DOCTYPE html>
<html>
<body>
@if (isLoggedIn)
{
<h1>Welcome, @username!</h1>
}
else
{
<h1>Please log in.</h1>
}
</body>
</html>@{
var username = "Alice";
}
<!DOCTYPE html>
<html>
<body>
<script>
var user = "@username";
console.log("Welcome, " + user);
</script>
</body>
</html>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));
}struct Person {
name: String,
age: u8,
}
fn main() {
let alice = Person {
name: String::from("Alice"),
age: 30,
};
println!("Name: {}, Age: {}", alice.name, alice.age);
}fn main() {
let point = (3, 4);
let (x, y) = point;
println!("Point: ({}, {})", x, y);
}int add(int a, int b) {
return a + b;
}
void main() {
int result = add(3, 5);
print('Sum: $result');
}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);
}void main() {
List<int> numbers = [1, 2, 3, 4];
// Using an anonymous function
numbers.forEach((num) {
print(num * num);
});
}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++;
}
}void main() {
int age = 25;
if (age < 18) {
print('Minor');
} else if (age >= 18 && age < 65) {
print('Adult');
} else {
print('Senior');
}
}void main() {
String? nullableString = null;
if (nullableString == null) {
print('The string is null');
} else {
print('The string is $nullableString');
}
}threads = []
5.times do |i|
threads << Thread.new do
puts "Thread #{i} is running"
end
end
threads.each(&:join)
# Custom iterator
def countdown(start)
while start > 0
yield start
start -= 1
end
end
countdown(5) { |n| puts n }
# For loop
(1..5).each do |i|
puts "Iteration: #{i}"
end
# While loop
count = 0
while count < 3
puts "Count: #{count}"
count += 1
end
def greet(name)
"Hello, #{name}!"
end
puts greet("Alice")
# Define a lambda
square = ->(x) { x * x }
puts square.call(5)
fruits = ["Apple", "Banana", "Cherry"]
# Access elements
puts fruits[0]
# Iterate through an array
fruits.each do |fruit|
puts "Fruit: #{fruit}"
end
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;
}
}text = "Hello, Python!"
print(text.upper())
print(text.lower())
print(text.replace("Python", "World"))
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();
}age = 25
if age < 18:
print("Minor")
elif 18 <= age < 65:
print("Adult")
else:
print("Senior")
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())
fn main() {
// Print a message
println!("Hello, Rust!");
// Simple arithmetic
let x = 5 + 3;
let y = x * 2;
println!("The result is: {}", y);
}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())
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);
}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"),
}
}extension StringExtension on String {
String toTitleCase() {
return this[0].toUpperCase() + this.substring(1).toLowerCase();
}
}
void main() {
String text = 'hello';
print(text.toTitleCase()); // Output: Hello
}text = "The quick brown fox"
if text =~ /quick/
puts "Match found!"
end
puts text.gsub(/fox/, "dog")
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();
}# Print to the console
puts "Hello, Ruby!"
# Simple arithmetic
x = 5 + 3
y = x * 2
puts "The result is: #{y}"
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');
}
}void main() {
// Print to the console
print('Hello, Dart!');
// Simple arithmetic
int x = 5 + 3;
int y = x * 2;
print('The result is: $y');
}import numpy as np
# Create a NumPy array
array = np.array([1, 2, 3, 4, 5])
# Perform operations
print(array * 2)
print(array.mean())
module Greetable
def greet
"Hello!"
end
end
class Person
include Greetable
end
alice = Person.new
puts alice.greet
module MathUtils
def self.square(x)
x * x
end
end
puts MathUtils.square(5)
begin
result = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
end
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
const PI: f64 = 3.14159;
fn main() {
println!("Value of Pi: {}", PI);
}
fn print_string(s: &String) {
println!("{}", s);
}
fn main() {
let s = String::from("Hello");
print_string(&s); // Borrowing
println!("{}", s); // Still accessible
}# Generator function
def countdown(n):
while n > 0:
yield n
n -= 1
for number in countdown(5):
print(number)
# 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)
// 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}`);
});
class Animal {
speak() {
return "Animal makes a sound";
}
}
class Dog extends Animal {
speak() {
return "Woof!";
}
}
const myDog = new Dog();
console.log(myDog.speak());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());const header: HTMLElement | null = document.querySelector("h1");
if (header) {
header.textContent = "Hello, DOM!";
}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
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
fn main() {
let x = Some(5);
match x {
Some(value) => println!("Value: {}", value),
None => println!("No value"),
}
}fn main() {
let s = String::from("Hello");
let s_with_world = format!("{}, World!", s);
println!("{}", s_with_world);
}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);
}# Import math module
import math
print(f"Pi value: {math.pi}")
interface Person {
name: string;
age: number;
}
const alice: Person = { name: "Alice", age: 30 };
console.log(`Name: ${alice.name}, Age: ${alice.age}`);# Immutable variable
name = "Alice"
# Mutable variable
age = 30
age += 1
print(f"Name: {name}, Age: {age}")
const fetchData = () =>
new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 1000);
});
fetchData().then((data) => console.log(data));
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person; // "name" | "age"
const key: PersonKeys = "name";
console.log(key);type ID = string | number;
let userId: ID = "123";
console.log(`User ID: ${userId}`);
userId = 456;
console.log(`User ID: ${userId}`);
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
age = 25
if age < 18
puts "Minor"
elsif age >= 18 && age < 65
puts "Adult"
else
puts "Senior"
end
name = "Alice"
age = 30
is_active = true
puts "Name: #{name}, Age: #{age}, Active: #{is_active}"
# 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
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}"
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');
}
}# Using symbols as keys
person = { name: "Alice", age: 30 }
puts person[:name]
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();
}mixin Flyable {
void fly() {
print('I can fly!');
}
}
class Bird with Flyable {}
void main() {
Bird bird = Bird();
bird.fly();
}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;
}
}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']);
}
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greet("Alice"));
console.log(greet("Bob", "Hi"));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
import re
text = "The quick brown fox"
pattern = r"quick"
if re.search(pattern, text):
print("Pattern found!")
// 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";
const age = 25;
if (age < 18) {
console.log("Minor");
} else if (age >= 18 && age < 65) {
console.log("Adult");
} else {
console.log("Senior");
}
use std::fs::File;
fn main() {
match File::open("nonexistent.txt") {
Ok(_) => println!("File opened successfully"),
Err(e) => println!("Error opening file: {}", e),
}
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let result = add(3, 5);
println!("Sum: {}", result);
}use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("Hello from a thread!");
});
handle.join().unwrap();
}
fn main() {
let age = 25;
if age < 18 {
println!("Minor");
} else if age >= 18 && age < 65 {
println!("Adult");
} else {
println!("Senior");
}
}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"))
# 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)
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"])
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 }));# Using a block
[1, 2, 3].each { |n| puts n * n }
# Using a proc
square = Proc.new { |x| x * x }
puts square.call(4)
# Generate squares of numbers from 1 to 5
squares = [x**2 for x in range(1, 6)]
print(squares)
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);
// Print to the console
console.log("Hello, JavaScript!");
// Simple arithmetic
let x = 5 + 3;
let y = x * 2;
console.log(`The result is: ${y}`);
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);person = { name: "Alice", age: 30, city: "New York" }
# Access values
puts person[:name]
# Add a new key-value pair
person[:country] = "USA"
puts personuse 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);
}
const fetchData = async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 1000);
});
};
(async () => {
console.log("Fetching...");
const data = await fetchData();
console.log(data);
})();enum Shape {
Circle,
Rectangle,
Triangle,
}
const myShape: Shape = Shape.Circle;
console.log(`Selected shape: ${Shape[myShape]}`);const multiply = (a: number, b: number): number => a * b;
console.log(`Product: ${multiply(4, 5)}`);
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
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
text = "Hello, Ruby!"
puts text.upcase
puts text.downcase
puts text.gsub("Ruby", "World")
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
try {
throw new Error("Something went wrong!");
} catch (error) {
console.log(`Error: ${error.message}`);
}# 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
# Print to the console
print("Hello, Python!")
# Simple arithmetic
x = 5 + 3
y = x * 2
print(f"The result is: {y}")
# Define a function
def add(a, b):
return a + b
# Call the function
result = add(3, 5)
print(f"Sum: {result}")
# Define a lambda function
square = lambda x: x * x
# Call the lambda function
print(f"Square of 4: {square(4)}")
// 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);
let point: [number, number] = [3, 4];
console.log(`Point: (${point[0]}, ${point[1]})`);
# Define a list
fruits = ["Apple", "Banana", "Cherry"]
# Access elements
print(fruits[0])
# Iterate through a list
for fruit in fruits:
print(f"Fruit: {fruit}")
// 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++;
}
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
console.log(`Name: ${name}, Age: ${age}, Active: ${isActive}`);
const text = "The quick brown fox";
const pattern = /quick/;
if (pattern.test(text)) {
console.log("Match found!");
}
console.log(text.replace(/fox/, "dog"));
// Immutable variable
const name = "Alice";
// Mutable variable
let age = 30;
age += 1;
console.log(`Name: ${name}, Age: ${age}`);
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());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
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
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
const text = "Hello, JavaScript!";
console.log(text.toUpperCase());
console.log(text.toLowerCase());
console.log(text.replace("JavaScript", "World"));
interface User {
id: number;
name: string;
email?: string; // Optional property
}
const user: User = { id: 1, name: "Alice" };
console.log(user);function identity<T>(value: T): T {
return value;
}
console.log(identity<number>(42));
console.log(identity<string>("Hello"));// 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}`);
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
const multiply = (a, b) => a * b;
console.log(`Product: ${multiply(4, 5)}`);
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
let value: unknown = "Hello, TypeScript!";
let strLength: number = (value as string).length;
console.log(`String length: ${strLength}`);
// Define a function
function add(a, b) {
return a + b;
}
// Call the function
const result = add(3, 5);
console.log(`Sum: ${result}`);
// 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));
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);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()
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));extension Int {
func squared() -> Int {
return self * self
}
}
print("Square of 5: \(5.squared())")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
// 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));
open System.Threading.Tasks
let asyncExample () =
async {
do! Async.Sleep 1000
printfn "Hello from async!"
}
Async.Start(asyncExample ())
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
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)")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
function fetchData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve("Data fetched!"), 1000);
});
}
fetchData().then((data) => console.log(data));# 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
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)
}
let fruits = ["Apple", "Banana", "Cherry"]
print("First fruit: \(fruits[0])")
for fruit in fruits {
print("Fruit: \(fruit)")
}
// 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
# Concatenate strings
greeting <- paste("Hello", "World", sep = ", ")
print(greeting)
# String length
print(nchar(greeting)) # Output: 12
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);
})();function add(a: number, b: number): number {
return a + b;
}
const result: number = add(3, 5);
console.log(`Sum: ${result}`);let mutable counter = 0
counter <- counter + 1
printfn "Counter: %d" counter
let identity x = x
printfn "Int: %d" (identity 42)
printfn "String: %s" (identity "Hello")
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
# Match a pattern
text <- "The quick brown fox"
matches <- grepl("quick", text)
print(matches) # Output: TRUE
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)
}
class Animal {
func speak() {
print("Animal sound")
}
}
class Dog: Animal {
override func speak() {
print("Woof!")
}
}
let myDog = Dog()
myDog.speak()try
let result = 10 / 0
printfn "Result: %d" result
with
| :? System.DivideByZeroException -> printfn "Cannot divide by zero!"
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
func add(a: Int, b: Int) -> Int {
return a + b
}
let result = add(a: 3, b: 5)
print("Sum: \(result)")let constantVar = "I cannot change"
var mutableVar = "I can change"
mutableVar = "I've changed!"
print(constantVar)
print(mutableVar)
// 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
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)
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
# Try-Catch block
result <- tryCatch(
{
10 / 0
},
warning = function(w) {
print("This is a warning")
},
error = function(e) {
print("An error occurred")
}
)
print(result)
# 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)
# Print to console
print("Hello, R!")
# Basic arithmetic
x <- 5 + 3
y <- x * 2
print(y)
# 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
# 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
# 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)
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)
}
}
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
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())")let numbers = seq { 1 .. 10 }
let squares = numbers |> Seq.map (fun x -> x * x)
printfn "Squares: %A" squares// 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
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
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
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)
}
let username: String? = nil
let defaultUsername = "Guest"
let currentUsername = username ?? defaultUsername
print("Current username: \(currentUsername)")
-- Print to console
print("Hello, Lua!")
-- Simple arithmetic
local x = 5 + 3
local y = x * 2
print("Result:", y)
# 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
protocol Greetable {
func greet()
}
class Greeter: Greetable {
func greet() {
print("Hello!")
}
}
let greeter = Greeter()
greeter.greet()import Foundation
print("Hello, Swift!")
// Simple arithmetic
let x = 5 + 3
let y = x * 2
print("The result is: \(y)")
// Define a function
let square x = x * x
// Call the function
let result = square 4
printfn "Square of 4 is: %d" result
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
# Using the pipe operator
library(dplyr)
result <- mtcars %>%
filter(mpg > 20) %>%
select(mpg, cyl)
print(result)
# Define a function
square <- function(x) {
return(x * x)
}
# Call the function
print(square(4)) # Output: 16
# 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")
-- 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)
-- 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"))
# 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"
package main
import "fmt"
func updateValue(num *int) {
*num = 20
}
func main() {
x := 10
fmt.Println("Before:", x)
updateValue(&x)
fmt.Println("After:", x)
}
// 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"
// 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
# 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
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)
}
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)
}
var person = ["name": "Alice", "age": "30"]
print("Name: \(person["name"]!)")
person["city"] = "New York"
print(person)
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()' Print a message to the console
Module HelloWorld
Sub Main()
Console.WriteLine("Hello, VB.NET!")
End Sub
End Module
let age = 25
if age < 18 then
printfn "Minor"
elif age >= 18 && age < 65 then
printfn "Adult"
else
printfn "Senior"
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
# Basic plot
x <- 1:10
y <- x^2
plot(x, y, type = "b", col = "blue", main = "Basic Plot", xlab = "X", ylab = "Y^2")
# Create a factor
gender <- factor(c("Male", "Female", "Male"))
print(gender)
# Levels
print(levels(gender))
# 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)
-- 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)
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())
}
var possibleNumber: Int? = 42
if let number = possibleNumber {
print("Number: \(number)")
} else {
print("No number")
}
local age = 25
if age < 18 then
print("Minor")
elseif age >= 18 and age < 65 then
print("Adult")
else
print("Senior")
end
let age = 25
if age < 18 {
print("Minor")
} else if age < 65 {
print("Adult")
} else {
print("Senior")
}
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
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
# 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
}
-- 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)
# Try-Catch block
try {
Get-Content non_existent_file.txt
} catch {
Write-Output "An error occurred: $_"
}
# 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"
}
# Get a list of running processes
Get-Process
# Stop a specific process
# Stop-Process -Name "notepad"
# Get current directory
Get-Location
// Print to the console
printfn "Hello, F#!"
// Basic arithmetic
let x = 5 + 3
let y = x * 2
printfn "The result is: %d" y
-- 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
# Run a command on a remote machine
Invoke-Command -ComputerName "Server01" -ScriptBlock { Get-Process }
# Start a remote session
Enter-PSSession -ComputerName "Server01"
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
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)
}
}
// For loop
for i in 1...5 {
print("Iteration: \(i)")
}
// While loop
var count = 0
while count < 3 {
print("Count: \(count)")
count += 1
}
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
# If-Else statement
x <- 10
if (x > 5) {
print("x is greater than 5")
} else {
print("x is 5 or less")
}
struct Data {
lazy var expensiveCalculation: Int = {
print("Calculating...")
return 42
}()
}
var data = Data()
print("Before accessing")
print("Value: \(data.expensiveCalculation)")// Define a tuple
let point = (3, 4)
// Access tuple elements
let x, y = point
printfn "Point: (%d, %d)" x y
// 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)))
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
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
# 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)
# 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)
# 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
# Output to console
Write-Output "Hello, PowerShell!"
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)
}
-- 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
# Get the status of a service
Get-Service -Name "wuauserv"
# Stop a service
Stop-Service -Name "wuauserv"
# Start a service
Start-Service -Name "wuauserv"
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)
}
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)")
}-- 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
-- Debugging with debug library
local function debugExample()
local x = 10
print(debug.traceback("Stack trace:"))
end
debugExample()
let square = { (x: Int) -> Int in
return x * x
}
print("Square of 4: \(square(4))")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)
}
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")
}
}
# Create a reusable module
function Add-Numbers {
param (
[int]$a,
[int]$b
)
return $a + $b
}
# Save this function to a .psm1 file for reuse
package main
import "fmt"
func main() {
defer fmt.Println("Deferred message")
fmt.Println("Main function message")
}
# Save a script as script.ps1
# To run it:
.\script.ps1
# Write to a file
"Hello, PowerShell!" > example.txt
# Read from a file
$content = Get-Content example.txt
Write-Output $content
# Define a function
function Greet {
param ($name)
Write-Output "Hello, $name!"
}
# Call the function
Greet "Alice"
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))
}
# Import a module
Import-Module MyModule
# List available modules
Get-Module -ListAvailable
-- Define a function
function greet(name)
return "Hello, " .. name .. "!"
end
-- Call the function
local message = greet("Alice")
print(message)
-- 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
-- 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
-- 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"))
#!/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);
# 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"
}
# 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
# 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++
}
# Define variables
$name = "Alice"
$age = 30
# Print variables
Write-Output "Name: $name, Age: $age"
package main
import "fmt"
const Pi = 3.14159
func main() {
fmt.Printf("Value of Pi: %.5f\n", Pi)
}
# 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!
// 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))
}
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++
}
}
-- 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
-- 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
#!/usr/bin/perl
use strict;
use warnings;
eval {
die "An error occurred!";
};
if ($@) {
print "Caught error: $@\n";
}
-- Math operations
local x = math.sqrt(16)
local y = math.pi * 2
print("Square root of 16:", x)
print("2 * pi:", y)
-- Global variable
globalVar = "I'm global!"
-- Local variable
local localVar = "I'm local!"
print(globalVar)
print(localVar)
-- 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())
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)
}
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")
}
(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!
#!/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";
# Use a pipeline to filter processes
Get-Process | Where-Object { $_.CPU -gt 100 } | Select-Object -Property Name, CPU
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"])
}
-- 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]
; Define a function
(defun greet (name)
(format t "Hello, ~a!~%" name))
; Call the function
(greet "Alice") ; Prints: Hello, Alice!
(setq x 10) ; Set x to 10
(setq y (+ x 20)) ; y becomes 30
(print y) ; Prints 30
import Lean.Data.Json
-- Parse JSON
def parseJson : Option Lean.Json :=
Lean.Json.parse "{ \"name\": \"Lean\", \"version\": 4 }"
#eval parseJson
-- 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))
-- 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]
-- Working with tuples
def pair : Nat × String := (42, "Hello")
#eval pair.1 -- Output: 42
#eval pair.2 -- Output: "Hello"
#!/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";
}
-- 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]
-- 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)
-- 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
#!/usr/bin/perl
use strict;
use warnings;
my $multiline = <<"END";
This is a
multi-line
string in Perl.
END
print $multiline;
(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.
; Symbols
(setq my-symbol 'hello)
(eq my-symbol 'hello) ; Returns T
; Keywords
(eq :key :key) ; Returns T
; Recursive function to calculate factorial
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
(factorial 5) ; Returns 120
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
#!/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";
}
; Local bindings with `let`
(let ((x 5)
(y 10))
(+ x y)) ; Returns 15
-- 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
-- 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
-- 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
-- MyModule.hs
module MyModule (greet) where
greet :: String -> String
greet name = "Hello, " ++ name ++ "!"
-- Main.hs
import MyModule
main :: IO ()
main = putStrLn (greet "Alice")
-- 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]
-- 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"
#!/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";
-- Lambda function to square a number
square = \x -> x * x
main :: IO ()
main = print (square 5) -- Output: 25
% Define and use an anonymous function
square = @(x) x^2;
result = square(5);
disp(['Square of 5: ', num2str(result)]);
#!/usr/bin/perl
use strict;
use warnings;
use Math::Complex;
my $result = Math::Complex::sqrt(-4);
print "Square root of -4: $result\n";
; 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!
; 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)
% 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;
-- Define a function
square :: Int -> Int
square x = x * x
-- Call the function
result :: Int
result = square 4
; 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)))
-- 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
-- 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
% 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
-- Recursive factorial function
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)
main :: IO ()
main = print (factorial 5) -- Output: 120
-- 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)))
-- Lambda expression to double a number
def double := fun x : Nat => x * 2
#eval double 4 -- Output: 8
---
environment: development
debug: true
---
environment: production
debug: false
employees:
- name: Bob
position: Manager
- name: Carol
position: Developer
- name: Eve
position: Designer
-- Infinite list of numbers
numbers = [1..]
-- Take the first 5 numbers
main :: IO ()
main = print (take 5 numbers) -- Output: [1, 2, 3, 4, 5]
#!/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";
}
% 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
#!/bin/bash
# Define a function
greet() {
local name=$1
echo "Hello, $name!"
}
# Call the function
greet "Alice"
greet "Bob"
#!/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
#!/bin/bash
# Declare variables
name="Alice"
age=25
# Print variables
echo "Name: $name"
echo "Age: $age"
#!/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!"
server: &server_defaults
host: localhost
port: 8080
environments:
development:
<<: *server_defaults
debug: true
production:
<<: *server_defaults
debug: false
port: 80
custom_types:
timestamp: !!timestamp "2023-10-25T10:30:00Z"
binary_data: !!binary |
VGhpcyBpcyBhIHRlc3Qgc3RyaW5nLg==
integer_as_string: !!str 42
(setq my-plist '(:name "Alice" :age 30))
; Access properties
(getf my-plist :name) ; Returns "Alice"
(getf my-plist :age) ; Returns 30
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
#!/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";
#!/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";
}
; 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"
description: >
This is a long description
that spans multiple lines.
note: |
This is a block literal.
Line breaks are preserved here.
-- Simple arithmetic
x = 5 + 3
y = x * 2
-- Print a value
main :: IO ()
main = putStrLn ("The result is: " ++ show y)
; Basic arithmetic
(+ 1 2 3) ; Addition
(* 2 3 4) ; Multiplication
(- 10 3 2) ; Subtraction
; Catch and handle errors
(handler-case
(/ 1 0) ; Division by zero
(division-by-zero ()
(print "Cannot divide by zero!")))
-- 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
-- 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
-- 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]
#!/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";
% 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
-- Reading and writing to a file
main :: IO ()
main = do
writeFile "example.txt" "Hello, Haskell!"
content <- readFile "example.txt"
putStrLn content
users: [
{name: Alice, age: 25},
{name: Bob, age: 30},
{name: Charlie, age: 35}
]
-- 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
-- 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)
-- 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
---
app_name: ExampleApp
version: 1.0.0
dependencies:
- name: lib1
version: 2.1.0
- name: lib2
version: 3.3.7
...
; 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)
#!/usr/bin/perl
use strict;
use warnings;
print "Hello, World!\n";
#!/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
#!/bin/bash
# Prompt the user for input
read -p "Enter your name: " user_name
echo "Welcome, $user_name!"
#!/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
#!/usr/bin/perl
use strict;
use warnings;
# Run a system command
my $output = `ls -l`;
print "Command output:\n$output\n";
#!/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";
% 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)]);
% 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);
defaults: &default_settings
log_level: debug
timeout: 30
development:
<<: *default_settings
debug_mode: true
production:
<<: *default_settings
log_level: error
% 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)]);
x = 10;
if x > 0
disp('x is positive');
elseif x == 0
disp('x is zero');
else
disp('x is negative');
end
boolean_value: true
integer_value: 42
float_value: 3.14
null_value: null
colors: [red, green, blue]
dimensions: {width: 1920, height: 1080}
#!/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
? [first_key, second_key]
: value for complex key
? |
Multiline
Key
: Multiline Value
#!/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"
#!/bin/bash
# Get the current date and time
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "Current time: $current_time"
#!/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
name: John Doe
age: 30
email: johndoe@example.com
person:
name: Alice
address:
street: 123 Main St
city: Springfield
zip: 12345
# 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
shopping_list:
- apples
- bananas
- oranges
(* Simple arithmetic *)
let x = 5 + 3
let y = x * 2
(* Print a value *)
print_endline ("The result is: " ^ string_of_int y)
(* 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)))
% 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.
(* 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
% Facts about lists
member(X, [X|_]).
member(X, [_|Tail]) :- member(X, Tail).
% Query: Is 3 in the list?
% ?- member(3, [1, 2, 3, 4]).
% Facts
person(john, male).
person(mary, female).
% Query: Who is a male?
% ?- person(X, male).
<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>
<?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>
<?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>
<?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>
(* 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))
(ns my-app.core)
(defn say-hello []
(println "Hello from my-app.core!"))
(say-hello)
(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"]])))
% Facts
likes(john, pizza).
likes(john, pasta).
likes(mary, pizza).
% Query: What does John like?
% ?- likes(john, X).
% Query: Who likes pizza?
% ?- likes(_, pizza).
<?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>
(* 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
(* Use ref for mutable state *)
let counter = ref 0
let () =
counter := !counter + 1;
Printf.printf "Counter: %d\n" !counter
;; 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)
;; A simple function
(defn greet [name]
(str "Hello, " name "!"))
;; Call the function
(greet "Alice")
% Facts
color(red).
color(blue).
color(green).
% Query: Generate all colors
% ?- color(X).
% Rules
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
% Query: Who are Alice's grandparents?
% ?- grandparent(X, alice).
% Meta-predicate example
apply_twice(Predicate, Arg) :-
call(Predicate, Arg),
call(Predicate, Arg).
% Query: Apply write/1 twice
% ?- apply_twice(write, 'Hello!').
% Cut example
max(A, B, A) :- A >= B, !.
max(_, B, B).
% Query: What is the maximum of 3 and 7?
% ?- max(3, 7, Result).
<?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>
: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;
}/* 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;
}
# 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"]
# 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"]
# 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!"]
(defn factorial [n]
(if (<= n 1)
1
(* n (factorial (dec n)))))
(factorial 5) ;; 120
<?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>
# 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"]
(ns app.core
(:require ["dart:io" :as io]))
(defn main []
(io/print "Hello from ClojureDart!"))
(* 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
(* Define a lazy value *)
let lazy_value = lazy (2 + 2)
let () =
Printf.printf "Value: %d\n" (Lazy.force lazy_value)
(ns app.core)
;; Print to the browser console
(js/console.log "Hello, ClojureScript!")
% Unification
same(X, X).
% Query: Are 3 and 3 the same?
% ?- same(3, 3).
% Sort a list
sort_list(Unsorted, Sorted) :- msort(Unsorted, Sorted).
% Query: Sort [3, 1, 2, 4]
% ?- sort_list([3, 1, 2, 4], Result).
/* 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;
}
{
"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"
}(* 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
% Facts
parent(john, mary).
parent(mary, alice).
% Query: Who are Mary's parents?
% ?- parent(X, mary).
<!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>
(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
;; Calling a JavaScript function
(.log js/console "This is JavaScript interop")
;; Accessing object properties
(defn get-element-by-id [id]
(.getElementById js/document id))
% 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).
<?xml version="1.0" encoding="UTF-8"?>
<code>
<![CDATA[
<script>
console.log("This is raw JavaScript inside CDATA");
</script>
]]>
</code>
% 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).
<?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>
# 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
% 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).
/* 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;
}
/* 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));
}
/* 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;
}
# 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
# 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
(* 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)
(* 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"
(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))))
% 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!').
<?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>
% String operations
concatenate(Str1, Str2, Result) :- atom_concat(Str1, Str2, Result).
% Query: Concatenate 'hello' and 'world'
% ?- concatenate('hello', 'world', Result).
# 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"]
(* 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
(* 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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE greeting [
<!ELEMENT greeting (#PCDATA)>
]>
<greeting>Hello, World!</greeting>
# Base image
FROM alpine:latest
# Change shell to Bash
SHELL ["/bin/bash", "-c"]
# Run a Bash script
RUN echo "Hello from Bash!"
# Base image
FROM node:16 AS base
# Add ONBUILD instructions
ONBUILD COPY . /app
ONBUILD RUN npm install
ONBUILD CMD ["node", "index.js"]
(->> [1 2 3 4]
(filter odd?)
(map #(* % %))) ;; (1 9)
(-> {:a 1 :b 2}
(assoc :c 3)
(dissoc :a)) ;; {:b 2, :c 3}
;; 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))
(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!")})}))}))
% 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).
% 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).
<?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>
/* 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;
}
# 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
(defmacro unless [condition & body]
`(if (not ~condition)
(do ~@body)))
(unless false
(println "Condition is false!"))
# 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
# 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
(* 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))
% 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]).
/* 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);
}
/* 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;
}
/* Responsive design with media queries */
@media (max-width: 600px) {
.container {
padding: 10px;
font-size: 14px;
}
#header {
font-size: 20px;
}
}
# 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"]
# 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/*
(* 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"
// 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.
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
class Person(val name: String)
object Person {
def apply(name: String): Person = new Person(name)
}
val bob = Person("Bob")
println(bob.name) // Output: Bob
// Define a function
def square(x: Int): Int = x * x
// Call the function
println(square(4)) // Output: 16
# 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
# 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"}))
# 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
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;
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;
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;
-- 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);
-- 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;
-- Update rows conditionally
UPDATE employees
SET salary = salary * 1.1
WHERE position = 'Developer';
-- Delete rows with a condition
DELETE FROM employees
WHERE salary < 50000;
-- Pivoting data (MySQL example with JSON_ARRAYAGG)
SELECT
department_id,
JSON_ARRAYAGG(name) AS employee_names
FROM
employees
GROUP BY
department_id;
-- 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);
<?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();
}
?>
<?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";
}
?>
<?php
$name = "Alice"; // String
$age = 30; // Integer
$price = 19.99; // Float
$isAvailable = true; // Boolean
echo "Name: $name, Age: $age, Price: $price, Available: $isAvailable";
?>
# 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]
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$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")
}
// 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
}
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// 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!
model DiscreteSystem
discrete Real counter(start=0);
equation
when sample(0, 1) then
counter = pre(counter) + 1;
end when;
end DiscreteSystem;
@book{latexcompanion,
author = {Frank Mittelbach and Michel Goossens},
title = {The LaTeX Companion},
year = {2004},
publisher = {Addison-Wesley}
}<?php
echo "Current date: " . date("Y-m-d");
echo "Current time: " . date("H:i:s");
?>
# Spawn a new process
spawn(fn -> IO.puts("Hello from a new process!") end)
\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}-- 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;
-- 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;
<?php
session_start();
$_SESSION['username'] = 'Alice';
echo "Session username: " . $_SESSION['username'];
?>
# Simple arithmetic
x = 5 + 3
y = x * 2
# String interpolation
name = "Alice"
greeting = "Hello, #{name}!"
IO.puts(greeting)
# Using the pipe operator
list = [1, 2, 3, 4]
list
|> Enum.map(&(&1 * 2))
|> Enum.filter(&(&1 > 4))
|> IO.inspect() # Output: [6, 8]
# 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"]
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;
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;
-- 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;
-- 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);
<?php
try {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "Cleanup resources";
}
?>
// Using an anonymous function
val increment = (x: Int) => x + 1
println(increment(5)) // Output: 6
// Print to the console
println("Hello, Scala!")
// Simple arithmetic
val x = 5 + 3
val y = x * 2
println(s"The result is: $y")
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
# 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
<?php
// Simple PHP script
echo "Hello, World!";
?>
<?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;
?>
// 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
\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}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;
\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}<?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();
?>
lazy val expensiveComputation = {
println("Computing...")
42
}
println("Before accessing lazy val")
println(expensiveComputation) // Computes and prints 42defmodule 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
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
-- 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 ;
<?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";
}
?>
<?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];
?>
// 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)
# Define and access tuples
tuple = {:ok, "Success"}
IO.inspect(elem(tuple, 1)) # Output: "Success"
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
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;
-- 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;
-- 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;
<?php
$pattern = "/^hello/i";
$text = "Hello, World!";
if (preg_match($pattern, $text)) {
echo "Pattern matches!";
}
?>
// Immutable variable
val immutableVar = "I can't change"
// Mutable variable
var mutableVar = "I can change"
mutableVar = "I've changed!"
println(immutableVar)
println(mutableVar)
function add
input Real a;
input Real b;
output Real result;
algorithm
result := a + b;
end add;
-- 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"}';
// 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)
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;
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;
<?php
// content.php
// <?php
// echo "This is included content.";
// Include a file
include 'content.php';
// Require a file
require 'content.php';
?>
<?php
$number = 10;
if ($number > 0) {
echo "Positive";
} elseif ($number < 0) {
echo "Negative";
} else {
echo "Zero";
}
?>
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
val age = 25
if (age < 18) {
println("Minor")
} else if (age >= 18 && age < 65) {
println("Adult")
} else {
println("Senior")
}
defmodule Recursion do
def factorial(0), do: 1
def factorial(n), do: n * factorial(n - 1)
end
IO.puts(Recursion.factorial(5)) # Output: 120
# 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
-- Grouping data with HAVING
SELECT position, COUNT(*) AS num_employees, MAX(salary) AS max_salary
FROM employees
GROUP BY position
HAVING MAX(salary) > 80000;
# 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
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;
\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}\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}<?php
// Simple function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
?>
model SimpleModel
parameter Real a = 2.0;
parameter Real b = 3.0;
Real x;
equation
x = a + b;
end SimpleModel;
<?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'];
?>
import scala.util.Try
val result = Try {
10 / 0
}.recover {
case _: ArithmeticException => "Division by zero!"
}
println(result) // Output: Division by zero!
model DynamicSimulation
Real x(start=0);
Real y;
equation
der(x) = sin(time);
y = cos(time);
end DynamicSimulation;
// 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