YoungLion 0.0.9.9
Professional Python library with hierarchical data models (DDM), utilities, games, file operations, search, terminal styling, and rich debugging tools for developers.
License: MIT
Requires Python: >=3.7
Keywords: YoungLion, Young Lion, DDM, DataModel, utilities, games, file-operations, terminal-styling, debugging, search

# Young Lion Python Library

[![PyPI](https://img.shields.io/pypi/v/YoungLion.svg?color=gold&logo=python&logoColor=white)](https://pypi.org/project/YoungLion)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/)
[![Python Version](https://img.shields.io/badge/python-3.7%2B-blue.svg?logo=python&logoColor=white)](https://www.python.org/)
[![issues](https://img.shields.io/github/issues/Cavanshirpro/YoungLionPythonLibrary?logo=github&logoColor=white)](https://github.com/Cavanshirpro/YoungLionPythonLibrary/issues)
[![stars](https://img.shields.io/github/stars/Cavanshirpro/YoungLionPythonLibrary?logo=github&logoColor=white&style=flat-square)](https://github.com/Cavanshirpro/YoungLionPythonLibrary/)


The **Young Lion Python Library** is designed to simplify the work of developers, especially *Young Lion Developers*. This library provides a wide range of functionalities for handling various file formats, managing directories, and executing file-related operations efficiently.

This library is under development and will be expanded with more features in the future.

---

## Changelog

## Unlike 0.0.7:
 - We fixed some minor bugs in VISTA in version 0.0.7.1. We did not make the version 0.0.8 because there were no major changes. (0.0.7.2, 0.0.7.3)
 - In 0.0.7.4 we colored some terminal text.
 - In 0.0.7.6 New functions have been added to the File class. move_folder move_file copy_file create_folder
 - In 0.0.7.8 We optimized functions
## Unlike 0.0.8:
 - 0.0.8 We add new search module
 - 0.0.8.2 Added some small functions to File class
## Unlike 0.0.9:
 - 0.0.9 We add minigames in library
 - 0.0.9.1 Some bugs have been fixed and hangman word data has been improved.
 - 0.0.9.2 A custom feature has arrived for you to integrate XOX and Hangman games into your own interface and applications.
 - 0.0.9.4 We add Terminal Module in library
 - 0.0.9.6 We added ANCI and untils to the terminal module.
 - 0.0.9.7 I came to the decision to divide the library into categories
 - 0.0.9.8 We add Debugger, DDM (Dynamic Data Model) and Colors
## Unlike 0.0.9.9:
 - 0.0.9.9 **Major DataModel Expansion**: 
   - ✨ **60+ New DDM Methods**: Path-based access, cloning, merging, validation, filtering, transformation, sorting, grouping, aggregation
   - 🎯 **New Utility Classes**: `Range`, `Vector`, `Timeline`, `Dataset` (all DDM-based)
   - ⚡ **SmartCache (SC)**: Ultra-fast template-based data completion system
   - 🏗️ **DDMBuilder**: Fluent API for constructing complex DDM instances
   - 🔧 **Advanced Features**: JSON/CSV/XML export, batch processing, statistics, diff detection
   - 📊 **100+ Total New Methods**: Across all new and enhanced classes
---

## Table of Contents

- [Installation](#installation)
- [Modules](#modules)
  - [Functions](#functions-features-and-overview)
  - [Search](#search-features-and-overview)
  - [DataModel](#datamodel-features-and-overview)
  - [Colors](#colors-features-and-overview)
- [Usage Examples](#usage-examples)
  - [File Module Example](#comprehensive-guide-to-using-the-file-class)
  - [Search Module Example](#usage-example)
  - [DataModel Module Example](#usage-examples)
- [Changelog](#changelog)
- [License](#license)

---

## Installation

To install the Young Lion library, run the following command:

```bash
pip install YoungLion
```

**Attention!** If an error or problem occurs during the installation, you may need to run these commands in the terminal:

```bash
pip cache purge
python -m pip install --upgrade pip
pip install YoungLion --no-cache-dir
```

---

## Modules

The library is organized into the following modules:

- ### Functions
  Comprehensive file handling, scripting, scheduling, logging, and utilities.

- ### Search
  Advanced keyword-based search engine with tag generation and fuzzy matching.

- ### DataModel (NEW in 0.0.9.9 - Massively Expanded)
  Professional data management with 60+ new methods, 4 specialized classes, and SmartCache.

- ### Colors
  Cross-platform ANSI color support for terminal output.
---

## Functions Features and Overview

This module contains a very comprehensive set of Python classes that perform various functions. Below is a general summary of these classes and the main features they offer:

---

#### **1. `File` Class**
- **Purpose**: File processing (JSON, TXT, CSV, LOG, PDF, XML, YAML, INI, etc.) and directory management.
- **Supported Operations**:
  - Reading and writing JSON, TXT, LOG files.
  - Reading, writing, adding and updating CSV files.
  - Reading, writing, and creating PDF content.
  - Read, write and edit XML files.
  - Compressing and extracting compressed files (`.zip`).
  - Read/write HTML, CSS, and JS files.
  - **Python File Management**:
    - Executing Python files with argument and terminal options.
    - Adding code blocks to Python files (start, end, or specific line).
    - Validating and preparing Python file paths.
  - Executing SQL queries and creating tables.
  - **JavaScript File Management**:
    - Reading, writing, and executing JavaScript files.
    - Terminal-based or background execution.
  - **LaTeX Processing**:
    - Converting Markdown to LaTeX.
    - Reading and writing `.tex` files.
    - Compiling LaTeX to plain text.
    - Converting LaTeX to Markdown.
    - Appending content to `.tex` files.
    - Converting LaTeX to HTML with MathJax support.
    - Rendering LaTeX as images.
  - **Directory & File Operations**: (Added in 0.0.7.6)
    - `move_folder`, `move_file`, `copy_file`, `create_folder`, `delete_file`, `delete_folder` (Added in 0.0.8.2)

---

#### **2. `ScriptRunner` Class**
- **Objective**: Execute scripts in Node.js or a specified interpreter.
- **Key Features**:
  - Run a script in the terminal or in the background.
  - Providing input data for the script.
  - Capture and process outputs.

---

#### **3. `TaskScheduler` Class**
- **Purpose**: Schedule, pause, resume and cancel tasks.
- **Supported Functions**:
  - Create one-off or repetitive tasks.
  - Prioritizing tasks.
  - CLI-based task listing.

---

#### **4. `Logger` Class**
- Purpose**: Flexible logging at the application level.
- **Features**:
  - Write information, error and warning messages to log file.
  - Support for different log levels (INFO, DEBUG, ERROR, etc.).
  - Console and file logging support.

---

#### **5. `EmailManager` Class**
- **Purpose**: Email sending and management.
- **Basic Functions**:
  - Sending email instantly.
  - Scheduling email based on a specific time.
  - Check the last messages in your inbox.

---

#### **6. `FileTransferManager` Class**
- **Purpose**: Uploading and downloading files using FTP and SFTP.
- **Features**:
  - File upload and download.
  - Track transfer status.
  - Supported protocols: FTP and SFTP.

---

#### **7. `TextProcessor` Class**
- **Purpose**: Text analysis and editing.
- **Key Features**:
  - Word and character counting.
  - Keyword search.
  - Text replacement and summarization.
  - Finding the most frequently used words.
  - Readability score calculation.

---

#### **8. `Debugger` Class**
- **Purpose**: Easy Debugging
- **Key Features**:
  - Colorized
  - Symbolized
  - Ready Debug Types
  - Custom debugging function

---

With their modular structure and rich feature set, these classes provide powerful tools for many application development processes. Each one is optimized for a specific type of data processing or management operations.

---
## Search Features and Overview

The **Search** module provides an advanced and efficient way to search through structured data using keyword-based matching. This module offers:

- **Tag Generation (`GenerateTags` class)**:
  - Automatically generates keyword tags from input text.
  - Supports custom replacements (e.g., "Minecraft" → "MC").
  - Removes unnecessary stopwords for better efficiency.
  - Supports case normalization and special character cleaning.
  - Generates keyword combinations and permutations.

- **Data Organization (`SearchData` class)**:
  - Stores searchable data with keyword-based mapping.
  - Allows quick retrieval of associated data.

- **Advanced Search System (`Search` class)**:
  - Finds relevant search results based on keywords.
  - Uses fuzzy matching to suggest close alternatives.
  - Supports exact-match searching if required.

### **Usage Example**

```python
from YoungLion import Search, SearchData, GenerateTags

# Create structured search data
search_entries = [
    {"tags": ["Science", "Physics", "Quantum Mechanics"], "return": {"title": "Quantum Theory", "link": "example.com/qm"}},
    {"tags": ["Programming", "Python", "Machine Learning"], "return": "Learn Python for ML"}
]

sdata = SearchData(search_entries)
search_engine = Search(sdata)

# Perform a search
results = search_engine.search("Physics")
print(results)  # Output: [{'title': 'Quantum Theory', 'link': 'example.com/qm'}]
```

With the **Search** module, you can implement a high-performance keyword search engine with minimal effort.

---

## DataModel Features and Overview

The **DataModel** module provides a professional, enterprise-grade system for managing hierarchical structured data in Python. Introduced in version 0.0.9.8 and massively expanded in 0.0.9.9, it offers sophisticated tools for data manipulation, validation, transformation, and optimization.

### **🎉 What's New in Version 0.0.9.9**

This version introduces a **massive expansion** of the DataModel module:

- ✨ **60+ New DDM Methods** - Path-based access, deep cloning, merging, validation, advanced filtering, transformation, sorting, grouping, and statistical analysis
- 🎯 **4 New Utility Classes** - `Range` (interval management), `Vector` (N-dimensional math), `Timeline` (event management), `Dataset` (tabular data)
- ⚡ **SmartCache (SC)** - Ultra-fast O(n) template-based data completion system for high-frequency processing
- 🏗️ **DDMBuilder** - Fluent API for constructing complex DDM instances
- 📊 **Advanced Analytics** - Batch processing, diffing, statistics, type analysis
- 🔧 **Format Support** - JSON, CSV, XML-like export formats with full customization
- 📈 **Performance** - Memory-optimized with O(1) key lookup, bulk operations

---

### **Core Components**

#### **1. DDM - Dynamic Data Model** (Base Class)
The foundational class for all data models with 60+ methods for professional data management:

**Data Management:**
- Stores input dictionaries as dynamic attributes
- Supports nested DDM objects, lists, tuples, and dictionaries
- Recursive serialization via `.to_dict()` and `.to_json()`
- Path-based access to nested data (e.g., `get_path("address.city")`)
- Deep cloning and merging operations

**Advanced Features:**
- **Filtering & Search**: `filter_keys()`, `exclude_keys()`, `search()`, `find_by_type()`
- **Transformation**: `transform()`, `map_attributes()`, batch operations
- **Sorting & Organization**: `sort_by_key()`, `sort_by_value()`, `group_by()`, `aggregate()`
- **Validation**: `validate_schema()`, `has_type()`, `get_types()`
- **Export Formats**: CSV, XML-like, JSON with custom control
- **Statistics**: Detailed analysis with `analyze_ddm_structure()`, `get_ddm_size_info()`
- **Dict-Like Interface**: `__getitem__()`, `__setitem__()`, `keys()`, `values()`, `items()`

**Key Methods (Partial List):**
```python
# Serialization
.to_dict(), .to_json(indent=2), .to_flat_dict(), .to_csv()

# Path Access
.get_path(path), .set_path(path, value), .has_path(path)

# Cloning & Merging
.clone(), .merge(other), .update(**kwargs)

# Comparison
.diff(other), .validate_schema(schema)

# Filtering & Searching
.filter_keys(keys), .search(query), .find_by_type(type)

# Transformation
.transform(func), .map_attributes(mapping)

# Advanced
.group_by(func), .aggregate(funcs), .pick(*keys)
```

---

#### **2. Utility Classes** (DDM-Based)

##### **Range** - Bounded Interval Management
Manages continuous numerical intervals with powerful operations:

```python
r = Range(min_val=0, max_val=100, step=10)

# Basic operations
r.contains(50)           # True
r.clamp(150)             # 100
r.span()                 # 100
r.midpoint()             # 50

# Normalization
r.normalize(50)          # 0.5
r.denormalize(0.5)       # 50.0

# Advanced
r.subdivide(5)           # Split into 5 parts
r.intersect(other)       # Find intersection
r.overlaps(other)        # Check overlap
for val in r.iterate():  # Stepped iteration
    process(val)
```

**Methods:** `contains()`, `clamp()`, `normalize()`, `denormalize()`, `span()`, `midpoint()`, `random()`, `iterate()`, `subdivide()`, `intersect()`, `overlaps()`

---

##### **Vector** - N-Dimensional Mathematical Vectors
Professional vector operations for physics, graphics, and mathematics:

```python
v1 = Vector(components=[1, 2, 3])
v2 = Vector(components=[4, 5, 6])

# Vector operations
v1.magnitude()           # 3.74...
v1.normalize()           # Unit vector
v1.dot(v2)              # 32
v1.cross(v2)            # Cross product (3D)
v1.distance_to(v2)      # 5.196...
v1.angle_to(v2)         # Degrees

# Transformations
v1.project_onto(v2)     # Projection
v1.perpendicular()      # Perpendicular (2D)
v1.lerp(v2, 0.5)        # Linear interpolation

# Operator support
v3 = v1 + v2
v4 = v1 * 2
```

**Methods:** `magnitude()`, `normalize()`, `dot()`, `cross()`, `distance_to()`, `angle_to()`, `add()`, `subtract()`, `scale()`, `project_onto()`, `perpendicular()`, `lerp()`, operators

---

##### **Timeline** - Event/Milestone Management
Sequential event management with time-based operations:

```python
tl = Timeline(start_time=0, end_time=10)

# Event management
tl.add_event(0, "start", {"value": 0})
tl.add_event(5, "middle", {"value": 50})
tl.add_event(10, "end", {"value": 100})

# Queries
tl.get_event("middle")              # Get event data
tl.events_at(5)                     # Events at time
tl.events_between(2, 8)             # Time range

# Timeline control
tl.get_progress(5)                  # 0.5 (50% progress)
tl.duration()                       # 10
tl.sort()                           # Sort by time
tl.reverse()                        # Reverse order
```

**Methods:** `add_event()`, `remove_event()`, `get_event()`, `events_at()`, `events_between()`, `duration()`, `get_progress()`, `sort()`, `reverse()`

---

##### **Dataset** - Tabular Data Management
Professional spreadsheet-like data handling with statistics:

```python
ds = Dataset(columns=["name", "age", "city"])

# Data operations
ds.add_row({"name": "Alice", "age": 30, "city": "NY"})
ds.add_row({"name": "Bob", "age": 25, "city": "LA"})

# Filtering & sorting
adults = ds.filter_rows(lambda row: row["age"] >= 25)
sorted_ds = ds.sort_by("age")

# Organization
by_city = ds.group_by("city")           # Group by column

# Statistics
age_stats = ds.stats("age")             # {count, sum, mean, min, max, std}
avg_age = ds.aggregate("age", sum)      # Custom aggregation

# Export & transform
csv = ds.to_csv()                       # CSV export
transposed = ds.transpose()             # Row/column flip

# Column management
ds.add_column("salary", default=0)
ds.remove_column("salary")
ds.map_column("name", str.upper)
```

**Methods:** `add_row()`, `add_column()`, `remove_column()`, `filter_rows()`, `map_column()`, `sort_by()`, `group_by()`, `aggregate()`, `stats()`, `to_csv()`, `transpose()`

---

##### **SmartCache (SC)** - Ultra-Fast Data Completion
⚡ Production-grade template-based data completion with O(n) complexity:

```python
# Setup
template = {"name": "Unknown", "age": 0, "city": "Unknown"}
sc = SmartCache(template=template)

# Single completion (very fast!)
raw = {"name": "Alice", "age": 30}
completed = sc.complete(raw)
# → {"name": "Alice", "age": 30, "city": "Unknown"}

# Batch processing (ultra-efficient)
records = [{"name": "Bob"}, {"age": 25}]
all_completed = sc.complete_batch(records)

# Analysis
missing = sc.get_missing_keys(raw)      # ["city"]
extra = sc.get_extra_keys(raw)          # []
report = sc.completion_report(raw)      # Detailed analysis
stats = sc.get_stats()                  # Performance metrics

# Dynamic updates
sc.update_template(new_template)
sc.reset_stats()
```

**Key Features:**
- ✨ O(n) completion time - processes only missing keys
- 🔒 Template protection - default values never modified
- 🧠 Memory-optimized - hash-based key lookup O(1)
- 📊 Statistics tracking - monitor efficiency
- 🔄 Batch mode - handle thousands of records efficiently

**Methods:** `complete()`, `complete_batch()`, `fill()`, `fill_batch()`, `get_missing_keys()`, `get_extra_keys()`, `completion_report()`, `update_template()`, `get_stats()`, `reset_stats()`

---

#### **3. Advanced Utilities**

##### **DDMBuilder** - Fluent API Construction
Build complex DDM instances with chainable syntax:

```python
builder = DDMBuilder()
person = (builder
    .set("name", "Alice")
    .set("age", 30)
    .set_many(city="NY", country="USA")
    .nest("address", lambda b: 
        b.set("street", "123 Main").set("zip", "10001")
    )
    .add_list("hobbies", ["reading", "coding"])
    .build()
)
```

**Methods:** `set()`, `set_many()`, `nest()`, `add_list()`, `build()`

---

##### **Helper Functions**
- `merge_ddms(*ddms)` - Merge multiple DDM instances
- `compare_ddms(ddm1, ddm2)` - Detailed comparison
- `batch_transform(ddms, transformer)` - Apply function to batch
- `batch_filter(ddms, predicate)` - Filter batch by condition
- `validate_ddm_batch(ddms, schema)` - Validate multiple DDMs
- `analyze_ddm_structure(ddm)` - Structural analysis
- `get_ddm_size_info(ddm)` - Memory metrics
- `create_smart_cache(template)` - Create SmartCache
- `fast_complete(template, raw_data)` - One-shot completion
- `batch_complete_fast(template, records)` - Fast batch completion

---

### **Color Integration**
All classes support ANSI color output via `Colors` module:

```python
from YoungLion import DDM, Colors

person = DDM({"name": "Alice", "age": 30})
print(f"{Colors.BLUE}Person:{Colors.RESET}")
print(person)  # Keys in blue, values in green
```

---

### **Usage Examples**

#### **Example 1: Data Standardization**
```python
from YoungLion import SmartCache

# API response standardization
template = {
    "user_id": None,
    "username": "guest",
    "verified": False,
    "email": ""
}

cache = SmartCache(template=template)

# Different API responses
responses = [
    {"user_id": 1, "username": "alice"},
    {"user_id": 2, "verified": True},
    {"username": "bob", "email": "bob@example.com"}
]

# Normalize all
normalized = cache.complete_batch(responses)
print(cache.get_stats())  # Efficiency report
```

#### **Example 2: Complex Data Analysis**
```python
from YoungLion import Dataset

# Create dataset
ds = Dataset(columns=["product", "quantity", "price"])

# Add data
ds.add_row({"product": "Laptop", "quantity": 5, "price": 1000})
ds.add_row({"product": "Mouse", "quantity": 50, "price": 25})
ds.add_row({"product": "Keyboard", "quantity": 30, "price": 75})

# Analysis
expensive = ds.filter_rows(lambda r: r["price"] > 50)
by_price = ds.sort_by("price", reverse=True)

# Statistics
stats = ds.stats("price")
print(f"Average: {stats['mean']}, Max: {stats['max']}")

# Export
print(ds.to_csv())
```

#### **Example 3: Vector Calculations**
```python
from YoungLion import Vector

# 3D vectors
pos1 = Vector(components=[0, 0, 0])
pos2 = Vector(components=[3, 4, 0])

# Distance calculation
dist = pos1.distance_to(pos2)  # 5.0

# Direction
direction = (pos2 - pos1).normalize()

# Interpolation
midpoint = pos1.lerp(pos2, 0.5)
```

---

### **Benefits**

* ✅ **Professional-Grade**: Enterprise-ready data management
* ✅ **Comprehensive**: 60+ methods covering all common operations
* ✅ **Efficient**: O(n) to O(1) algorithms, memory-optimized
* ✅ **Extensible**: Easy to subclass and customize
* ✅ **Integrated**: All classes work seamlessly together
* ✅ **Type-Safe**: Full type hints throughout
* ✅ **Well-Documented**: Detailed docstrings and examples
* ✅ **Production-Ready**: Used in real-world applications

---


---

## Colors Features and Overview 

The **Colors** module provides a comprehensive set of ANSI escape codes for terminal text formatting.
It is designed to be simple, flexible, and professional for Python projects.

Using this module, you can add colored, styled, and visually distinctive text to your terminal output, making your scripts and applications more readable and user-friendly.

---

## Features

* **Text Colors**
  Foreground text colors for standard and bright variants:
  `BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE` and their bright counterparts.

* **Background Colors**
  Background colors for standard and bright variants:
  `BG_BLACK, BG_RED, BG_GREEN, BG_YELLOW, BG_BLUE, BG_MAGENTA, BG_CYAN, BG_WHITE` and bright versions.

* **Text Styles**
  Easily apply styles such as:
  `RESET, BRIGHT, DIM, ITALIC, UNDERLINE, BLINK, REVERSE, HIDDEN, STRIKETHROUGH`

* **Cross-Platform**
  Works on Windows, Linux, and Mac terminals. ANSI support is automatically enabled if necessary.

* **Professional Integration**
  Fully class-based, easy to import and use in any Python project. Works well with **DataModel**, **Terminal utilities**, or other console-based scripts.

---

## Installation

Just include `Colors` in your project and import the class:

```python
from YoungLion import Colors
```

No external dependencies are required.

---

## Usage Examples

### Basic Usage

```python
from YoungLion import Colors

print(f"{Colors.RED}This is red text{Colors.RESET}")
print(f"{Colors.BRIGHT_GREEN}Bright green text{Colors.RESET}")
print(f"{Colors.UNDERLINE}{Colors.CYAN}Underlined cyan text{Colors.RESET}")
print(f"{Colors.BG_BLUE}{Colors.WHITE}White text on blue background{Colors.RESET}")
```

### Combining Styles

```python
print(f"{Colors.BRIGHT}{Colors.MAGENTA}Bright magenta text{Colors.RESET}")
print(f"{Colors.REVERSE}{Colors.YELLOW}Reversed yellow text{Colors.RESET}")
print(f"{Colors.BLINK}{Colors.RED}Blinking red text (may not work on all terminals){Colors.RESET}")
```

### Example with DataModel Integration

```python
from YoungLion import DDM,Colors

class Person(DDM):
    pass

data = {"name": "Alice", "age": 30}
person = Person(data)

# Use Colors to highlight keys or values
print(f"{Colors.BLUE}Person Info:{Colors.RESET}")
print(person)
```



---

## Notes

* ANSI codes are supported in most modern terminals. On Windows, ensure ANSI processing is enabled (via the `enable_ansi()` function in your projects if necessary).
* Reset the formatting after applying any color or style to prevent bleed


# Usage/Examples

### **Comprehensive Guide to Using the `File` Class**

The `File` class is a robust utility for managing and processing various file types such as JSON, TXT, CSV, PDF, XML, YAML, and more. With built-in error handling and directory management, it simplifies complex file operations for developers. Below is a detailed guide on its usage and capabilities.

---

### **Initialization**
The `File` class can optionally be initialized with a `filefolder` parameter, which sets a default directory for file operations.

```python
import YoungLion

# Initialize with a default directory
file_manager = YoungLion.File(filefolder="/path/to/default/directory")
```

---

### **Supported File Operations**

#### **1. Directory Management**
The `list_files_and_folders` method lists all files and folders in a given directory.

```python
# List files and folders in the default directory
items = file_manager.list_files_and_folders()

# List files and folders in a specific directory
items = file_manager.list_files_and_folders(path="/path/to/directory")
```

---

#### **2. JSON File Handling**
**Reading JSON Files**: Reads data from a JSON file, with optional defaults and automatic creation of empty files if missing.

```python
# Reading a JSON file
data = file_manager.json_read("data.json", default={"key": "value"})

# Access nested data safely
value = data["key"]["nested_key"]
```

**Writing JSON Files**: Writes a dictionary to a JSON file.

```python
# Writing data to a JSON file
file_manager.json_write("data.json", {"name": "John", "age": 30})
```

---

#### **3. TXT File Handling**
**Reading Text Files**: Read an entire text file or process it line-by-line.

```python
# Read the whole file as a string
content = file_manager.txt_read_str("notes.txt")

# Read line-by-line into a dictionary with line numbers as keys
lines = file_manager.txt_read_linear("notes.txt")
```

**Writing Text Files**: Write strings or line-based dictionaries to a text file.

```python
# Write a string to a file
file_manager.txt_write_str("output.txt", "This is a sample text.")

# Write lines to a file with line numbers
lines_to_write = {1: "First line", 2: "Second line"}
file_manager.txt_write_linear("output.txt", lines_to_write)
```

---

#### **4. CSV File Handling**
**Reading CSV Files**: Reads a CSV file into a list of dictionaries.

```python
# Read CSV file
rows = file_manager.csv_read("data.csv")
```

**Writing CSV Files**: Writes a list of dictionaries to a CSV file.

```python
# Write rows to a CSV file
file_manager.csv_write("output.csv", [{"Name": "Alice", "Age": 25}, {"Name": "Bob", "Age": 30}])
```

**Appending and Updating CSV Data**: Append new rows or update existing ones based on unique identifiers.

```python
# Append rows to an existing CSV
file_manager.csv_append("data.csv", [{"Name": "Charlie", "Age": 35}])

# Update rows in a CSV
file_manager.csv_update("data.csv", [{"Name": "Alice", "Age": 26}], identifier="Name")
```

---

#### **5. PDF File Handling**
**Reading PDF Files**: Extracts text content from a PDF file.

```python
# Extract text from a PDF
text = file_manager.pdf_read("document.pdf")
```

**Writing PDF Files**: Writes text content to a PDF.

```python
# Write text to a PDF
file_manager.pdf_write("output.pdf", "This is a sample PDF content.")
```

---

#### **6. XML File Handling**
**Reading XML Files**: Parses XML files into dictionaries.

```python
# Read an XML file
xml_data = file_manager.xml_read("data.xml")
```

**Writing and Appending XML Files**: Writes or appends dictionaries to XML files.

```python
# Write XML data
file_manager.xml_write("output.xml", {"root": {"child": "value"}})

# Append XML data
file_manager.xml_append("data.xml", {"additional": "value"})
```

---

#### **7. YAML and INI File Handling**
**YAML Operations**: Read and write YAML files.

```python
# Read YAML file
yaml_data = file_manager.yaml_read("config.yml", default={"setting": "default"})

# Write YAML data
file_manager.yaml_write("config.yml", {"setting": "custom"})
```

**INI Operations**: Read and write INI configuration files.

```python
# Read INI file
ini_data = file_manager.ini_read("config.ini")

# Write INI data
file_manager.ini_write("config.ini", {"Section": {"Key": "Value"}})
```

---

#### **8. Properties File Handling**
Reads and writes `.properties` files, commonly used for configuration.

```python
# Read properties file
props = file_manager.properties_read("config.properties")

# Write to properties file
file_manager.properties_write("config.properties", {"key": "value"}, append=True)
```

---

#### **9. HTML, CSS, and JavaScript**
Handles web-related file types like HTML, CSS, and JS.

```python
# Read an HTML file
html_content = file_manager.html_read("index.html")

# Write to an HTML file
file_manager.html_write("index.html", "<h1>Hello World</h1>")
```

---

#### **10. Compressed Files**
Compress or extract files and folders.

```python
# Compress a folder
file_manager.handle_compressed("folder_path", action="compress", target="archive.zip")

# Extract a zip file
file_manager.handle_compressed("archive.zip", action="extract", target="output_folder")
```

---

#### **11. LaTeX Processing**
The `File` class includes comprehensive support for LaTeX operations.

**Converting Markdown to LaTeX**: Converts a Markdown string to a LaTeX-formatted string.

```python
# Convert Markdown to LaTeX
latex_content = file.markdown_to_latex("# Heading\nThis is a paragraph.")
```

**Reading and Writing `.tex` Files**: Provides utilities to read, write, and append `.tex` files.

```python
# Read a .tex file
content = file.tex_read("document.tex")

# Write content to a .tex file
file.tex_write("output.tex", "\\section{Introduction}\nThis is a LaTeX document.")

# Append content to a .tex file
file.tex_append("document.tex", "\\subsection{Conclusion}\nThank you!")
```

**Compiling LaTeX to Plain Text**: Converts LaTeX-formatted content to plain text, stripping out special commands.

```python
# Compile LaTeX to plain text
plain_text = file.latex_compile(r"V_{SC} = \frac{N}{G}")
```

**Converting LaTeX to Markdown**: Transforms LaTeX content into Markdown format.

```python
# Convert LaTeX to Markdown
markdown_content = file.tex_to_markdown(r"\section{Hello World}")
```

**Generating HTML with MathJax Support**: Creates an HTML file displaying LaTeX content using MathJax.

```python
# Convert LaTeX to HTML
html_content = file.latex_to_html(r"V_{SC} = \frac{YL_{bank}}{YL_{official}}", "output.html")
```

**Rendering LaTeX as an Image**: Generates a visual representation of LaTeX formulas as images.

```python
# Render LaTeX formula as an image
image_data = file.latex_to_image(r"V_{SC} = \sqrt{N}", "output.png")
```

---

### **12. Python File Handling**
The `File` class includes enhanced support for managing and manipulating Python files, such as executing scripts and dynamically adding code blocks.

#### **Executing Python Files**
You can execute a Python file with optional arguments and capture its output.

```python
# Run a Python script
output = file.py_run("example.py", args=["--arg1", "value"])
print(output)
```

#### **Adding Code to Python Files**
Dynamically add new functions or code snippets to an existing Python file.

**Adding Code to the End of a File**:
```python
new_function = """
def say_hello():
    print("Hello, Python!")
"""
file.py_add_code("example.py", new_function, position="end")
```

**Adding Code to the Start of a File**:
```python
new_function = """
def initialize():
    print("Initialization complete!")
"""
file.py_add_code("example.py", new_function, position="start")
```

**Adding Code at a Specific Line**:
```python
new_code = "print('This is a new line of code.')"
file.py_add_code("example.py", new_code, position=5)
```

---

### **Error Handling**
The `File` class incorporates robust error handling mechanisms to deal with:
- Missing files or directories.
- Invalid formats (e.g., corrupted JSON or XML).
- Permission issues.

For instance, if a file is missing during a `json_read` operation, it will automatically create an empty JSON file to ensure smooth operation.

---

### **Advantages**
- **Versatile**: Supports a wide variety of file formats and operations.
- **Error-Resilient**: Handles common issues like missing files or invalid data gracefully.
- **Customizable**: Flexible options for path validation and directory management.
- **Integrated**: Provides a unified API for diverse file handling needs.

---

The `File` class is a powerful addition to any Python developer's toolkit, offering a comprehensive suite of file management capabilities in a single interface. Whether you are dealing with structured data files or generating dynamic outputs, this class simplifies and accelerates your workflow.

---

### **Comprehensive Guide to Using the `ScriptRunner` Class**

The `ScriptRunner` class provides a streamlined interface for executing scripts across various interpreters, such as Node.js, Python, or others. It supports input handling, terminal execution, and capturing output, making it ideal for dynamic script management.

---

### **Initialization**
The `ScriptRunner` is initialized with a default interpreter, which will be used unless another is specified during execution.

```python
import YoungLion

# Initialize with a default interpreter (Node.js)
runner = Younglion.ScriptRunner(default_interpreter="node")

# Change the default interpreter
runner.set_default_interpreter("python")
```

---

### **Key Features and Methods**

#### **1. Setting and Validating Paths**
The `_validate_path` method ensures the provided script path is valid and converts it to an absolute path. If the file does not exist, it raises a `FileNotFoundError`.

```python
# Example usage (internal)
validated_path = runner._validate_path("script.js")
print(validated_path)  # Outputs the absolute path of the script
```

---

#### **2. Running Scripts**
The `run_script` method is the core functionality of this class. It allows executing scripts with a specified interpreter, in the terminal or background, with optional input and output handling.

**Parameters**:
- `path`: Path to the script file.
- `interpreter`: Interpreter to use (defaults to the class's default interpreter).
- `terminal`: If `True`, runs the script in a terminal window.
- `inputs`: Input data passed as a string or list of strings.
- `output`: If `True`, captures and returns the script output.

**Example: Basic Script Execution**
```python
# Run a Node.js script in the background
output = runner.run_script("script.js")
print(output)  # Prints the script output
```

**Example: Changing Interpreters**
```python
# Run a Python script with inputs
output = runner.run_script("script.py", interpreter="python", inputs=["arg1", "arg2"])
print(output)
```

**Example: Terminal Execution**
```python
# Run a script in the terminal (e.g., on macOS/Linux)
runner.run_script("script.js", terminal=True)
```

---

#### **3. Handling Inputs**
The `inputs` parameter can handle either a single string or a list of strings. The class ensures the inputs are formatted correctly for the script.

**Example: Passing Inputs**
```python
# Pass a single input string
runner.run_script("script.js", inputs="input_data")

# Pass multiple inputs as a list
runner.run_script("script.js", inputs=["arg1", "arg2", "arg3"])
```

---

#### **4. Output Management**
By default, the method captures and returns the script's output when executed in the background. If `output` is set to `False`, the script is executed without returning the output.

**Example: Suppressing Output**
```python
# Execute without returning output
runner.run_script("script.js", output=False)
```

---

#### **5. Terminal Execution**
When `terminal=True`, the script is run in a terminal window. This feature depends on the operating system and requires a terminal emulator.

- **Windows**: Uses the `cmd` terminal.
- **macOS/Linux**: Uses `xterm` or similar terminal emulators.

**Example: Terminal Execution**
```python
# Run a script in a terminal
runner.run_script("script.js", terminal=True)
```

If no terminal emulator is found, a `RuntimeError` is raised.

---

### **Error Handling**
The `ScriptRunner` class includes robust error handling for common issues:
1. **File Not Found**: If the script file path is invalid or does not exist.
2. **Interpreter Not Found**: If the specified interpreter is unavailable.
3. **Execution Errors**: If the script fails during execution (e.g., syntax errors).

**Example: Error Handling**
```python
try:
    runner.run_script("nonexistent.js")
except FileNotFoundError as e:
    print(f"Error: {e}")
except RuntimeError as e:
    print(f"Execution Error: {e}")
```

---

### **Changing the Default Interpreter**
You can dynamically update the default interpreter using the `set_default_interpreter` method.

```python
# Change to Python as the default interpreter
runner.set_default_interpreter("python")

# Execute a Python script using the new default interpreter
runner.run_script("example.py")
```

---

### **Advantages**
- **Flexibility**: Supports multiple interpreters (e.g., Node.js, Python).
- **Input Handling**: Seamless integration of inputs for scripts.
- **Terminal/Background Execution**: Run scripts in various modes depending on your needs.
- **Cross-Platform**: Works on Windows, macOS, and Linux with appropriate configurations.

---

### **Usage Scenarios**
- **Automated Script Execution**: Dynamically run scripts for tasks such as testing or data processing.
- **Multi-Interpreter Environments**: Manage scripts in different programming languages without switching environments.
- **Real-Time Input/Output**: Capture output and integrate with larger Python workflows.

The `ScriptRunner` class is a powerful utility for developers needing streamlined script execution across diverse environments. It bridges the gap between Python and other runtime environments, making it an essential tool for automation and scripting.

---

### **Comprehensive Guide to Using the `TaskScheduler` Class**

The `TaskScheduler` class is a robust solution for managing and executing tasks with features such as priority-based scheduling, pausing/resuming tasks, repeating intervals, and detailed task tracking. Designed with multi-threading and thread safety, it is ideal for building dynamic and flexible applications.

---

### **Initialization**
The `TaskScheduler` initializes the necessary data structures and locks for managing tasks. 

```python
import YoungLion

# Initialize a TaskScheduler instance
scheduler = YoungLion.TaskScheduler()
```

---

### **Key Features and Methods**

#### **1. Scheduling Tasks**
The `schedule_task` method allows scheduling tasks with optional repeating intervals and priority control.

**Parameters**:
- `task`: The callable function to execute.
- `interval`: Time interval (in seconds) for repeating tasks. If `None`, the task runs only once.
- `repeat`: Whether the task repeats (`True`) or runs once (`False`).
- `priority`: Lower values indicate higher priority.

**Returns**: A unique `task_id` for tracking the task.

**Example: One-Time Task**
```python
# Schedule a one-time task
task_id = scheduler.schedule_task(lambda: print("Hello, world!"), repeat=False)
```

**Example: Repeating Task**
```python
# Schedule a repeating task with an interval of 5 seconds
task_id = scheduler.schedule_task(lambda: print("Repeating task"), interval=5, repeat=True)
```

**Example: Priority-Based Task Scheduling**
```python
# Schedule tasks with different priorities
scheduler.schedule_task(lambda: print("High priority task"), priority=1)
scheduler.schedule_task(lambda: print("Low priority task"), priority=10)
```

---

#### **2. Pausing and Resuming Tasks**
Tasks can be paused and resumed using their unique `task_id`.

**Pausing a Task**
```python
# Pause a running task
scheduler.pause_task(task_id)
```

**Resuming a Task**
```python
# Resume a paused task
scheduler.resume_task(task_id)
```

**Example: Pausing and Resuming**
```python
# Pause and resume a repeating task
scheduler.pause_task(task_id)
scheduler.resume_task(t