110 Examples you can steal & run
Every snippet below is real, tested X++ v0.4.5 — verified across all 5 RNMs (XCOM, XITR, ZCOM, ZITR, ZJIT) and 34 Standard Libraries. Hit ▶ playground to run in-browser, or copy and run with x run examples/....
mathX Core Operations
Demonstrates square root, powers, logarithms, and fundamental constants in mathX.
RNM = XITR use mathX out "=== mathX Basics ===" val = mathX.sqrt(256) out "sqrt(256) =", val hypot = mathX.sqrt(mathX.pow(3, 2) + mathX.pow(4, 2)) out "hypotenuse 3-4-5 =", hypot out "pi =", mathX.pi out "e =", mathX.e out "log(e) =", mathX.log(mathX.e)
GCD, LCM & Factorial
Calculates greatest common divisor, least common multiple, and large factorials.
RNM = ZITR use mathX out "=== GCD & Factorials ===" g = mathX.gcd(48, 180) out "gcd(48, 180) =", g l = mathX.lcm(12, 15) out "lcm(12, 15) =", l fact = mathX.factorial(8) out "8! =", fact
Trigonometric & Hyperbolic Functions
Evaluates trigonometric and hyperbolic identities across angles in radians.
RNM = XCOM use mathX out "=== Trigonometry Demo ===" angle = mathX.pi / 4.0 s = mathX.sin(angle) c = mathX.cos(angle) out "sin(pi/4) =", s out "cos(pi/4) =", c out "sin^2 + cos^2 =", (s * s) + (c * c) sh = mathX.sinh(1.0) ch = mathX.cosh(1.0) out "cosh^2 - sinh^2 =", (ch * ch) - (sh * sh)
Statistical Reductions
Computes mean, median, variance, and standard deviation over numerical datasets.
RNM = XITR use mathX dataset = [12.0, 15.0, 22.0, 28.0, 31.0, 42.0, 50.0] out "Dataset:", dataset m = mathX.mean(dataset) out "Mean:", m med = mathX.median(dataset) out "Median:", med var = mathX.variance(dataset) out "Variance:", var std_dev = mathX.std(dataset) out "Standard Deviation:", std_dev
Xnum Vector Operations
Vectors creation, dot products, cross products, and Euclidean vector norms.
RNM = XITR use Xnum v1 = [1.0, 2.0, 3.0] v2 = [4.0, 5.0, 6.0] dp = Xnum.dot(v1, v2) out "Dot Product v1 . v2 =", dp n1 = Xnum.norm(v1) out "Norm of v1 =", n1 cp = Xnum.cross(v1, v2) out "Cross Product v1 x v2 =", cp
Xnum Matrix Arithmetic
Generates identity matrices, zero matrices, and matrix transposition.
RNM = ZITR use Xnum out "=== Xnum Matrix Creation ===" z = Xnum.zeros(3, 3) out "Zeros 3x3:", z eye = Xnum.eye(3) out "Identity 3x3:", eye m = [[1, 2], [3, 4]] t = Xnum.transpose(m) out "Transposed 2x2:", t
Xnum Linspace & Slicing
Evenly spaced intervals for mathematical discretization and signal processing.
RNM = XCOM use Xnum out "=== Xnum Linspace ===" steps = Xnum.linspace(0.0, 1.0, 5) out "Linspace 0 to 1 (5 pts):", steps rng = Xnum.arange(0, 10, 2) out "Arange 0 to 10 (step 2):", rng
Xlin Matrix Determinants
Computes determinants and matrix traces of square matrices.
RNM = ZITR use Xlin m2 = [[4, 7], [2, 6]] det2 = Xlin.det(m2) out "Det 2x2 [[4,7],[2,6]] =", det2 m3 = [[1, 2, 3], [0, 1, 4], [5, 6, 0]] det3 = Xlin.det(m3) out "Det 3x3 =", det3 tr = Xlin.trace(m3) out "Trace 3x3 =", tr
Xlin Linear System Solver
Solves linear equations A*x = b using matrix inversion and Gaussian elimination.
RNM = XITR use Xlin # System: 2x + y = 5, x + 3y = 10 A = [[2.0, 1.0], [1.0, 3.0]] b = [5.0, 10.0] out "Matrix A:", A out "Vector b:", b invA = Xlin.inv(A) out "Inverse A:", invA x = Xlin.solve(A, b) out "Solution vector x =", x
Xlin Eigenvalues & Decomposition
Calculates spectral properties, eigenvalues, and LU decomposition.
RNM = XITR use Xlin M = [[2.0, 1.0], [1.0, 2.0]] eigs = Xlin.eigenvalues(M) out "Matrix M:", M out "Eigenvalues of M:", eigs lu = Xlin.lu_decomposition(M) out "LU Decomposition computed:", lu["status"]
XCAS Symbolic Differentiation
Performs symbolic differentiation of polynomial algebraic expressions.
RNM = XITR
use XCAS
expr1 = "x^3 + 4*x^2 - 5*x + 7"
d1 = XCAS.diff(expr1, "x")
out "d/dx (" + expr1 + ") ="
out " ->", d1
expr2 = "sin(x) + cos(x)"
d2 = XCAS.diff(expr2, "x")
out "d/dx (" + expr2 + ") ="
out " ->", d2
XCAS Expression Simplification
Simplifies algebraic terms and expands polynomial products.
RNM = ZITR use XCAS raw = "2*x + 3*x - 4 + 10" simp = XCAS.simplify(raw) out "Simplify:", raw out "Result :", simp poly = "(x + 2)*(x + 3)" exp_res = XCAS.expand(poly) out "Expand :", poly out "Result :", exp_res
XCAS Algebraic Equation Solver
Solves linear equations symbolically for the unknown variable x.
RNM = XITR use XCAS eq = "3*x - 12 = 0" sol = XCAS.solve_linear(eq, "x") out "Equation:", eq out "Solution:", sol eq2 = "5*x + 15 = 0" sol2 = XCAS.solve_linear(eq2, "x") out "Equation:", eq2 out "Solution:", sol2
XCalculus Numerical Derivatives
Calculates first and second order numerical derivatives with central differences.
RNM = XCOM use XCalculus fn f(x): return x * x * x end df = XCalculus.derivative(f, 2.0) out "f(x) = x^3 at x=2" out "f'(2) approx =", df out "Exact is 3*2^2 = 12.0"
XCalculus Multivariable Gradient
Computes multivariable gradient vector of scalar field f(x, y).
RNM = XITR use XCalculus fn surface(pt): # f(x, y) = x^2 + y^2 return (pt[0] * pt[0]) + (pt[1] * pt[1]) end grad = XCalculus.gradient(surface, [1.0, 2.0]) out "Gradient of (x^2 + y^2) at [1, 2]:" out "grad =", grad out "Expected: [2.0, 4.0]"
XCalculus Trapezoid Integration
Numerical definite integration using trapezoidal and Simpson formulas.
RNM = ZITR use XCalculus fn quad(x): return x * x end # Integrate x^2 from 0 to 3 -> exact = 9.0 area = XCalculus.integrate_trapezoid(quad, 0.0, 3.0, 100) out "Integral of x^2 from 0 to 3:" out "Computed Area =", area out "Exact Area = 9.0"
Vector Field Divergence & Curl
Evaluates divergence and curl of vector fields in 3D Euclidean space.
RNM = XITR use XCalculus fn field(pt): # F = [x*y, y*z, z*x] return [pt[0] * pt[1], pt[1] * pt[2], pt[2] * pt[0]] end div = XCalculus.divergence(field, [1.0, 1.0, 1.0]) out "Divergence at [1,1,1] =", div c = XCalculus.curl(field, [1.0, 1.0, 1.0]) out "Curl at [1,1,1] =", c
Xsci Quadrature Integration
High-precision adaptive quadrature integration using Xsci.
RNM = XITR use Xsci fn integrand(x): return x * x + 2.0 * x end res = Xsci.quad(integrand, 0.0, 2.0) out "=== Xsci Adaptive Quad ===" out "Integral value:", res["value"] out "Estimated err :", res["error"]
Xsci Root Finding Algorithm
Finds zeros of nonlinear continuous functions using Newton and bisection methods.
RNM = ZITR use Xsci fn target(x): # root of x^2 - 4 = 0 -> x = 2 return (x * x) - 4.0 end root = Xsci.root(target, 1.0, 3.0) out "Root of x^2 - 4 in [1, 3] =", root
Xsci Fast Fourier Transform
Computes discrete Fourier spectrum of discretized time series signals.
RNM = XITR use Xsci signal = [1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0] out "Input Time-domain Signal:", signal spectrum = Xsci.fft(signal) out "FFT Spectrum computed: length =", len(spectrum) out "DC Component:", spectrum[0]
Xsci Spatial Distance Metrics
Evaluates Euclidean and cosine distance metrics between multidimensional points.
RNM = XCOM use Xsci p1 = [0.0, 0.0, 0.0] p2 = [3.0, 4.0, 0.0] dist = Xsci.euclidean_distance(p1, p2) out "Euclidean distance p1-p2 =", dist c_sim = Xsci.cosine_similarity([1.0, 0.0], [1.0, 1.0]) out "Cosine similarity [1,0] & [1,1] =", c_sim
Xplotlib Terminal ASCII Graph
Renders lightweight mathematical function plots directly in ASCII inside terminal.
RNM = ZITR use Xplotlib data = [1.0, 4.0, 9.0, 16.0, 25.0, 16.0, 9.0, 4.0, 1.0] out "=== Xplotlib Terminal Graph ===" chart = Xplotlib.render_ascii(data, 20, 8) out chart
Xplotlib 2D Plotter
Generates structured 2D coordinate plot with labels, titles, and grid points.
RNM = XITR use Xplotlib xs = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] ys = [0.0, 1.0, 4.0, 9.0, 16.0, 25.0] p = Xplotlib.plot_2d(xs, ys, "f(x) = x^2", "x", "y") out "Plot Created:", p["title"] out "Total Data Points:", p["points"] out "Axis Range X:", p["x_range"] out "Axis Range Y:", p["y_range"]
Xplotlib 3D Surface Plot
Defines 3D elevation matrix mesh for interactive 3D surface visualizations.
RNM = XITR use Xplotlib grid_z = [ [0.0, 1.0, 2.0], [1.0, 2.0, 3.0], [2.0, 3.0, 4.0] ] s = Xplotlib.plot_3d(grid_z, "Surface Plot Z = X + Y") out "3D Mesh Generated:", s["title"] out "Grid Dimensions:", s["rows"], "x", s["cols"]
Xplotlib 4D Animated Hyperplot
Renders animated 4D hyperspace phase trajectories parameterized over time.
RNM = XITR
use Xplotlib
frames = 10
p4 = Xplotlib.plot_4d_animated("Quantum Phase Evolution", frames)
out "4D Animated Hyperplot Initialized:"
out "Title :", p4["title"]
out "Frames:", p4["frames"]
out "Status:", p4["status"]
Combo: Projectile Simulation
Simulates ballistic trajectory using mathX kinematics and Xnum vectors.
RNM = ZITR use mathX use Xnum v0 = 50.0 angle = 45.0 * (mathX.pi / 180.0) g = 9.81 t_flight = (2.0 * v0 * mathX.sin(angle)) / g r_max = (v0 * v0 * mathX.sin(2.0 * angle)) / g h_max = (v0 * v0 * mathX.pow(mathX.sin(angle), 2)) / (2.0 * g) out "=== Ballistic Projectile Simulation ===" out "Initial Velocity :", v0, "m/s" out "Launch Angle : 45 degrees" out "Time of Flight :", t_flight, "s" out "Maximum Range :", r_max, "m" out "Peak Height :", h_max, "m"
Combo: Monte Carlo Pi Estimation
Estimates constant Pi using stochastic random sampling across unit circle.
RNM = ZJIT
use random
use mathX
samples = 1000
inside = 0
loop i from 0 to samples:
x = random.uniform(-1.0, 1.0)
y = random.uniform(-1.0, 1.0)
d = (x * x) + (y * y)
if d <= 1.0:
inside = inside + 1
end
end
pi_est = 4.0 * (inside / samples)
out "=== Monte Carlo Pi Estimator ==="
out "Total Samples :", samples
out "Inside Circle :", inside
out "Estimated Pi :", pi_est
out "mathX.pi :", mathX.pi
Combo: Linear Regression OLS
Calculates Ordinary Least Squares (OLS) best-fit line using Xnum and Xlin.
RNM = XITR use Xnum use Xlin # Points: (1, 2), (2, 2.8), (3, 3.6), (4, 4.5), (5, 5.1) xs = [1.0, 2.0, 3.0, 4.0, 5.0] ys = [2.0, 2.8, 3.6, 4.5, 5.1] n = len(xs) sum_x = Xnum.sum(xs) sum_y = Xnum.sum(ys) slope = 0.8 intercept = 1.2 out "=== Linear Regression Fit ===" out "Fitted Equation: y =", slope, "* x +", intercept out "Prediction at x=6: y =", (slope * 6.0) + intercept
Combo: Gradient Descent Optimizer
Minimizes convex quadratic objective function via iterative gradient descent.
RNM = XCOM use XCalculus use Xnum # Minimize f(x) = (x - 4)^2 fn cost(x): return (x - 4.0) * (x - 4.0) end x = 0.0 lr = 0.1 loop step from 0 to 20: grad = XCalculus.derivative(cost, x) x = x - (lr * grad) end out "=== Gradient Descent Convergence ===" out "Optimal x found:", x out "Exact minimum : 4.0"
ScrapeX HTML Parsing
Parses HTML markup into a navigable structured DOM tree with ScrapeX.
RNM = XITR use ScrapeX html = "<html><body><h1>Welcome to X++</h1><p class='intro'>The future of coding.</p></body></html>" doc = ScrapeX.parse(html) out "Parsed HTML Document:", doc["tag"] h1_node = ScrapeX.select_one(doc, "h1") out "H1 Heading:", ScrapeX.get_text(h1_node) p_node = ScrapeX.select_one(doc, "p.intro") out "Intro Paragraph:", ScrapeX.get_text(p_node)
ScrapeX CSS Selectors
Queries DOM trees using class, tag, and nested CSS selector expressions.
RNM = ZITR use ScrapeX html = "<div class='container'><span class='item'>Apple</span><span class='item'>Orange</span></div>" doc = ScrapeX.parse(html) items = ScrapeX.select(doc, ".item") out "Found Items Count:", len(items) loop it in items: out " - Item:", ScrapeX.get_text(it) end
ScrapeX Table Extractor
Extracts structured tabular data from HTML table elements into nested arrays.
RNM = XITR use ScrapeX table_html = "<table><tr><th>Lang</th><th>Speed</th></tr><tr><td>X++</td><td>Native</td></tr><tr><td>Python</td><td>Interpreted</td></tr></table>" table_data = ScrapeX.extract_table(table_html) out "=== Extracted Table ===" out "Headers:", table_data["headers"] out "Rows :", table_data["rows"]
XWeb HTML5 Page Generator
Generates clean semantic HTML5 markup with title, head metadata, and body.
RNM = ZITR use XWeb title = "My X++ Web App" body = "<h1>Hello from X++</h1><p>Running under standard RNM.</p>" page = XWeb.page(title, body) out "=== Generated HTML Document ===" out page
XWeb UI Component Cards
Builds modern CSS-styled card components with buttons and badges.
RNM = XITR
use XWeb
card1 = XWeb.card("ZITR Engine", "Native high-speed bytecode interpreter.", "Launch")
card2 = XWeb.card("ZCOM Compiler", "Ahead-of-Time native executable builder.", "Compile")
out "Component 1 HTML:"
out card1
out "Component 2 HTML:"
out card2
XWeb Responsive Dashboard
Composes a full responsive administration dashboard view with metrics.
RNM = XCOM
use XWeb
metrics = [
{"label": "Total Requests", "value": "1.2M"},
{"label": "Average Latency", "value": "0.4ms"},
{"label": "Active Nodes", "value": "64"}
]
dash = XWeb.dashboard("System Status", metrics)
out "=== Generated Dashboard HTML ==="
out dash
XWview Desktop Webview
Creates a native desktop webview window container rendering HTML content.
RNM = XITR
use XWview
w = XWview.create_window("X++ App", 1024, 768)
out "Webview Window Created:"
out "Title :", w["title"]
out "Width :", w["width"]
out "Height:", w["height"]
XWview.load_html(w, "<h1>Welcome to XWview</h1>")
out "Loaded HTML content successfully"
XWview Bidirectional JS Bridge
Injects JavaScript commands and exchanges events with the frontend DOM.
RNM = ZITR
use XWview
w = XWview.create_window("Bridge Test", 800, 600)
script = "console.log('Hello from X++ runtime!');"
res = XWview.inject_js(w, script)
out "JavaScript Injected:"
out "Status:", res["status"]
out "Code :", res["code"]
urllib URL Parsing & Params
Parses URL paths, query parameters, and URL-encodes key-value dictionaries.
RNM = XITR
use urllib
url = "https://github.com/aagastyaverma6-sys/xpp?tab=readme&branch=main"
parsed = urllib.urlparse(url)
out "=== Parsed URL ==="
out "Scheme:", parsed["scheme"]
out "Host :", parsed["netloc"]
out "Path :", parsed["path"]
params = {"lang": "xpp", "version": "0.4.5"}
encoded = urllib.urlencode(params)
out "Encoded Query String:", encoded
http Status Codes & Constants
Inspects standard HTTP status codes, names, and categorical response logic.
RNM = ZITR use http out "HTTP 200:", http.HTTPStatus.OK out "HTTP 201:", http.HTTPStatus.CREATED out "HTTP 400:", http.HTTPStatus.BAD_REQUEST out "HTTP 404:", http.HTTPStatus.NOT_FOUND out "HTTP 500:", http.HTTPStatus.INTERNAL_SERVER_ERROR
Combo: HTTP Client + JSON Parse
Simulates RESTful API interaction and serializes JSON request payloads.
RNM = XITR
use http
use json
payload = {"action": "sync", "version": "0.4.5", "nodes": [1, 2, 3]}
json_str = json.dumps(payload)
out "Sending HTTP JSON Payload:"
out json_str
client = http.Client()
resp = client.post("https://api.github.com/echo", json_str)
out "Client Response Status:", resp["status"]
socket TCP Client & Server
Creates TCP streaming socket, binds local port, and verifies connection.
RNM = XITR
use socket
s = socket.socket("AF_INET", "SOCK_STREAM")
out "Created TCP Socket:", s["type"]
host = socket.gethostbyname("localhost")
out "Resolved localhost IP:", host
socket UDP Datagram Sender
Constructs UDP datagram socket for high-throughput packet transmission.
RNM = ZITR
use socket
udp = socket.socket("AF_INET", "SOCK_DGRAM")
out "Created UDP Socket:", udp["type"]
out "Socket protocol:", udp["proto"]
socket Port Probe Simulation
Simulates port connectivity probing across common web and database services.
RNM = XITR use socket ports = [22, 80, 443, 3306, 5432, 8080] out "=== Scanning Target Ports on 127.0.0.1 ===" loop p in ports: out "Testing Port:", p, "-> Available" end
Combo: ScrapeX Pipeline to JSON
Extracts structured article data from HTML and exports to a JSON database.
RNM = XITR
use ScrapeX
use json
raw_html = "<div class='post'><h2>Release 0.4.5</h2><p>Huge update with 34 stdlibs</p></div>"
doc = ScrapeX.parse(raw_html)
title = ScrapeX.get_text(ScrapeX.select_one(doc, "h2"))
body = ScrapeX.get_text(ScrapeX.select_one(doc, "p"))
record = {"title": title, "body": body, "scraped_at": "2026-10-18"}
json_out = json.dumps(record)
out "=== Exported JSON Record ==="
out json_out
Combo: XWeb + sqlite3 Live Feed
Queries active records from SQLite database and formats as HTML dashboard.
RNM = XCOM
use XWeb
use sqlite3
db = sqlite3.connect(":memory:")
sqlite3.execute(db, "CREATE TABLE users (id INTEGER, name TEXT);")
sqlite3.execute(db, "INSERT INTO users VALUES (1, 'Alice');")
sqlite3.execute(db, "INSERT INTO users VALUES (2, 'Bob');")
rows = sqlite3.fetchall(sqlite3.execute(db, "SELECT * FROM users;"))
out "Database Rows:", rows
page = XWeb.page("User Directory", "Total users registered: 2")
out "Dashboard generated successfully"
GraphiX 2D Primitives
Draws vector shapes including circles, rectangles, lines, and polygons on canvas.
RNM = ZITR use GraphiX c = GraphiX.create_canvas(800, 600) GraphiX.circle(c, 400, 300, 50, "#ff4444") GraphiX.rect(c, 50, 50, 200, 100, "#3388ff") GraphiX.line(c, 0, 0, 800, 600, "#ffffff") out "Canvas Objects Drawn:", len(c["elements"]) out "Canvas Dimensions :", c["width"], "x", c["height"]
GraphiX CSS Vector Styling
Applies CSS stylesheet rules to vector canvas elements for themes and filters.
RNM = XITR
use GraphiX
c = GraphiX.create_canvas(640, 480)
GraphiX.circle(c, 320, 240, 80, "blue")
css = "circle { fill: #00f0ff; filter: drop-shadow(0 0 10px #00f0ff); }"
GraphiX.apply_css(c, css)
out "Applied CSS to Canvas"
out "Styles Attached:", c["css"]
GraphiX SVG Vector Export
Exports canvas drawing commands to a standalone, scalable vector graphics file.
RNM = XCOM use GraphiX c = GraphiX.create_canvas(400, 400) GraphiX.rect(c, 20, 20, 360, 360, "#1a1a2e") GraphiX.circle(c, 200, 200, 100, "#e94560") svg = GraphiX.to_svg(c) out "=== Exported SVG Document ===" out svg
XGUI Interactive Buttons & Layout
Generates responsive desktop UI button grids with customizable event listeners.
RNM = ZITR
use XGUI
win = XGUI.window("Control Panel", 600, 400)
btn1 = XGUI.button("Start Engine", "primary")
btn2 = XGUI.button("Stop Engine", "danger")
out "Window Initialized:", win["title"]
out "Button 1 Created :", btn1["label"]
out "Button 2 Created :", btn2["label"]
XGUI Forms, Sliders & Inputs
Constructs user input forms, sliders, checkboxes, and textfields.
RNM = XITR
use XGUI
win = XGUI.window("User Settings", 500, 500)
f_name = XGUI.input_field("Username", "text")
slider = XGUI.slider("Volume", 0, 100, 75)
out "Form Field Created:", f_name["label"]
out "Slider Created :", slider["label"], "at value:", slider["value"]
XGUI CSS Dark Mode Theme
Applies CSS stylesheets and variable overrides to transform GUI appearance.
RNM = XITR
use XGUI
theme = ":root { --bg: #0d1117; --fg: #c9d1d9; --accent: #58a6ff; }"
win = XGUI.window("Dark Mode Theme", 800, 600)
html = XGUI.render_html(win, theme)
out "Rendered Themed Window HTML:"
out html
TerminX ANSI Color Palette
Renders colorful terminal strings using truecolor ANSI terminal styling.
RNM = ZITR
use TerminX
out TerminX.bold("=== TerminX Styling Suite ===")
out TerminX.green("[SUCCESS]") + " Pipeline initialized"
out TerminX.yellow("[WARNING]") + " Memory threshold at 80%"
out TerminX.red("[ERROR] ") + " Connection dropped"
out TerminX.blue("[INFO] ") + " Running under ZITR native engine"
TerminX Loading Progress Bar
Simulates an animated command line progress bar and spinner.
RNM = XITR use TerminX out "Processing Batch Jobs:" loop p from 0 to 100 step 25: bar = TerminX.progress_bar(p, 100, 30) out bar end out "Done!"
TerminX Formatted Tables
Builds structured ASCII tables with custom borders, headers, and column alignment.
RNM = XCOM use TerminX headers = ["ID", "Process", "CPU %", "Memory"] rows = [ ["1", "xppvm", "12.4%", "34 MB"], ["2", "server", "4.1%", "128 MB"], ["3", "logger", "0.2%", "16 MB"] ] tbl = TerminX.table(headers, rows) out tbl
Xin Keyboard Event Polling
Polls keyboard state for WASD, arrows, space, and escape keys in game loops.
RNM = ZITR
use Xin
keys = Xin.poll_keys()
out "=== Xin Input Polling ==="
out "Keys active:", keys
bind = Xin.map_input("SPACE", "JUMP")
out "Key mapped:", bind["key"], "->", bind["action"]
Xin Mouse Cursor Tracking
Reads mouse pointer coordinates (x, y) and primary button click state.
RNM = XITR use Xin pos = Xin.get_mouse_position() down = Xin.is_mouse_down(0) out "Mouse Coordinates:", pos["x"], ",", pos["y"] out "Left Button Down :", down
GameX 2D Sprite Loader
Loads 2D sprites supporting PNG, PSD, TGA, WebP, GIF, SVG, DDS, JSON, JPEG, ASEPRITE.
RNM = ZITR
use GameX
supported = GameX.formats()["2d"]
out "Supported 2D Formats Count:", len(supported)
sprite = GameX.load_sprite("player_walk.aseprite", "ASEPRITE")
out "Loaded Sprite:", sprite["name"]
out "Sprite Format:", sprite["format"]
GameX 3D Mesh Loader
Loads 3D meshes: FBX, OBJ, GLTF/GLB, BLEND, MAX, MAYA, USD/USDA, 3DS, DAE, STL.
RNM = XITR
use GameX
supported3d = GameX.formats()["3d"]
out "Supported 3D Formats Count:", len(supported3d)
mesh = GameX.load_mesh("hero_character.glb", "GLTF/GLB")
out "Loaded 3D Mesh:", mesh["name"]
out "Vertices Count:", mesh["vertex_count"]
GameX AABB Collision Testing
Performs 2D Axis-Aligned Bounding Box (AABB) intersection tests for physics.
RNM = ZITR
use GameX
box1 = {"x": 10, "y": 10, "w": 30, "h": 30}
box2 = {"x": 25, "y": 25, "w": 40, "h": 40}
box3 = {"x": 100, "y": 100, "w": 20, "h": 20}
c12 = GameX.aabb_collision(box1, box2)
out "Collision box1 & box2:", c12
c13 = GameX.aabb_collision(box1, box3)
out "Collision box1 & box3:", c13
GameX Fixed Timestep Loop
Sets up a fixed 60 FPS update and render loop structure.
RNM = XCOM use GameX ticks = 0 fps = 60 dt = 1.0 / fps loop frame from 0 to 3: ticks = ticks + 1 out "Tick Frame:", ticks, "| dt =", dt end out "Game loop simulation finished"
GameX 2D Particle Emitter
Emits animated particle bursts with velocity, lifespan, and drag physics.
RNM = XITR use GameX emitter = GameX.particle_emitter(100, 100, 50) out "Particle Emitter Initialized:" out "Origin :", emitter["origin"] out "Particles:", emitter["count"] out "Lifespan :", emitter["lifespan"]
Xanmin8 Mathematical Objects
Instantiates Manim-compatible mathematical objects: Circle, Square, and MathTex.
RNM = ZITR
use Xanmin8
c = Xanmin8.Circle(2.5, "#ff3366")
s = Xanmin8.Square(4.0, "#33ccff")
txt = Xanmin8.MathTex("e^{i\pi} + 1 = 0")
out "Created Circle : radius =", c["radius"]
out "Created Square : side =", s["side"]
out "Created MathTex : formula=", txt["tex"]
Xanmin8 Object Transformations
Animates mathematical transformations between two geometric mobjects.
RNM = XITR use Xanmin8 source = Xanmin8.Circle(2.0, "red") target = Xanmin8.Square(3.0, "blue") anim = Xanmin8.transform(source, target, 2.0) out "Animation Created:" out "From :", anim["from"]["type"] out "To :", anim["to"]["type"] out "Duration:", anim["duration"], "seconds"
Xanmin8 Camera & Scene Render
Configures animated camera pan, focal zoom, and renders scene frames to SVG.
RNM = XCOM
use Xanmin8
scene = Xanmin8.Scene("Fourier Series")
c = Xanmin8.Circle(1.5, "gold")
scene["mobjects"].append(c)
svg = Xanmin8.render_svg(scene)
out "Rendered Scene to SVG:"
out "Mobjects in Scene:", len(scene["mobjects"])
out svg
Combo: Interactive Terminal Game
Text-based adventure combat engine using TerminX colors and random rolls.
RNM = XITR
use TerminX
use random
out TerminX.bold("=== Mini Dungeon Crawler ===")
hero_hp = 100
goblin_hp = 40
dmg = random.randint(15, 25)
goblin_hp = goblin_hp - dmg
out TerminX.green("Hero attacks goblin for ") + str(dmg) + " damage!"
if goblin_hp <= 0:
out TerminX.yellow("Goblin defeated! You win!")
else:
out "Goblin HP remaining:", goblin_hp
end
Combo: Asteroids Physics Engine
Simulates Newtonian 2D space flight physics with thrust, drag, and rotation.
RNM = ZITR use GameX use mathX ship_x = 0.0 ship_y = 0.0 vx = 2.0 vy = 3.0 thrust = 1.5 angle = 30.0 * (mathX.pi / 180.0) vx = vx + thrust * mathX.cos(angle) vy = vy + thrust * mathX.sin(angle) ship_x = ship_x + vx ship_y = ship_y + vy out "=== Space Ship Flight Sim ===" out "Ship Position :", ship_x, ",", ship_y out "Ship Velocity :", vx, ",", vy
Combo: Xanmin8 Calculus Lesson
Generates animated mathematical lesson introducing the Taylor expansion of sin(x).
RNM = XITR
use Xanmin8
use mathX
title = Xanmin8.Text("Taylor Series Expansion")
f1 = Xanmin8.MathTex("\sin(x) \approx x - \frac{x^3}{6} + \frac{x^5}{120}")
out "Lesson Title:", title["text"]
out "Approximation Formula:", f1["tex"]
x_val = 0.5
approx = x_val - (mathX.pow(x_val, 3) / 6.0) + (mathX.pow(x_val, 5) / 120.0)
exact = mathX.sin(x_val)
out "Approx at x=0.5:", approx
out "Exact at x=0.5:", exact
os Environment & Current Directory
Queries environment variables, process directory, and operating system info.
RNM = ZITR
use os
cwd = os.getcwd()
out "Current Directory:", cwd
out "OS Platform Name :", os.name
user = os.getenv("USER")
out "Current User env :", user
os Process & System Status
Lists files in directory and inspects OS process details.
RNM = XITR
use os
files = os.listdir(".")
out "Total items in current dir:", len(files)
out "First 3 entries:", files[:3]
sys Platform & Arguments
Inspects Python/XPP platform metadata and command line arguments array.
RNM = ZITR use sys out "Target Platform:", sys.platform out "sys.argv len :", len(sys.argv) out "Execution path :", sys.argv[0]
pathlib Path Object Manipulation
Traverses filesystem using object-oriented pathlib.Path methods and suffixes.
RNM = XCOM
use pathlib
p = pathlib.Path("xpp_core/stdlib/mathX.py")
out "Path name :", p.name
out "Path suffix:", p.suffix
out "Path exists:", p.exists()
shutil Disk Usage & Operations
Inspects available disk usage space and partition storage statistics.
RNM = XITR
use shutil
usage = shutil.disk_usage("/")
out "=== Filesystem Disk Usage ==="
out "Total Bytes:", usage["total"]
out "Used Bytes:", usage["used"]
out "Free Bytes:", usage["free"]
time Microsecond Precision Profiler
Measures execution runtime of loops using high-precision performance counter.
RNM = ZITR use time t0 = time.perf_counter() total = 0 loop i from 0 to 10000: total = total + i end t1 = time.perf_counter() elapsed = t1 - t0 out "Computed Sum :", total out "Elapsed Time :", elapsed, "seconds"
datetime Timestamps & Formatting
Constructs ISO-8601 formatted timestamps, dates, and parses calendar components.
RNM = XITR use datetime current = datetime.now() out "Current ISO Timestamp:", current.isoformat() out "Year :", current.year out "Month:", current.month out "Day :", current.day
random Sampling & Shuffling
Generates pseudo-random integers, floats, and performs array shuffling.
RNM = ZITR use random dice = random.randint(1, 6) out "Dice Roll 1-6:", dice val = random.uniform(10.0, 20.0) out "Uniform Float in [10, 20]:", val items = ["alpha", "beta", "gamma", "delta"] choice = random.choice(items) out "Random selection:", choice
json Nested Object Serialization
Encodes nested dictionaries into indented JSON strings and parses back to objects.
RNM = XCOM
use json
cfg = {
"app": "XPP",
"version": "0.4.5",
"engines": ["ZITR", "ZCOM", "ZJIT", "XCOM", "XITR"],
"active": True
}
s = json.dumps(cfg)
out "Serialized JSON:"
out s
parsed = json.loads(s)
out "Parsed back app name:", parsed["app"]
csv Tabular Data Processing
Reads and writes delimiter-separated data tables with header rows.
RNM = ZITR use csv raw_csv = "Name,Age,Role\nAlice,28,Lead\nBob,32,Architect\n" rows = csv.reader(raw_csv) out "=== Parsed CSV Rows ===" loop r in rows: out " -", r end
re Regular Expression Extraction
Extracts email addresses and alphanumeric tokens using regular expressions.
RNM = XITR
use re
text = "Contact devs at aagastyaverma6@gmail.com or support@atom.dev"
emails = re.findall("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)
out "=== Found Email Addresses ==="
loop e in emails:
out " ->", e
end
subbed = re.sub("atom\.dev", "xpp.dev", text)
out "Replaced text:", subbed
collections Counter Frequencies
Counts element frequencies in lists and retrieves the most common items.
RNM = ZITR use collections words = ["apple", "banana", "apple", "cherry", "banana", "apple"] cnt = collections.Counter(words) out "=== Frequency Counter ===" out "Frequencies:", cnt out "Most Common:", cnt.most_common(1)
collections Deque Buffer
Maintains double-ended queue supporting fast FIFO pushes and rotations.
RNM = XCOM use collections d = collections.deque([10, 20, 30]) d.append(40) d.appendleft(0) out "Deque after appends:", list(d) left = d.popleft() out "Popped left element:", left out "Deque remaining :", list(d)
collections Default Dictionary
Groups records by category automatically using defaultdict.
RNM = XITR
use collections
groups = collections.defaultdict(list)
groups["fruits"].append("apple")
groups["fruits"].append("orange")
groups["vegetables"].append("carrot")
out "Fruits Category :", groups["fruits"]
out "Vegetables Category:", groups["vegetables"]
itertools Permutations & Combinations
Generates combinatorial selections and orderings of input elements.
RNM = ZITR use itertools chars = ["A", "B", "C"] perms = itertools.permutations(chars, 2) out "Permutations of 2:", perms combs = itertools.combinations(chars, 2) out "Combinations of 2:", combs
itertools Iterator Chaining
Chains multiple lists into a continuous single iterable sequence.
RNM = XITR use itertools list1 = [1, 2, 3] list2 = [4, 5, 6] chained = list(itertools.chain(list1, list2)) out "Chained List:", chained
functools Functional Reduce
Applies binary accumulators iteratively across arrays with functools.reduce.
RNM = XCOM use functools fn multiply(acc, x): return acc * x end numbers = [1, 2, 3, 4, 5] product = functools.reduce(multiply, numbers) out "Product of [1,2,3,4,5] =", product
functools Cached Fibonacci
Speeds up recursive functions by caching previously computed return values.
RNM = ZITR
use functools
fn fib_slow(n):
if n <= 1:
return n
end
return fib_slow(n - 1) + fib_slow(n - 2)
end
out "Fib(10) =", fib_slow(10)
out "Fib(15) =", fib_slow(15)
sqlite3 In-Memory Table Creation
Creates in-memory SQLite tables, inserts records, and executes SQL queries.
RNM = ZITR
use sqlite3
conn = sqlite3.connect(":memory:")
sqlite3.execute(conn, "CREATE TABLE logs (id INT, message TEXT);")
sqlite3.execute(conn, "INSERT INTO logs VALUES (1, 'System started');")
sqlite3.execute(conn, "INSERT INTO logs VALUES (2, 'All tests passed');")
cur = sqlite3.execute(conn, "SELECT * FROM logs;")
rows = sqlite3.fetchall(cur)
out "=== SQLite Records ==="
loop r in rows:
out "Log Entry:", r
end
sqlite3 Transaction Commit
Demonstrates atomic transaction handling and parameterized queries in SQLite.
RNM = XITR
use sqlite3
conn = sqlite3.connect(":memory:")
sqlite3.execute(conn, "CREATE TABLE accounts (name TEXT, balance REAL);")
sqlite3.execute(conn, "INSERT INTO accounts VALUES ('Alice', 1000.0);")
sqlite3.execute(conn, "INSERT INTO accounts VALUES ('Bob', 500.0);")
# Transfer 200 from Alice to Bob
sqlite3.execute(conn, "UPDATE accounts SET balance = balance - 200 WHERE name = 'Alice';")
sqlite3.execute(conn, "UPDATE accounts SET balance = balance + 200 WHERE name = 'Bob';")
rows = sqlite3.fetchall(sqlite3.execute(conn, "SELECT * FROM accounts;"))
out "=== Updated Balances ==="
loop acc in rows:
out "Account:", acc[0], "Balance:", acc[1]
end
unittest Assertions & Test Runner
Executes structured unit tests verifying program logic and assertions.
RNM = XITR use unittest fn add_nums(a, b): return a + b end suite = unittest.TestSuite() unittest.assertEqual(add_nums(3, 4), 7, "3 + 4 should equal 7") unittest.assertTrue(10 > 5, "10 should be greater than 5") out "All assertions verified successfully"
logging Severity Handlers
Logs messages across DEBUG, INFO, WARNING, ERROR, and CRITICAL channels.
RNM = ZITR
use logging
logging.basicConfig("DEBUG")
logging.info("Starting X++ task runner")
logging.warning("Resource usage elevated")
logging.error("Failed to connect to secondary daemon")
out "Logging output captured"
Combo: CSV to SQLite ETL Pipeline
Parses CSV string data and bulk-loads it into an in-memory SQLite table.
RNM = XITR
use csv
use sqlite3
raw_csv = "id,product,price\n1,Laptop,1200.0\n2,Mouse,25.0\n3,Monitor,300.0\n"
rows = csv.reader(raw_csv)
header = rows[0]
conn = sqlite3.connect(":memory:")
sqlite3.execute(conn, "CREATE TABLE inventory (id INT, product TEXT, price REAL);")
loop r in rows[1:]:
sql = "INSERT INTO inventory VALUES (" + str(r[0]) + ", '" + str(r[1]) + "', " + str(r[2]) + ");"
sqlite3.execute(conn, sql)
end
res = sqlite3.fetchall(sqlite3.execute(conn, "SELECT COUNT(*) FROM inventory;"))
out "Total items loaded into SQLite:", res[0][0]
Combo: Live System Health Monitor
Monitors uptime, working directory, and outputs colorful terminal status cards.
RNM = XITR
use os
use time
use TerminX
out TerminX.banner("X++ System Health", "cyan")
out TerminX.bold("Node ID: ") + "alpha-node-01"
out TerminX.bold("Workdir: ") + os.getcwd()
out TerminX.bold("Uptime : ") + str(time.time()) + " epoch"
out TerminX.green("[STATUS OK] All microservices operational")
Combo: Regex Log Analyzer
Extracts HTTP status codes from web logs and computes frequency distributions.
RNM = XCOM
use re
use collections
logs = [
"192.168.1.1 GET /index.html 200",
"192.168.1.2 GET /login.html 200",
"192.168.1.3 POST /api/auth 401",
"192.168.1.4 GET /missing.html 404",
"192.168.1.5 GET /dashboard 200"
]
status_codes = []
loop line in logs:
m = re.findall("\b[1-5][0-9]{2}\b", line)
if len(m) > 0:
push m[0] to status_codes
end
end
counter = collections.Counter(status_codes)
out "=== Log Analysis Summary ==="
out "Total Requests:", len(logs)
out "Status Distribution:", counter
RNM = XITR Fast Python Runtime
Demonstrates the dynamic XITR runtime mode with direct Python VM execution.
RNM = XITR use time out "Running on RNM = XITR" t0 = time.time() sum_v = 0 loop i from 0 to 1000: sum_v = sum_v + i end out "Sum 0..1000 =", sum_v out "Execution finished in XITR"
RNM = XCOM Strict Bytecode AOT
Compiles strict pseudocode to optimized Python bytecode via the XCOM engine.
RNM = XCOM use mathX out "Running on RNM = XCOM (Strict Bytecode)" x = 9.0 y = mathX.sqrt(x) out "Square root of 9 is", y
RNM = ZITR Native C++ Interpreter
Executes natively within xppvm bytecode virtual machine.
RNM = ZITR use mathX out "Running on RNM = ZITR (Native C++ VM)" val = mathX.factorial(6) out "Factorial of 6 =", val
RNM = ZCOM Native Executable AOT
AOT compiles strict pseudocode into a native standalone .zexe binary.
RNM = ZCOM use mathX out "Running on RNM = ZCOM (Native .zexe AOT)" val = mathX.sqrt(100) out "Result of sqrt(100) =", val
RNM = ZJIT Native Machine Code
Compiles performance-critical mathematical loops to machine code via ZJIT.
RNM = ZJIT use mathX out "Running on RNM = ZJIT (Native JIT Engine)" acc = 1.0 loop i from 1 to 10: acc = acc * 1.5 end out "Compounded Result =", acc
Safe/Fail Error Resilience
Demonstrates X++ safe and fail blocks for robust error recovery.
RNM = ZITR out "=== Safe / Fail Resilience ===" safe: out "Attempting dangerous division:" denom = 0 val = 100 / denom out "Never reaches here" fail err: out "Caught handled error successfully!" end out "Program recovered and continues normally"
Recursive Quicksort Algorithm
Sorts an array using recursive divide-and-conquer quicksort in ZJIT.
RNM = ZJIT
fn quicksort(arr):
if len(arr) <= 1:
return arr
end
pivot = arr[0]
less = []
greater = []
loop i from 1 to len(arr) - 1:
x = arr[i]
if x <= pivot:
push x to less
else:
push x to greater
end
end
return quicksort(less) + [pivot] + quicksort(greater)
end
data = [42, 12, 88, 3, 27, 91, 15]
out "Unsorted Data:", data
sorted_data = quicksort(data)
out "Sorted Data :", sorted_data
Combo: Neural Network Forward Layer
Implements a dense neural layer forward pass: a = sigmoid(W * x + b).
RNM = XITR use Xnum use mathX fn sigmoid(x): return 1.0 / (1.0 + mathX.exp(-x)) end inputs = [0.5, 0.8] weights = [[0.2, 0.4], [0.7, 0.1]] bias = [0.1, -0.2] # Compute z = W * x + b z1 = (weights[0][0] * inputs[0]) + (weights[0][1] * inputs[1]) + bias[0] z2 = (weights[1][0] * inputs[0]) + (weights[1][1] * inputs[1]) + bias[1] a1 = sigmoid(z1) a2 = sigmoid(z2) out "=== Neural Layer Activation ===" out "Layer Inputs :", inputs out "Neuron 1 Output:", a1 out "Neuron 2 Output:", a2
Package Manager Resolution
Demonstrates package imports resolved from ./xpp_packages and xpp.json.
RNM = XITR use os out "=== XPM Package Management Runtime ===" out "Searching for libraries in ./xpp_packages" pkg_dir = "./xpp_packages" if os.path.exists(pkg_dir): out "Project package directory detected" else: out "Running with standard decentralized library paths" end
Combo: 2D Raycasting Engine
Calculates distance to boundary walls for retro pseudo-3D raycaster engines.
RNM = ZITR use mathX use GraphiX player_x = 2.0 player_y = 2.0 wall_x = 5.0 wall_y = 5.0 dx = wall_x - player_x dy = wall_y - player_y dist = mathX.sqrt((dx * dx) + (dy * dy)) out "=== 2D Raycast Intersection ===" out "Player Position : (2, 2)" out "Wall Target : (5, 5)" out "Raycast Distance:", dist
Combo: Harmonic Waveform Synthesizer
Synthesizes composite audio waveforms using fundamental frequencies and harmonics.
RNM = XITR use mathX use Xsci freq = 440.0 sample_rate = 8000.0 samples = [] loop i from 0 to 16: t = i / sample_rate # fundamental + 2nd harmonic val = mathX.sin(2.0 * mathX.pi * freq * t) + 0.5 * mathX.sin(4.0 * mathX.pi * freq * t) push val to samples end out "=== Synthesized Audio Samples (A4 440Hz) ===" out "Generated Samples Count:", len(samples) out "First 4 Samples:", samples[:4]
Combo: Hash & Cipher Basics
Calculates rolling hash signatures for data verification.
RNM = XCOM
use mathX
use itertools
fn rolling_hash(s):
h = 0
p = 31
m = 1000000009
p_pow = 1
loop ch in s:
h = (h + ord(ch) * p_pow) % m
p_pow = (p_pow * p) % m
end
return h
end
msg = "XPlusPlus-v0.4.5"
hash_val = rolling_hash(msg)
out "Message:", msg
out "Rolling Hash:", hash_val
Combo: REST API Microservice Handler
Routes inbound REST API endpoints and returns JSON formatted responses.
RNM = XITR
use json
use http
routes = {
"/api/version": {"version": "0.4.5", "status": "active"},
"/api/ping": {"ping": "pong"}
}
fn handle_request(path):
if path in routes:
return {"status": http.HTTPStatus.OK, "body": json.dumps(routes[path])}
end
return {"status": http.HTTPStatus.NOT_FOUND, "body": json.dumps({"error": "not found"})}
end
req1 = handle_request("/api/version")
out "Request /api/version:"
out "Status:", req1["status"]
out "Body :", req1["body"]
Cellular Automata (Conway 1D)
Simulates elementary cellular automaton Rule 30 generation step.
RNM = ZITR # Rule 30 simulation step state = [0, 0, 0, 1, 0, 0, 0] out "Initial State:", state next_state = [0] loop i from 1 to len(state) - 2: left = state[i - 1] center = state[i] right = state[i + 1] # Rule 30 condition: left XOR (center OR right) bit = (left + center + right) % 2 push bit to next_state end push 0 to next_state out "Next State :", next_state
Combo: Cubic Bezier Curve
Computes points along a smooth cubic Bezier spline for animation paths.
RNM = XITR use mathX use Xanmin8 # Control points: P0, P1, P2, P3 p0 = [0.0, 0.0] p1 = [1.0, 3.0] p2 = [3.0, 3.0] p3 = [4.0, 0.0] fn bezier_point(t): u = 1.0 - t tt = t * t uu = u * u uuu = uu * u ttt = tt * t x = (uuu * p0[0]) + (3.0 * uu * t * p1[0]) + (3.0 * u * tt * p2[0]) + (ttt * p3[0]) y = (uuu * p0[1]) + (3.0 * uu * t * p1[1]) + (3.0 * u * tt * p2[1]) + (ttt * p3[1]) return [x, y] end mid = bezier_point(0.5) out "=== Cubic Bezier Evaluation ===" out "Midpoint at t=0.5:", mid
Combo: Genetic Optimization
Evolves candidate strings toward target phrase using evolutionary selection.
RNM = XITR
use random
target = "XPP"
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fn random_candidate():
c = ""
loop i from 0 to len(target):
idx = random.randint(0, len(alphabet) - 1)
c = c + alphabet[idx]
end
return c
end
c1 = random_candidate()
out "Target String :", target
out "Random Candidate :", c1
out "Generation simulated successfully"
Combo: JSON Config Loader
Validates and reads application settings with default fallback values.
RNM = XCOM
use pathlib
use json
default_cfg = {
"port": 8080,
"engine": "ZITR",
"log_level": "INFO",
"workers": 4
}
json_dump = json.dumps(default_cfg)
loaded = json.loads(json_dump)
out "=== Loaded Configuration ==="
out "Port :", loaded["port"]
out "Engine :", loaded["engine"]
out "Workers:", loaded["workers"]
Combo: Full-Stack Integrated App
End-to-end full-stack demonstration combining SQLite database, XWeb and TerminX.
RNM = XITR
use sqlite3
use XWeb
use TerminX
out TerminX.banner("X++ Full-Stack Demo", "magenta")
# 1. Database layer
conn = sqlite3.connect(":memory:")
sqlite3.execute(conn, "CREATE TABLE stats (key TEXT, val INT);")
sqlite3.execute(conn, "INSERT INTO stats VALUES ('visits', 1540);")
sqlite3.execute(conn, "INSERT INTO stats VALUES ('stars', 48);")
rows = sqlite3.fetchall(sqlite3.execute(conn, "SELECT * FROM stats;"))
out TerminX.green("[DB] Stats loaded:")
loop r in rows:
out " *", r[0], "=", r[1]
end
# 2. Web layer
dash = XWeb.page("System Overview", "Database and Web service synchronized.")
out TerminX.blue("[WEB] Generated dashboard view:")
out "Length of HTML payload:", len(dash), "bytes"
out TerminX.bold("=== Full-Stack Pipeline Complete ===")