
## python after Hello World

import secrets

    # Get a secure random integer between 0 and 9
    secure_num = secrets.randbelow(10)

random_str_id = ''.join(random.choices(
   string.ascii_lowercase + string.digits, k=8))

even_squares = [x**2 for x in range(10) if x % 2 == 0]
first, *middle, last = [1, 2, 3, 4, 5]

my_list = []

if not my_list:
    print("The list is empty!")


### str

text = "Python Programming"

print(text[:6])     # "Python" (First 6 characters)
print(text[-3:])    # "ing" (Last 3 characters)
print(text[::-1])   # "gnimmargorP nohtyP" (Reverse)


raw_input = "   Spacey User   "

# Remove whitespace
clean = raw_input.strip()  # "Spacey User"

# Replace substrings
shout = clean.replace(" ", "_")  # "Spacey_User"


s = "python is fun"

print(s.upper())      # "PYTHON IS FUN"
print(s.title())      # "Python Is Fun"
print(s.capitalize()) # "Python is fun"


filename = "report.pdf"

print(filename.endswith(".pdf"))   # True
print(filename.startswith("rep")) # True
print("port" in filename)         # True
print("123".isdigit())            # True

lambda arguments: expression

    students = [("Alice", 90), ("Bob", 85), ("Charlie", 95)]
    # Sort by the second item (the grade)
    students.sort(key=lambda student: student[1])
    # Result: [('Bob', 85), ('Alice', 90), ('Charlie', 95)]

    nums = [1, 2, 3, 4, 5, 6]

    # Filter for even numbers
    evens = list(filter(lambda x: x % 2 == 0, nums)) 
    # [2, 4, 6]


ternary operators

    age = 20

    # Standard way
    if age >= 18:
        status = "Adult"
    else:
        status = "Minor"

    # Ternary (Pythonic) way
    status = "Adult" if age >= 18 else "Minor"

    # Inside a print statement
    print(f"Access {'granted' if is_logged_in else 'denied'}")

    # Inside a list comprehension
    nums = [1, 2, 3, 4, 5]
    results = ["Even" if n % 2 == 0 else "Odd" for n in nums]

    # Hard to read!
    score = 85
    grade = "A" if score > 90 else "B" if score > 80 else "C"

    from pydantic import BaseModel, Field

    # A lambda that returns "High" if value > 100, else "Low"
    check_level = lambda x: "High" if x > 100 else "Low"

    print(check_level(150)) # Output: High



### type hints

names: list[str] = ["Alice", "Bob"]
scores: dict[str, int] = {"Alice": 95, "Bob": 88}
coordinates: tuple[float, float] = (45.0, -90.0)


def find_user(user_id: int) -> str | None:

from pydantic import BaseModel, Field

name: str = Field(default="John")
name: Annotated[str, Field(min_length=2)]

id: str = Field(default_factory=lambda: str(uuid4()))

@field_validator('username')
@classmethod
def validate_username(cls, v: str) -> str:

class attributes 

If you change a class attribute using the class name, 
it changes for everyone. However, 
if you change it using an instance, 
you actually create a new "shadow" instance attribute 
for only that object.

from typing import ClassVar
from pydantic import BaseModel

class User(BaseModel):
    # This is a Pydantic FIELD (validated, expected in input)
    username: str

    # This is a CLASS VARIABLE (not validated, shared by all)
    app_name: ClassVar[str] = "MyAwesomeApp"

class HackerProfile(BaseModel):
    id: int
    alias: str = 'za'

    # This locks the backdoor!
    model_config = {'validate_assignment': True}


# langchain in many programming lang.

Here is the polyglot breakdown! 
LangChain started in Python, 
but it has official and community-driven ports 
across almost every major backend language.

Assuming you want to connect to your local Ollama engine, here is how you would write that exact Python import and initialization in your other languages:

### 1. TypeScript / JavaScript (Node.js)
LangChain has an official, heavily supported JavaScript port (`@langchain/ollama`).

```typescript
import { ChatOllama } from "@langchain/ollama";

const model = new ChatOllama({
  model: "gemma3:4b",
  baseUrl: "http://127.0.0.1:11434",
  temperature: 0.7,
});
```

### 2. Go (Golang)
The Go community maintains a robust port called `langchaingo`. You handle the configuration using Go's standard options pattern.

```go
import (
	"context"
	"github.com/tmc/langchaingo/llms/ollama"
)

// Initialization
llm, err := ollama.New(
    ollama.WithModel("gemma3:4b"),
    ollama.WithServerURL("http://127.0.0.1:11434"),
)
// In Go, temperature is usually passed when you actually invoke the model:
// llms.WithTemperature(0.7)
```

### 3. Rust
There is a growing community crate called `langchain-rust`. It heavily utilizes the Builder pattern, which is standard for Rust structs.

```rust
use langchain_rust::llm::Ollama;
use langchain_rust::llm::client::OllamaClient;

let model = Ollama::default()
    .with_model("gemma3:4b")
    .with_base_url("http://127.0.0.1:11434")
    .with_temperature(0.7);
```

### 4. Ruby
The Ruby port is called `langchainrb`. It uses a slightly different structure where you initialize the overarching LLM module with the Ollama integration.

```ruby
require "langchain"

model = Langchain::LLM::Ollama.new(
  url: "http://127.0.0.1:11434",
  default_options: {
    chat_model: "gemma3:4b",
    temperature: 0.7
  }
)
```

---



### Demystifying LLM Parameters
When an LLM generates text, it doesn't just "know" the next word. It generates a massive list of *every possible word in its vocabulary* and assigns a mathematical probability to each one.

These three parameters are filters that tell the engine how to pick the winning word from that list.

**1. Temperature (The "Creativity" Dial)**
Temperature flattens or sharpens the probabilities before the model makes a choice.
* **Low (e.g., 0.0 - 0.2):** The model becomes highly analytical and robotic. It will almost always pick the mathematically most probable next word. Perfect for writing strict code or answering factual questions.
* **Medium (e.g., 0.7):** The standard default. It allows the model to occasionally pick the 2nd or 3rd most likely word, giving the text a natural, conversational flow without sounding hallucinated.
* **High (e.g., 1.0+):** The model gets wild. Probabilities are flattened, meaning obscure words have a high chance of being selected. Good for creative writing, terrible for programming.

**2. Top-K (The "Hard Cutoff")**
Before the model rolls the dice to pick a word, `top_k` acts as a bouncer at the door.
* If you set `top_k=40`, the engine looks at the thousands of possible next words, keeps only the top 40 most likely ones, and throws the rest in the trash.
* **Why use it?** It prevents the model from ever accidentally selecting a "1-in-a-million" word that would completely derail the sentence. It cuts off the long tail of crazy gibberish.

**3. Top-P (Nucleus Sampling)**
*(Note: I suspect you meant Top-P instead of Top-Q, as Top-P is the industry standard pair to Top-K!)*
`top_p` is a "Soft Cutoff." Instead of picking a fixed *number* of words like Top-K, it picks words based on their *cumulative probability mass*.
* If you set `top_p=0.90`, the engine starts adding up the most likely words (e.g., Word A is 50% likely + Word B is 30% likely + Word C is 10% likely = 90%).
* It stops there and only chooses between those 3 words.
* **Why use it?** It is dynamic. If the LLM is absolutely certain what the next word should be, the Top-P pool shrinks to just 1 or 2 words. If the LLM is confused, the Top-P pool expands to give it more options.

**The Golden Rule:** 
AI researchers generally recommend 
altering **either** Temperature **or** Top-P, 
but not both at the same time, 
as they can interfere with each other and 
make the model's output unpredictable.


# typescript


Here is a cheat sheet of the basic syntax you will use most often in TypeScript.
## 1. Primitive Types
Explicitly declare the type of a variable using a colon (:).

const isDone: boolean = false;const lines: number = 42;const name: string = "Justine";const unknownData: any = "could be anything"; // Disables type checkingconst basicTuple: [string, number] = ["hello", 10]; // Fixed length and type order

## 2. Arrays
Define arrays by appending [] to the type, or by using the Array<type> generic.

const list: number[] = [1, 2, 3];const fruits: Array<string> = ["apple", "banana"];

## 3. Functions
Type both the function input arguments and the returned value.

// Named function with typed arguments and explicit return typefunction add(x: number, y: number): number {
    return x + y;
}
// Arrow function syntaxconst multiply = (x: number, y: number): number => x * y;
// Function that returns nothingfunction logMessage(message: string): void {
    console.log(message);
}

## 4. Optional and Default Parameters
Use ? to make a parameter optional, or assign a value directly to set a default.

function greet(name: string, greeting?: string): string {
    return `${greeting || "Hello"}, ${name}`;
}
function power(base: number, exponent: number = 2): number {
    return Math.pow(base, exponent);
}

## 5. Type Aliases and Interfaces
Use these to define custom structures or shapes for objects.

// Type Alias (commonly used for data shapes or primitives)type Point = {
    x: number;
    y: number;
};
// Interface (ideal for object blueprints and extendable shapes)interface User {
    readonly id: number; // Cannot be changed after creation
    name: string;
    email?: string;      // Optional property
}
const newUser: User = { id: 1, name: "Alice" };

## 6. Union Types
Allow a variable or argument to hold more than one type using the pipe (|) character.

let result: string | number;
result = "Success";
result = 200;
function printId(id: number | string) {
    console.log(`ID is: ${id}`);
}

## 7. Enums
Define a set of named constants to represent fixed choices.

enum Direction {
    Up = 1,
    Down,
    Left,
    Right
}
let move: Direction = Direction.Up; // Value is 1

If you want to practice with these, let me know if you would like to see how to handle object inheritance with interfaces, or how to use type narrowing to safely work with union types!


