diff --git a/README.md b/README.md index b904620..c996ce4 100644 --- a/README.md +++ b/README.md @@ -9,3 +9,17 @@ This project is inspired by the simplicity and clarity of gobyexample.com. ## Overview This project is built using the [hugo](https://gohugo.io/) static site generator, with the [hugo bearblog theme](https://github.com/janraasch/hugo-bearblog/). + +## TODO + +- [ ] Add more examples + - [ ] File I/O + - [ ] Regular expressions + - [ ] Web scraping + - [ ] Web Requests + - [ ] SQLite + - [ ] Logging + - [ ] Debugging + - [ ] Profiling + - [ ] Performance + - [ ] Multithreading diff --git a/content/_index.md b/content/_index.md index b23dbe7..e432243 100644 --- a/content/_index.md +++ b/content/_index.md @@ -4,8 +4,6 @@ title = "Python by example" Python is an open-source programming language known for its simplicity and readability. It is used in a wide range of applications, from web development to data analysis and machine learning. -This is a hands-on collection of Python examples, meant to be a reference for beginners and experienced programmers willing to learn it. +This is a hands-on collection of bit-sized Python examples, meant to be a reference for beginners and experienced programmers. This project is inspired by the simplicity and clarity of [gobyexample.com](https://gobyexample.com). - -[Hello world](hello-world/) diff --git a/content/args-kwargs.md b/content/args-kwargs.md new file mode 100644 index 0000000..8266794 --- /dev/null +++ b/content/args-kwargs.md @@ -0,0 +1,162 @@ ++++ +title = "Args and Kwargs" ++++ + +## Args and Kwargs in Python + +`*args` and `**kwargs` allow functions to accept a variable number of arguments. This makes functions more flexible by letting them handle different numbers of parameters. + +### *args (Variable Positional Arguments) + +`*args` allows a function to accept any number of positional arguments. The arguments are passed as a tuple: + +```python +def sum_all(*args): + total = 0 + for num in args: + total += num + return total + +print(sum_all(1, 2, 3)) # Output: 6 +print(sum_all(1, 2, 3, 4, 5)) # Output: 15 +print(sum_all(10)) # Output: 10 +``` + +### **kwargs (Variable Keyword Arguments) + +`**kwargs` allows a function to accept any number of keyword arguments. The arguments are passed as a dictionary: + +```python +def print_info(**kwargs): + for key, value in kwargs.items(): + print(f"{key}: {value}") + +print_info(name="Alice", age=30, city="New York") +# Output: +# name: Alice +# age: 30 +# city: New York +``` + +### Combining Regular Parameters with *args and **kwargs + +You can mix regular parameters, `*args`, and `**kwargs` in the same function: + +```python +def greet(greeting, *names, **options): + message = greeting + if names: + message += " " + ", ".join(names) + if options.get("excited"): + message += "!" + if options.get("uppercase"): + message = message.upper() + return message + +print(greet("Hello", "Alice", "Bob")) # Output: Hello Alice, Bob +print(greet("Hi", "Charlie", excited=True)) # Output: Hi Charlie! +print(greet("Hey", uppercase=True)) # Output: HEY +``` + +### Unpacking Arguments + +You can also use `*` and `**` to unpack arguments when calling functions: + +```python +def multiply(a, b, c): + return a * b * c + +# Unpacking a list with * +numbers = [2, 3, 4] +result = multiply(*numbers) # Same as multiply(2, 3, 4) +print(result) # Output: 24 + +# Unpacking a dictionary with ** +def introduce(name, age, city): + return f"My name is {name}, I'm {age} years old, and I live in {city}" + +person = {"name": "Alice", "age": 25, "city": "Boston"} +print(introduce(**person)) # Output: My name is Alice, I'm 25 years old, and I live in Boston +``` + +### Practical Examples + +#### Function with Default Values and Variable Arguments + +```python +def create_user(username, email, *groups, **preferences): + user = { + "username": username, + "email": email, + "groups": list(groups), + "preferences": preferences + } + return user + +user = create_user("alice", "alice@email.com", "admin", "editor", + theme="dark", notifications=True) +print(user) +# Output: {'username': 'alice', 'email': 'alice@email.com', +# 'groups': ['admin', 'editor'], +# 'preferences': {'theme': 'dark', 'notifications': True}} +``` + +#### Wrapper Functions + +```python +def log_function_call(func): + def wrapper(*args, **kwargs): + print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}") + result = func(*args, **kwargs) + print(f"Result: {result}") + return result + return wrapper + +@log_function_call +def add(a, b): + return a + b + +add(3, 5) +# Output: +# Calling add with args: (3, 5), kwargs: {} +# Result: 8 +``` + +#### Flexible Configuration Function + +```python +def configure_server(host, port=8000, *middlewares, **settings): + config = { + "host": host, + "port": port, + "middlewares": list(middlewares), + "settings": settings + } + return config + +config = configure_server("localhost", 3000, "auth", "cors", + debug=True, timeout=30) +print(config) +# Output: {'host': 'localhost', 'port': 3000, +# 'middlewares': ['auth', 'cors'], +# 'settings': {'debug': True, 'timeout': 30}} +``` + +### Order Matters + +When using all parameter types together, they must be in this specific order: + +```python +def example_function(required_arg, default_arg="default", *args, **kwargs): + print(f"Required: {required_arg}") + print(f"Default: {default_arg}") + print(f"Args: {args}") + print(f"Kwargs: {kwargs}") + +example_function("hello", "world", 1, 2, 3, key="value") +# Output: +# Required: hello +# Default: world +# Args: (1, 2, 3) +# Kwargs: {'key': 'value'} +``` diff --git a/content/boolean.md b/content/boolean.md new file mode 100644 index 0000000..e23b32b --- /dev/null +++ b/content/boolean.md @@ -0,0 +1,28 @@ ++++ +title = "Boolean" ++++ + +## Boolean in Python + +The boolean represents the truth values `True` and `False`. They are used to evaluate conditions in control structures such as `if` statements and loops. + +```python +is_true = True +is_false = False +``` + +Logical operations can be performed on boolean values in Python, such as `and`, `or`, and `not`: + +```python +# AND +result = True and False +print(result) # Output: False + +# OR +result = True or False +print(result) # Output: True + +# NOT +result = not True +print(result) # Output: False +``` diff --git a/content/classes.md b/content/classes.md new file mode 100644 index 0000000..401c317 --- /dev/null +++ b/content/classes.md @@ -0,0 +1,28 @@ ++++ +title = "Classes" ++++ + +## Classes in Python + +Python is an object-oriented programming language, which means that it provides features that support object-oriented programming (OOP). One of the key features of OOP is the ability to define classes, which are user-defined data structures that model real-world entities. + +A class is a blueprint for creating objects (instances), providing initial values for state (attributes) and implementations of behavior (methods). + +```python +class Person: + def __init__(self, name, age): + self.name = name + self.age = age + + def greet(self): + return f"Hello, my name is {self.name} and I am {self.age} years old." +``` + +In the example above, we define a `Person` class with two attributes (`name` and `age`) and a method (`greet`). The `__init__` method is a special method called a constructor, which is used to initialize the object's state. + +To create an instance of a class, we call the class as if it were a function, passing the necessary arguments to the constructor. + +```python +person = Person("Alice", 30) +print(person.greet()) # Output: Hello, my name is Alice and I am 30 years old. +``` diff --git a/content/csv.md b/content/csv.md new file mode 100644 index 0000000..a063414 --- /dev/null +++ b/content/csv.md @@ -0,0 +1,124 @@ ++++ +title = "CSV" ++++ + +## CSV in Python + +Python provides the `csv` module to work with CSV files easily. + +### Reading CSV Files + +The most basic way to read a CSV file is with the `csv.reader` function, which returns an iterable that provides each row as a list of strings. + +```python +import csv + +# Reading a CSV file +with open('data.csv', 'r', newline='') as file: + # Create a CSV reader + csv_reader = csv.reader(file) + + # Read the header + headers = next(csv_reader) + print(f"Headers: {headers}") + + # Read the data rows + for row in csv_reader: + print(row) +``` + +### Reading CSV as Dictionary + +When you want to access data by column names rather than indices, the `csv.DictReader` class is more convenient. It returns each row as a dictionary where the keys are taken from the header row. + +```python +import csv + +# Reading CSV as dictionary (using column names as keys) +with open('data.csv', 'r', newline='') as file: + csv_reader = csv.DictReader(file) + + for row in csv_reader: + # Access values by column name + print(f"Name: {row['name']}, Age: {row['age']}") +``` + +### Writing CSV Files + +To create new CSV files, you can use the `csv.writer` class. This allows you to write rows of data to the file, either one at a time or multiple rows at once. + +```python +import csv + +# Sample data +data = [ + ['name', 'age', 'city'], + ['Alice', '30', 'New York'], + ['Bob', '25', 'Los Angeles'], + ['Charlie', '35', 'Chicago'] +] + +# Writing to a CSV file +with open('output.csv', 'w', newline='') as file: + csv_writer = csv.writer(file) + + # Write multiple rows at once + csv_writer.writerows(data) + + # Or write one row at a time + # for row in data: + # csv_writer.writerow(row) +``` + +### Writing Dictionary to CSV + +If your data is organized as dictionaries, you can use the `csv.DictWriter` class to write it to a CSV file. This is particularly useful when you already have data in a dictionary format or when working with JSON data. + +```python +import csv + +# Sample data as list of dictionaries +data = [ + {'name': 'Alice', 'age': '30', 'city': 'New York'}, + {'name': 'Bob', 'age': '25', 'city': 'Los Angeles'}, + {'name': 'Charlie', 'age': '35', 'city': 'Chicago'} +] + +# Writing dictionary to CSV file +with open('dict_output.csv', 'w', newline='') as file: + # Define column names (fieldnames) + fieldnames = ['name', 'age', 'city'] + + # Create DictWriter + writer = csv.DictWriter(file, fieldnames=fieldnames) + + # Write header + writer.writeheader() + + # Write data rows + writer.writerows(data) +``` + +### CSV Dialect Options + +CSV files may use different delimiters, quote characters, or other formatting options. Python allows you to customize these settings by defining a CSV dialect, which lets you work with various CSV formats. + +```python +import csv + +# Custom CSV dialect +csv.register_dialect('custom', + delimiter=';', # Use semicolon as separator + quotechar='"', # Quote character + doublequote=True, # Double quotes are escaped by doubling them + skipinitialspace=True, # Skip spaces after delimiter + lineterminator='\n', # Line break character + quoting=csv.QUOTE_MINIMAL # Quote only when necessary +) + +# Use custom dialect +with open('custom.csv', 'w', newline='') as file: + writer = csv.writer(file, dialect='custom') + writer.writerow(['name', 'age', 'city']) + writer.writerow(['Alice', '30', 'New York']) +``` diff --git a/content/decorators.md b/content/decorators.md new file mode 100644 index 0000000..7203ed3 --- /dev/null +++ b/content/decorators.md @@ -0,0 +1,172 @@ ++++ +title = "Decorators" ++++ + +## Decorators in Python + +Decorators are a powerful feature in Python that allow you to modify the behavior of functions or methods without changing their source code. They are applied using the `@decorator_name` syntax above a function definition. + +### Basic Decorator + +Here's a simple decorator that prints a message before and after a function executes: + +```python +def my_decorator(func): + def wrapper(): + print("Before function call") + func() + print("After function call") + return wrapper + +@my_decorator +def say_hello(): + print("Hello!") + +say_hello() +# Output: +# Before function call +# Hello! +# After function call +``` + +Note we use the `wrapper` function to wrap the original function `func`. + +### Decorators with Arguments + +To create decorators that work with functions that take arguments, the wrapper function should accept `*args` and `**kwargs`: + +```python +def my_decorator(func): + def wrapper(*args, **kwargs): + print("Before function call") + result = func(*args, **kwargs) + print("After function call") + return result + return wrapper + +@my_decorator +def add(a, b): + return a + b + +print(add(3, 5)) +# Output: +# Before function call +# After function call +# 8 +``` + +### Decorators with Parameters + +You can also create decorators that accept their own parameters: + +```python +def repeat(n): + def decorator(func): + def wrapper(*args, **kwargs): + for _ in range(n): + result = func(*args, **kwargs) + return result + return wrapper + return decorator + +@repeat(3) +def greet(name): + print(f"Hello, {name}!") + +greet("Alice") +# Output: +# Hello, Alice! +# Hello, Alice! +# Hello, Alice! +``` + +### Practical Examples + +Decorators are commonly used for: + +#### Timing Functions + +```python +import time + +def timer(func): + def wrapper(*args, **kwargs): + start = time.time() + result = func(*args, **kwargs) + print(f"Function {func.__name__} took {time.time() - start:.2f} seconds to run") + return result + return wrapper + +@timer +def slow_function(): + time.sleep(1) + +slow_function() +# Output: Function slow_function took 1.00 seconds to run +``` + +#### Authentication + +```python +def require_auth(func): + def wrapper(user, *args, **kwargs): + if not user.is_authenticated: + raise Exception("Authentication required") + return func(user, *args, **kwargs) + return wrapper + +@require_auth +def view_profile(user): + return f"Welcome {user.name}!" +``` + +#### Caching Results + +```python +def cache(func): + stored_results = {} + + def wrapper(*args): + if args in stored_results: + return stored_results[args] + result = func(*args) + stored_results[args] = result + return result + + return wrapper + +@cache +def fibonacci(n): + if n <= 1: + return n + return fibonacci(n-1) + fibonacci(n-2) + +print(fibonacci(35)) # Fast even for large values +``` + +### Built-in Decorators + +Python has several built-in decorators: + +```python +# @property turns a method into a property +class Circle: + def __init__(self, radius): + self._radius = radius + + @property + def area(self): + return 3.14 * self._radius ** 2 + +# @classmethod creates a method that receives the class as the first argument +class MyClass: + @classmethod + def from_string(cls, string): + return cls(string.strip()) + +# @staticmethod creates a method that doesn't receive the instance or class +class MathUtils: + @staticmethod + def add(a, b): + return a + b +``` diff --git a/content/dictionaries.md b/content/dictionaries.md new file mode 100644 index 0000000..0c080ee --- /dev/null +++ b/content/dictionaries.md @@ -0,0 +1,32 @@ ++++ +title = "Dictionaries" ++++ + +## Dictionaries in Python + +In Python, hashmaps are implemented as dictionaries. + +They can be declared straightforwardly by using curly brackets `{}` or by using the `dict()` function. + +```python +my_dict = {"one": 1, "two": 2, "three": 3} +my_other_dict = dict() +``` + +Set and Get are done by using a key. + +```python +my_dict = {} +my_dict["four"] = 4 +print(my_dict["four"]) # Output: 4 +``` + +One dictionary can hold multiple types as key or values. + +```python +my_dict = { + "one": 1, + 2.5: True, + [1, 2]: {"three": 3} + } +``` diff --git a/content/enums.md b/content/enums.md new file mode 100644 index 0000000..eba5afa --- /dev/null +++ b/content/enums.md @@ -0,0 +1,60 @@ ++++ +title = "Enums" ++++ + +## Enums in Python + +Enumerations (or enums) in Python are a set of symbolic names bound to unique, constant values. + +```python +from enum import Enum + +# Basic enum definition +class Color(Enum): + RED = 1 + GREEN = 2 + BLUE = 3 + +# Accessing enum members +print(Color.RED) # Output: Color.RED +print(Color.RED.name) # Output: RED +print(Color.RED.value) # Output: 1 +``` + +Enums can be used for comparison and iteration: + +```python +# Comparing enum members +color = Color.RED +if color == Color.RED: + print("The color is red") # This will be printed + +# Iterating through enum members +for color in Color: + print(color.name, color.value) +# Output: +# RED 1 +# GREEN 2 +# BLUE 3 +``` + +For enums where each value must be unique, use `IntEnum` or `unique`: + +```python +from enum import IntEnum, unique + +# IntEnum forces values to be integers +class Status(IntEnum): + ERROR = 0 + PENDING = 1 + RUNNING = 2 + SUCCESS = 3 + +# The @unique decorator ensures no duplicate values +@unique +class UniqueColor(Enum): + RED = 1 + GREEN = 2 + BLUE = 3 + # DUPLICATE = 1 # This would raise an error +``` diff --git a/content/errors.md b/content/errors.md new file mode 100644 index 0000000..41873bc --- /dev/null +++ b/content/errors.md @@ -0,0 +1,89 @@ ++++ +title = "Errors" ++++ + +## Error Handling in Python + +In Python, errors are handled using try-except blocks. When an error occurs, Python raises an exception which can be caught and processed. + +### Basic Try-Except + +The `try` block contains code that might cause an exception, and the `except` block contains code to handle the exception. + +```python +try: + x = 10 / 0 # Division by zero causes an error +except: + print("An error occurred") # Output: An error occurred +``` + +### Catching Specific Exceptions + +You can catch specific exceptions by specifying the exception type. + +```python +try: + x = 10 / 0 +except ZeroDivisionError: + print("Division by zero") # Output: Division by zero +except ValueError: + print("Invalid value") +``` + +### Accessing Exception Information + +You can access the exception information using the `as` keyword. + +```python +try: + x = 10 / 0 +except ZeroDivisionError as error: + print(f"Error message: {error}") # Output: Error message: division by zero +``` + +### Finally Block + +The `finally` block is executed regardless of whether an exception occurred or not. + +```python +try: + x = 10 / 2 + print(x) # Output: 5.0 +except ZeroDivisionError: + print("Division by zero") +finally: + print("This always executes") # Output: This always executes +``` + +### Else Block + +The `else` block is executed only if no exceptions occur in the try block. + +```python +try: + x = 10 / 5 +except ZeroDivisionError: + print("Division by zero") +else: + print(f"Result is {x}") # Output: Result is 2.0 +``` + +### Raising Exceptions + +You can raise exceptions using the `raise` keyword. + +```python +x = -5 +if x < 0: + raise ValueError("x cannot be negative") # Raises: ValueError: x cannot be negative +``` + +### Common Built-in Exceptions + +Python has many built-in exceptions such as: + +- `ValueError`: Raised when a function receives an argument of correct type but invalid value +- `TypeError`: Raised when an operation is performed on an inappropriate type +- `IndexError`: Raised when trying to access an index that is out of range +- `KeyError`: Raised when a dictionary key is not found +- `FileNotFoundError`: Raised when trying to access a file that does not exist diff --git a/content/formatting.md b/content/formatting.md new file mode 100644 index 0000000..6d9c215 --- /dev/null +++ b/content/formatting.md @@ -0,0 +1,29 @@ ++++ +title = "Formatting" ++++ + +## Formatting in Python + +Formatting strings in python is very convenient, mostly because most types have a `__str__` method that returns a string representation of the object. Because of this, we can format most types seamlessly. + +The most common way to format strings in Python is by using the `format` method. This method allows you to insert values into a string by using placeholders and passing the values as arguments to the `format` method. + +By using the `format` method, you can insert values into a string in a specific order defined by the placeholders `{}`. + +```python +name = "Alice" +age = 30 + +message = "Hello, my name is {} and I am {} years old.".format(name, age) +print(message) # Output: Hello, my name is Alice and I am 30 years old. +``` + +From python 3.6 onwards, you can also use f-strings to format strings. F-strings Let you embed expressions inside string literals, using curly braces `{}`. + +```python +name = "Alice" +age = 30 + +message = f"Hello, my name is {name} and I am {age} years old." +print(message) # Output: Hello, my name is Alice and I am 30 years old. +``` diff --git a/content/functions.md b/content/functions.md new file mode 100644 index 0000000..c110c8d --- /dev/null +++ b/content/functions.md @@ -0,0 +1,21 @@ ++++ +title = "Functions" ++++ + +## Functions in Python + +Like in other programming languages, a function in Python is a block of code that performs a specific task. Functions are defined using the `def` keyword followed by the function name and parentheses `()`. The function body is indented, and it may include a `return` statement to return a value. + +```python +def add(a, b): + return a + b +``` + +Functions can have parameters and return values. In the example above, the `add` function takes two parameters `a` and `b` and returns their sum. + +We can also use default arguments. Default arguments are used when the function is called without passing a value for that argument. + +```python +def greet(name="World"): + return f"Hello, {name}!" +``` diff --git a/content/hello-world.md b/content/hello-world.md index 67e9e3c..f880951 100644 --- a/content/hello-world.md +++ b/content/hello-world.md @@ -1,5 +1,5 @@ +++ -title = "hello-world" +title = "Hello World" +++ ## Hello world in Python diff --git a/content/if-else.md b/content/if-else.md new file mode 100644 index 0000000..e517508 --- /dev/null +++ b/content/if-else.md @@ -0,0 +1,35 @@ ++++ +title = "If Else" ++++ + +## If Else in Python + +The `if` keyword is used to create a conditional statement that executes a block of code if a condition is true. + +```python +x = 5 +if x > 3: + print("x is greater than 3") +``` + +The `else` keyword can be used to execute a block of code if the condition is false. + +```python +x = 2 +if x > 3: + print("x is greater than 3") +else: + print("x is less than or equal to 3") +``` + +The `elif` keyword can be used to create multiple conditions in a single `if` statement. + +```python +x = 3 +if x > 3: + print("x is greater than 3") +elif x < 3: + print("x is less than 3") +else: + print("x is equal to 3") +``` diff --git a/content/json.md b/content/json.md new file mode 100644 index 0000000..3c8452c --- /dev/null +++ b/content/json.md @@ -0,0 +1,80 @@ ++++ +title = "JSON" ++++ + +## JSON in Python + +Python provides the `json` module to work with JSON data. + +### Encoding (Python to JSON) + +Converting Python objects to JSON strings is called encoding, or serializing, or marshaling. The `json` module provides two main functions for this: `json.dumps()` which converts a Python object to a JSON string, and `json.dump()` which writes JSON data to a file. + +```python +import json + +# Python dictionary +data = { + "name": "Alice", + "age": 30, + "is_student": False, + "courses": ["Python", "Data Science", "Web Development"], + "address": { + "city": "New York", + "country": "USA" + } +} + +# Convert Python object to JSON string +json_string = json.dumps(data) +print(json_string) +# Output: {"name": "Alice", "age": 30, "is_student": false, "courses": ["Python", "Data Science", "Web Development"], "address": {"city": "New York", "country": "USA"}} + +# Pretty-print with indentation +pretty_json = json.dumps(data, indent=4) +print(pretty_json) +# Output: +# { +# "name": "Alice", +# "age": 30, +# "is_student": false, +# "courses": [ +# "Python", +# "Data Science", +# "Web Development" +# ], +# "address": { +# "city": "New York", +# "country": "USA" +# } +# } + +# Write JSON to a file +with open('data.json', 'w') as file: + json.dump(data, file, indent=4) +``` + +### Decoding (JSON to Python) + +Converting JSON strings to Python objects is called decoding, or deserializing, or unmarshaling. The `json` module provides two main functions for this: `json.loads()` which converts a JSON string to a Python object, and `json.load()` which reads JSON data from a file. + +```python +import json + +# JSON string +json_string = '{"name": "Bob", "age": 25, "is_student": true, "grades": [90, 85, 88]}' + +# Convert JSON string to Python object +python_data = json.loads(json_string) +print(python_data) +# Output: {'name': 'Bob', 'age': 25, 'is_student': True, 'grades': [90, 85, 88]} + +# Access the data +print(python_data["name"]) # Output: Bob +print(python_data["grades"][0]) # Output: 90 + +# Read JSON from a file +with open('data.json', 'r') as file: + file_data = json.load(file) + print(file_data) +``` diff --git a/content/list.md b/content/list.md new file mode 100644 index 0000000..cd50ddf --- /dev/null +++ b/content/list.md @@ -0,0 +1,87 @@ ++++ +title = "List" ++++ + +## Lists in Python + +In Python, there is no notion of fixed-size arrays. Instead, Python provides a more flexible and powerful data structure called a **list**. + +A list is a collection of items that are ordered and changeable. Lists are defined by enclosing the elements in square brackets `[]`. + +```python +my_list = [1, 2, 3, 4, 5] +``` + +A list can contain elements of different data types. + +```python +mixed_list = [1, 2.5, "hello", [5, 6, 7]] +``` + +Lists can be accessed by index, mutable, and can be sliced. + +Note that they are zero-indexed, meaning that the first element is at index 0. + +```python +my_list = [1, 2, 3, 4, 5] +print(my_list[0]) # Output: 1 + +my_list[0] = 10 +print(my_list) # Output: [10, 2, 3, 4, 5] + +print(my_list[1:3]) # Output: [2, 3] +``` + +Lists can be concatenated using the `+` operator. + +```python +list = [1, 2, 3] + [4, 5, 6] +print(list) # Output: [1, 2, 3, 4, 5, 6] +``` + +We can also use the `*` operator to repeat the elements of a list. + +```python +list = [1, 2, 3] * 3 +print(list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3] +``` + +To access the length of a list, we can use the `len()` function. + +```python +my_list = [1, 2, 3, 4, 5] +print(len(my_list)) # Output: 5 +``` + +To get the last element of a list, we can use negative indexing. + +```python +my_list = [1, 2, 3, 4, 5] +print(my_list[-1]) # Output: 5 +``` + +They offer a handful of methods to manipulate the list, such as `append()`, `insert()`, `remove()`, `pop()`, `count()`, `sort()`, and `reverse()`. + +```python +my_list = [1, 2, 3, 4, 5] +my_list.append(6) +print(my_list) # Output: [1, 2, 3, 4, 5, 6] + +my_list.insert(2, 2.5) +print(my_list) # Output: [1, 2, 2.5, 3, 4, 5, 6] + +my_list.remove(2.5) +print(my_list) # Output: [1, 2, 3, 4, 5, 6] + +my_list.pop() +print(my_list) # Output: [1, 2, 3, 4, 5] + +print(my_list.count(3)) # Output: 1 + +new_list = [3, 1, 4, 1, 5] +new_list.sort() +print(new_list) # Output: [1, 1, 3, 4, 5] + +new_list.reverse() +print(new_list) # Output: [5, 4, 3, 1, 1] +``` diff --git a/content/logging.md b/content/logging.md new file mode 100644 index 0000000..610e6aa --- /dev/null +++ b/content/logging.md @@ -0,0 +1,143 @@ ++++ +title = "Logging" ++++ + +## Logging in Python + +Logging is a way to track events that happen when your program runs. It's much better than using `print()` statements because you can control the level of detail and where the log messages go. + +### Basic Logging + +Python's `logging` module provides a simple way to add logging to your programs: + +```python +import logging + +logging.debug("This is a debug message") +logging.info("This is an info message") +logging.warning("This is a warning message") +logging.error("This is an error message") +logging.critical("This is a critical message") + +# Output (only warning and above are shown by default): +# WARNING:root:This is a warning message +# ERROR:root:This is an error message +# CRITICAL:root:This is a critical message +``` + +### Setting the Log Level + +You can control which messages are displayed by setting the log level: + +```python +import logging + +# Set the minimum level to INFO +logging.basicConfig(level=logging.INFO) + +logging.debug("This won't be shown") +logging.info("This will be shown") +logging.warning("This will be shown") + +# Output: +# INFO:root:This will be shown +# WARNING:root:This will be shown +``` + +### Formatting Log Messages + +You can customize how log messages appear: + +```python +import logging + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s" +) + +logging.info("Application started") +logging.warning("Low memory warning") + +# Output: +# 2024-01-15 10:30:45,123 - INFO - Application started +# 2024-01-15 10:30:45,456 - WARNING - Low memory warning +``` + +### Logging to a File + +Instead of printing to the console, you can save logs to a file: + +```python +import logging + +logging.basicConfig( + filename="app.log", + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s" +) + +logging.info("User logged in") +logging.error("Database connection failed") + +# Messages are saved to app.log file instead of console +``` + +### Using Loggers + +For more control, you can create your own logger: + +```python +import logging + +# Create a logger +logger = logging.getLogger("my_app") +logger.setLevel(logging.DEBUG) + +# Create a console handler +console_handler = logging.StreamHandler() +console_handler.setLevel(logging.INFO) + +# Create a formatter +formatter = logging.Formatter("%(name)s - %(levelname)s - %(message)s") +console_handler.setFormatter(formatter) + +# Add handler to logger +logger.addHandler(console_handler) + +logger.debug("This won't show (below INFO level)") +logger.info("Application initialized") +logger.error("Something went wrong") + +# Output: +# my_app - INFO - Application initialized +# my_app - ERROR - Something went wrong +``` + +### Logging Variables + +You can include variables in your log messages: + +```python +import logging + +logging.basicConfig(level=logging.INFO) + +username = "alice" +age = 25 + +logging.info(f"User {username} logged in, age: {age}") +# Or using % formatting (older style) +logging.info("User %s logged in, age: %d", username, age) + +# Output: +# INFO:root:User alice logged in, age: 25 +``` + +### Log Levels Explained + +- **DEBUG**: Detailed information for diagnosing problems +- **INFO**: General information about program execution +- **WARNING**: Something unexpected happened, but the program is still working +- **ERROR**: A serious problem occurred, some functionality failed +- **CRITICAL**: A very serious error occurred, the program might stop diff --git a/content/loop.md b/content/loop.md new file mode 100644 index 0000000..5bffe13 --- /dev/null +++ b/content/loop.md @@ -0,0 +1,28 @@ ++++ +title = "Loop" ++++ + +## Loop in Python + +The `for` keyword is used to iterate over a sequence of elements. It is the most common way to perform a loop in Python. + +```python +nums = [1, 2, 3, 4, 5] +for num in nums: + print(num) # Output: 1, 2, 3, 4, 5 +``` + +Usually, the `range()` function is used to generate a sequence of numbers to iterate over. + +```python +for i in range(5): + print(i) # Output: 0, 1, 2, 3, 4 - range(5) generates numbers from 0 to 4 +``` + +The `enumerate()` function can be used to get both the index and the value of each element in a sequence. + +```python +nums = [1, 2, 3, 4, 5] +for i, num in enumerate(nums): + print(f"Index: {i}, Value: {num}") # Output: Index: 0, Value: 1, Index: 1, Value: 2, Index: 2, Value: 3, Index: 3, Value: 4, Index: 4, Value: 5 +``` diff --git a/content/modules-packages.md b/content/modules-packages.md new file mode 100644 index 0000000..5c6b47a --- /dev/null +++ b/content/modules-packages.md @@ -0,0 +1,87 @@ ++++ +title = "Modules and Packages" ++++ + +## Modules and Packages in Python + +A module is a Python file containing definitions and statements. Modules are used to organize code into reusable components. + +### Importing Modules + +To use a module, you need to import it using the `import` statement. + +```python +import math +print(math.sqrt(16)) # Output: 4.0 +``` + +You can import specific functions or variables from a module using the `from` keyword. + +```python +from math import sqrt +print(sqrt(16)) # Output: 4.0 +``` + +You can also rename imported modules or functions using the `as` keyword. + +```python +import math as m +print(m.sqrt(16)) # Output: 4.0 + +from math import sqrt as square_root +print(square_root(16)) # Output: 4.0 +``` + +### Creating Your Own Modules + +To create a module, simply write your Python code in a `.py` file. For example, create a file named `mymodule.py`: + +```python +# mymodule.py +def greet(name): + return f"Hello, {name}!" + +PI = 3.14159 +``` + +Then import and use your module: + +```python +import mymodule +print(mymodule.greet("Alice")) # Output: Hello, Alice! +print(mymodule.PI) # Output: 3.14159 +``` + +### Packages + +A package is a collection of modules organized in directories. A package must contain a special file called `__init__.py` (can be empty) to indicate that the directory is a Python package. + +``` +mypackage/ +├── __init__.py +├── module1.py +└── module2.py +``` + +You can import modules from a package: + +```python +import mypackage.module1 +mypackage.module1.function() + +# Or import specific functions +from mypackage.module2 import function +function() +``` + +### Standard Library + +Python comes with a rich standard library of modules. Some commonly used modules include: + +```python +import os # Operating system interface +import sys # System-specific parameters and functions +import datetime # Date and time functions +import json # JSON encoding and decoding +import random # Generate random numbers +``` diff --git a/content/multi-threading.md b/content/multi-threading.md new file mode 100644 index 0000000..8128106 --- /dev/null +++ b/content/multi-threading.md @@ -0,0 +1,304 @@ ++++ +title = "Multi-threading" ++++ + +## Multithreading in Python + +Multithreading allows your program to run multiple tasks concurrently. While Python's Global Interpreter Lock (GIL) limits true parallelism for CPU-bound tasks, threading is still useful for I/O-bound operations like file reading, network requests, or waiting for user input. + +### Basic Threading + +The `threading` module provides tools for creating and managing threads: + +```python +import threading +import time + +def worker(name): + print(f"Worker {name} starting") + time.sleep(2) # Simulate some work + print(f"Worker {name} finished") + +# Create and start threads +thread1 = threading.Thread(target=worker, args=("A",)) +thread2 = threading.Thread(target=worker, args=("B",)) + +thread1.start() +thread2.start() + +# Wait for threads to complete +thread1.join() +thread2.join() + +print("All workers finished") + +# Output: +# Worker A starting +# Worker B starting +# Worker A finished +# Worker B finished +# All workers finished +``` + +### Thread with Return Values + +Since threads don't return values directly, you can use a list or queue to collect results: + +```python +import threading +import time + +def calculate_square(number, results, index): + time.sleep(1) # Simulate work + result = number ** 2 + results[index] = result + print(f"Square of {number} is {result}") + +numbers = [2, 3, 4, 5] +results = [None] * len(numbers) +threads = [] + +# Create threads +for i, num in enumerate(numbers): + thread = threading.Thread(target=calculate_square, args=(num, results, i)) + threads.append(thread) + thread.start() + +# Wait for all threads to complete +for thread in threads: + thread.join() + +print(f"Results: {results}") +# Output: +# Square of 2 is 4 +# Square of 3 is 9 +# Square of 4 is 16 +# Square of 5 is 25 +# Results: [4, 9, 16, 25] +``` + +### Using ThreadPoolExecutor + +The `concurrent.futures` module provides a higher-level interface for threading: + +```python +import concurrent.futures +import time + +def fetch_data(url): + print(f"Fetching {url}") + time.sleep(1) # Simulate network request + return f"Data from {url}" + +urls = ["site1.com", "site2.com", "site3.com", "site4.com"] + +# Use ThreadPoolExecutor +with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: + # Submit all tasks + future_to_url = {executor.submit(fetch_data, url): url for url in urls} + + # Get results as they complete + for future in concurrent.futures.as_completed(future_to_url): + url = future_to_url[future] + try: + data = future.result() + print(f"Retrieved: {data}") + except Exception as e: + print(f"Error fetching {url}: {e}") + +# Output: +# Fetching site1.com +# Fetching site2.com +# Retrieved: Data from site1.com +# Retrieved: Data from site2.com +# Fetching site3.com +# Fetching site4.com +# Retrieved: Data from site3.com +# Retrieved: Data from site4.com +``` + +### Thread Synchronization with Locks + +Use locks to prevent race conditions when multiple threads access shared data: + +```python +import threading +import time + +# Shared counter +counter = 0 +lock = threading.Lock() + +def increment_counter(name): + global counter + for i in range(5): + # Acquire lock before modifying shared data + with lock: + current = counter + time.sleep(0.01) # Simulate some processing + counter = current + 1 + print(f"Thread {name}: counter = {counter}") + +# Create threads +thread1 = threading.Thread(target=increment_counter, args=("A",)) +thread2 = threading.Thread(target=increment_counter, args=("B",)) + +thread1.start() +thread2.start() + +thread1.join() +thread2.join() + +print(f"Final counter value: {counter}") +# Output shows interleaved but safe increments: +# Thread A: counter = 1 +# Thread B: counter = 2 +# Thread A: counter = 3 +# Thread B: counter = 4 +# ... +# Final counter value: 10 +``` + +### Producer-Consumer Pattern with Queue + +Use `queue.Queue` for safe communication between threads: + +```python +import threading +import queue +import time +import random + +def producer(q, name): + for i in range(5): + item = f"{name}-item-{i}" + q.put(item) + print(f"Producer {name} created {item}") + time.sleep(random.uniform(0.1, 0.5)) + +def consumer(q, name): + while True: + try: + item = q.get(timeout=2) + print(f"Consumer {name} processed {item}") + time.sleep(random.uniform(0.1, 0.3)) + q.task_done() + except queue.Empty: + print(f"Consumer {name} timed out") + break + +# Create queue +q = queue.Queue() + +# Create threads +producer_thread = threading.Thread(target=producer, args=(q, "P1")) +consumer_thread1 = threading.Thread(target=consumer, args=(q, "C1")) +consumer_thread2 = threading.Thread(target=consumer, args=(q, "C2")) + +# Start threads +producer_thread.start() +consumer_thread1.start() +consumer_thread2.start() + +# Wait for producer to finish +producer_thread.join() + +# Wait for all items to be processed +q.join() + +print("All items processed") +``` + +### Practical Examples + +#### Concurrent File Downloads + +```python +import threading +import time +import urllib.request + +def download_file(url, filename): + print(f"Starting download: {filename}") + time.sleep(2) # Simulate download time + print(f"Completed download: {filename}") + +urls_and_files = [ + ("http://example.com/file1.txt", "file1.txt"), + ("http://example.com/file2.txt", "file2.txt"), + ("http://example.com/file3.txt", "file3.txt"), +] + +# Download sequentially (slow) +start_time = time.time() +for url, filename in urls_and_files: + download_file(url, filename) +sequential_time = time.time() - start_time + +print(f"Sequential downloads took: {sequential_time:.2f} seconds") + +# Download concurrently (faster) +start_time = time.time() +threads = [] +for url, filename in urls_and_files: + thread = threading.Thread(target=download_file, args=(url, filename)) + threads.append(thread) + thread.start() + +for thread in threads: + thread.join() + +concurrent_time = time.time() - start_time +print(f"Concurrent downloads took: {concurrent_time:.2f} seconds") +print(f"Speedup: {sequential_time / concurrent_time:.1f}x") +``` + +#### Background Task Monitor + +```python +import threading +import time + +class TaskMonitor: + def __init__(self): + self.running = False + self.thread = None + + def start_monitoring(self): + self.running = True + self.thread = threading.Thread(target=self._monitor) + self.thread.start() + print("Monitoring started") + + def stop_monitoring(self): + self.running = False + if self.thread: + self.thread.join() + print("Monitoring stopped") + + def _monitor(self): + count = 0 + while self.running: + count += 1 + print(f"Monitor check #{count}") + time.sleep(1) + +# Usage +monitor = TaskMonitor() +monitor.start_monitoring() + +# Do some other work +print("Doing main work...") +time.sleep(5) + +# Stop monitoring +monitor.stop_monitoring() +``` + +### Important Notes + +1. **GIL Limitation**: Python's Global Interpreter Lock prevents true parallelism for CPU-intensive tasks +2. **Best for I/O-bound tasks**: Threading works well for file operations, network requests, and waiting +3. **Use locks for shared data**: Prevent race conditions when multiple threads modify the same variables +4. **Consider ThreadPoolExecutor**: Higher-level interface that's often easier to use +5. **For CPU-bound tasks**: Consider using `multiprocessing` instead of threading diff --git a/content/numbers.md b/content/numbers.md new file mode 100644 index 0000000..8fe1f7d --- /dev/null +++ b/content/numbers.md @@ -0,0 +1,51 @@ ++++ +title = "Numbers" ++++ + +## Numbers in Python + +In Python, numbers are used to represent numerical data. There are three types of numbers in Python: + +- Integers: whole numbers, e.g., 0, 1, 2, 3, etc. +- Floating-point numbers: numbers with a decimal point, e.g., 3.14, 2.718, etc. +- Complex numbers: numbers with a real and imaginary part, e.g., 1 + 2j, 3 - 4j, etc. + +Here are some examples of numbers in Python: + +```python +# Integer +age = 25 +# Floating-point number +pi = 3.14 +# Complex number +z = 1 + 2j +``` + +You can perform arithmetic operations on numbers in Python, such as addition, subtraction, multiplication, and division: + +```python +# Addition +sum = 5 + 3 +# Subtraction +difference = 5 - 3 +# Multiplication +product = 5 * 3 +# Division +quotient = 5 / 3 +``` + +As python is a dynamically typed language, you can change the type of a variable at any time, by doing what is called casting. + +```python +# Casting an integer to a float +x = 1 +y = float(x) +print(y) # Output: 1.0 + +# Casting a float to an integer +x = 1.9 +y = int(x) +print(y) # Output: 1 +``` + +Note that by casting a float to an integer, the decimal part is truncated. diff --git a/content/operators.md b/content/operators.md new file mode 100644 index 0000000..58d6455 --- /dev/null +++ b/content/operators.md @@ -0,0 +1,52 @@ ++++ +title = "Operators" ++++ + +## Operators in Python + +Basic operations can be performed on variables of the same type using operators. + +```python +sum = 5 + 3 +difference = 5 - 3 +product = 5 * 3 +division = 5 / 3 +``` + +Simple operations can be performed on the change of variables, by using the following shorthand operators: + +```python +x = 5 +x += 3 # x = x + 3 +x -= 3 # x = x - 3 +x *= 3 # x = x * 3 +x /= 3 # x = x / 3 +``` + +Additional operators can be used to perform more complex operations: + +```python +# Exponentiation +exponentiation = 5 ** 3 # 5^3=125 +# Floor division +floor_division = 5 // 3 # 5 divided by 3, rounded down to the nearest integer = 1 +# Modulus +modulus = 5 % 3 # 5 divided by 3, remainder = 2 +``` + +Python also provides comparison operators to compare two values: + +```python +# Equal +is_equal = 5 == 3 +# Not equal +is_not_equal = 5 != 3 +# Greater than +is_greater_than = 5 > 3 +# Less than +is_less_than = 5 < 3 +# Greater than or equal to +is_greater_than_or_equal_to = 5 >= 3 +# Less than or equal to +is_less_than_or_equal_to = 5 <= 3 +``` diff --git a/content/random-numbers.md b/content/random-numbers.md new file mode 100644 index 0000000..dc99d3d --- /dev/null +++ b/content/random-numbers.md @@ -0,0 +1,113 @@ ++++ +title = "Random Numbers" ++++ + +## Random Numbers in Python + +Python's `random` module provides functions for generating random numbers and making random choices. This is useful for simulations, games, testing, and many other applications. + +### Basic Random Numbers + +The `random.random()` function returns a random float between 0.0 and 1.0: + +```python +import random + +print(random.random()) # Output: 0.8394304074412543 (varies each time) +print(random.random()) # Output: 0.2847192837465829 (different each time) +``` + +### Random Integers + +Use `random.randint()` to generate random integers within a specific range (inclusive): + +```python +import random + +# Random integer between 1 and 6 (like a dice roll) +dice_roll = random.randint(1, 6) +print(dice_roll) # Output: 4 (could be any number from 1 to 6) + +# Random integer between 10 and 99 +number = random.randint(10, 99) +print(number) # Output: 57 (varies each time) +``` + +### Random Floats in a Range + +Use `random.uniform()` to generate random floats within a specific range: + +```python +import random + +# Random price between 5.00 and 25.00 +price = random.uniform(5.0, 25.0) +print(f"Price: ${price:.2f}") # Output: Price: $18.73 +``` + +### Random Choices from Lists + +Use `random.choice()` to pick a random item from a list: + +```python +import random + +colors = ["red", "green", "blue", "yellow", "purple"] +random_color = random.choice(colors) +print(random_color) # Output: blue (varies each time) +``` + +### Multiple Random Choices + +Use `random.choices()` to pick multiple items (with replacement): + +```python +import random + +numbers = [1, 2, 3, 4, 5] +# Pick 3 random numbers (same number can be picked multiple times) +random_numbers = random.choices(numbers, k=3) +print(random_numbers) # Output: [2, 5, 2] (varies each time) +``` + +### Random Sample (No Duplicates) + +Use `random.sample()` to pick multiple unique items: + +```python +import random + +participants = ["Alice", "Bob", "Charlie", "Diana", "Eve"] +# Pick 3 winners (no duplicates) +winners = random.sample(participants, 3) +print(winners) # Output: ['Charlie', 'Alice', 'Eve'] (varies each time) +``` + +### Shuffling Lists + +Use `random.shuffle()` to randomly rearrange items in a list: + +```python +import random + +deck = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] +random.shuffle(deck) +print(deck) # Output: ['7', 'K', '2', 'A', '9', '3', 'J', '4', '10', '6', '8', 'Q', '5'] +``` + +### Setting a Seed + +Use `random.seed()` to make random numbers reproducible (useful for testing): + +```python +import random + +# Set the seed to get consistent results +random.seed(42) +print(random.randint(1, 100)) # Output: 82 (always the same with seed 42) +print(random.randint(1, 100)) # Output: 15 (always the same sequence) + +# Reset seed to get different results +random.seed(42) +print(random.randint(1, 100)) # Output: 82 (same as first call with seed 42) +``` diff --git a/content/regex.md b/content/regex.md new file mode 100644 index 0000000..786e1a7 --- /dev/null +++ b/content/regex.md @@ -0,0 +1,157 @@ ++++ +title = "Regular Expressions" ++++ + +## Regular Expressions in Python + +Regular expressions (regex) are patterns used to match character combinations in strings. Python's `re` module provides functions for working with regular expressions. + +### Basic Pattern Matching + +The `re.search()` function searches for a pattern in a string and returns a match object if found: + +```python +import re + +text = "Hello, my phone number is 123-456-7890" +pattern = r"\d{3}-\d{3}-\d{4}" # Pattern for phone number + +match = re.search(pattern, text) +if match: + print(match.group()) # Output: 123-456-7890 +``` + +### Finding All Matches + +The `re.findall()` function returns all matches as a list: + +```python +import re + +text = "Contact us at alice@email.com or bob@company.org" +pattern = r"\w+@\w+\.\w+" # Simple email pattern + +emails = re.findall(pattern, text) +print(emails) # Output: ['alice@email.com', 'bob@company.org'] +``` + +### Common Pattern Characters + +Here are the most useful regex characters: + +```python +import re + +# . matches any character except newline +re.search(r"h.t", "hat") # Matches "hat" + +# * matches zero or more of the preceding character +re.search(r"colou*r", "color") # Matches "color" + +# + matches one or more of the preceding character +re.search(r"go+d", "good") # Matches "good" + +# ? matches zero or one of the preceding character +re.search(r"colou?r", "colour") # Matches "colour" + +# \d matches any digit (0-9) +re.search(r"\d+", "I have 5 apples") # Matches "5" + +# \w matches any word character (letters, digits, underscore) +re.search(r"\w+", "hello_world") # Matches "hello_world" + +# \s matches any whitespace character +re.search(r"\s+", "hello world") # Matches the space +``` + +### Character Classes and Ranges + +Square brackets define character classes: + +```python +import re + +# Match vowels +re.findall(r"[aeiou]", "hello world") # Output: ['e', 'o', 'o'] + +# Match digits from 1 to 5 +re.findall(r"[1-5]", "123456789") # Output: ['1', '2', '3', '4', '5'] + +# Match uppercase letters +re.findall(r"[A-Z]", "Hello World") # Output: ['H', 'W'] + +# Match anything except digits +re.findall(r"[^\d]", "abc123") # Output: ['a', 'b', 'c'] +``` + +### Substitution + +The `re.sub()` function replaces matches with a replacement string: + +```python +import re + +text = "The quick brown fox" +# Replace 'fox' with 'dog' +result = re.sub(r"fox", "dog", text) +print(result) # Output: The quick brown dog + +# Remove all digits +text = "abc123def456" +result = re.sub(r"\d", "", text) +print(result) # Output: abcdef +``` + +### Groups and Capturing + +Parentheses create groups to capture parts of the match: + +```python +import re + +text = "John Doe was born on 1990-05-15" +pattern = r"(\w+) (\w+) was born on (\d{4})-(\d{2})-(\d{2})" + +match = re.search(pattern, text) +if match: + print(match.group(1)) # Output: John (first name) + print(match.group(2)) # Output: Doe (last name) + print(match.group(3)) # Output: 1990 (year) +``` + +### Practical Examples + +#### Validating Email + +```python +import re + +def is_valid_email(email): + pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" + return bool(re.match(pattern, email)) + +print(is_valid_email("user@example.com")) # Output: True +print(is_valid_email("invalid.email")) # Output: False +``` + +#### Extracting Numbers from Text + +```python +import re + +text = "The price is $29.99 and shipping costs $5.50" +numbers = re.findall(r"\d+\.\d+", text) +print(numbers) # Output: ['29.99', '5.50'] +``` + +#### Cleaning Text + +```python +import re + +text = "Hello!!! How are you??? Fine." +# Remove multiple punctuation and extra spaces +cleaned = re.sub(r"[!?]+", "", text) # Remove multiple ! or ? +cleaned = re.sub(r"\s+", " ", cleaned) # Replace multiple spaces with single space +print(cleaned.strip()) # Output: Hello How are you Fine. +``` diff --git a/content/sets-tuples.md b/content/sets-tuples.md new file mode 100644 index 0000000..b7f4d13 --- /dev/null +++ b/content/sets-tuples.md @@ -0,0 +1,70 @@ ++++ +title = "Sets and Tuples" ++++ + +## Sets and Tuples in Python + +### Tuples + +Tuples are ordered, immutable collections of elements. They are defined by enclosing elements in parentheses `()`. + +```python +# Creating a tuple +my_tuple = (1, 2, 3, 4, 5) +print(my_tuple) # Output: (1, 2, 3, 4, 5) + +# Tuples can contain elements of different types +mixed_tuple = (1, "hello", True, 3.14) + +# Accessing elements by index +print(my_tuple[0]) # Output: 1 + +# Tuples are immutable +# my_tuple[0] = 10 # This will raise an error + +# Length of a tuple +print(len(my_tuple)) # Output: 5 + +# Tuple unpacking +a, b, c, d, e = my_tuple +print(a, c, e) # Output: 1 3 5 +``` + +### Sets + +Sets are unordered collections of unique elements. They are defined by enclosing elements in curly braces `{}` or by using the `set()` function. + +```python +# Creating a set +my_set = {1, 2, 3, 4, 5} +print(my_set) # Output: {1, 2, 3, 4, 5} + +# Sets automatically remove duplicates +duplicates = {1, 2, 2, 3, 3, 3} +print(duplicates) # Output: {1, 2, 3} + +# Creating a set from a list +list_to_set = set([1, 2, 3, 2, 1]) +print(list_to_set) # Output: {1, 2, 3} + +# Set operations +set1 = {1, 2, 3} +set2 = {3, 4, 5} + +# Union +print(set1 | set2) # Output: {1, 2, 3, 4, 5} + +# Intersection +print(set1 & set2) # Output: {3} + +# Difference +print(set1 - set2) # Output: {1, 2} + +# Adding elements +my_set.add(6) +print(my_set) # Output: {1, 2, 3, 4, 5, 6} + +# Removing elements +my_set.remove(6) +print(my_set) # Output: {1, 2, 3, 4, 5} +``` diff --git a/content/static-typing.md b/content/static-typing.md new file mode 100644 index 0000000..66103d9 --- /dev/null +++ b/content/static-typing.md @@ -0,0 +1,63 @@ ++++ +title = "Static Typing" ++++ + +## Static Typing in Python + +Python is dynamically typed by default, but it supports optional static type hints through type annotations. + +Type hints don't affect runtime behavior but help with code documentation, IDE support, and static type checking tools like mypy. + +It is highly recommended to use type hints in your code for better readability and maintainability. + +```python +# Basic type annotations +name: str = "Alice" +age: int = 30 +height: float = 1.75 +is_student: bool = True +``` + +Function parameters and return types can also be annotated: + +```python +def greet(name: str) -> str: + return f"Hello, {name}!" + +# Function with multiple typed parameters +def calculate_bmi(weight: float, height: float) -> float: + return weight / (height ** 2) +``` + +For more complex types, you can use the `typing` module: + +```python +from typing import List, Dict, Tuple, Optional, Union + +# List of integers +numbers: List[int] = [1, 2, 3, 4, 5] + +# Dictionary with string keys and integer values +scores: Dict[str, int] = {"Alice": 95, "Bob": 87} + +# Tuple with specific types for each position +person: Tuple[str, int, float] = ("Alice", 30, 1.75) + +# Optional type (can be the specified type or None) +middle_name: Optional[str] = None + +# Union type (can be any of the specified types) +id_number: Union[int, str] = "A12345" +``` + +Type checking can be performed using tools like mypy: + +```bash +# Install mypy +pip install mypy + +# Run mypy on your Python file +mypy your_file.py +``` + +This will check for type errors and provide feedback on your code's type annotations. diff --git a/content/strings.md b/content/strings.md new file mode 100644 index 0000000..fc7af58 --- /dev/null +++ b/content/strings.md @@ -0,0 +1,29 @@ ++++ +title = "Strings" ++++ + +## Strings in Python + +In Python, a string is a sequence of characters enclosed in single or double quotes. Strings are immutable, which means that once they are created, their value cannot be changed. + +Here are some examples of strings in Python: + +```python +# Single-line string +name = "Romeo and Juliet" +# Multi-line string +quote = """ +What's in a name? That which we call a rose +By any other name would smell as sweet. +""" +``` + +You can concatenate strings using the `+` operator: + +```python +first_name = "Romeo" +last_name = "Montague" +full_name = first_name + " " + last_name + +print(full_name) # Output: Romeo Montague +``` diff --git a/content/switch.md b/content/switch.md new file mode 100644 index 0000000..b65750a --- /dev/null +++ b/content/switch.md @@ -0,0 +1,32 @@ ++++ +title = "Switch" ++++ + +## Switch in Python + +Previously to Python 3.10, there was no built-in switch statement in Python. Switches were implemented using dictionaries or if-elif-else statements. + +```python +if case == 'case1': + print('case1') +elif case == 'case2': + print('case2') +elif case == 'case3': + print('case3') +else: + print('default case') +``` + +Starting from Python 3.10, the `match` statement was introduced to provide a more concise way to implement switch-case statements. + +```python +match case: + case 'case1': + print('case1') + case 'case2': + print('case2') + case 'case3': + print('case3') + case _: + print('default case') +``` diff --git a/content/testing.md b/content/testing.md new file mode 100644 index 0000000..7d6220f --- /dev/null +++ b/content/testing.md @@ -0,0 +1,110 @@ ++++ +title = "Testing" ++++ + +## Testing in Python + +Testing is essential for ensuring your code works as expected. Python provides several built-in modules for testing, with `unittest` being the most common, but there exist other libraries like `pytest` that are widely used, which offer more features and a simpler syntax. + +### Basic Unit Test + +The `unittest` module provides a framework for writing and running tests. Here's a simple example: + +```python +import unittest + +def add(a, b): + return a + b + +class TestAddFunction(unittest.TestCase): + def test_add_positive_numbers(self): + self.assertEqual(add(1, 2), 3) + + def test_add_negative_numbers(self): + self.assertEqual(add(-1, -1), -2) + +if __name__ == '__main__': + unittest.main() +``` + +### Common Assertions + +The `unittest` module provides several assertion methods: + +```python +import unittest + +class TestAssertions(unittest.TestCase): + def test_assertions(self): + self.assertEqual(1 + 1, 2) # Check if two values are equal + self.assertNotEqual(1 + 1, 3) # Check if two values are not equal + self.assertTrue(1 < 2) # Check if a value is True + self.assertFalse(1 > 2) # Check if a value is False + self.assertIn(1, [1, 2, 3]) # Check if a value is in a sequence + self.assertNotIn(4, [1, 2, 3]) # Check if a value is not in a sequence + self.assertIsNone(None) # Check if a value is None + self.assertIsNotNone(1) # Check if a value is not None +``` + +### Using pytest + +`pytest` is a popular alternative to `unittest` that is simpler to use. Install it using `pip install pytest`: + +```python +# test_example.py +def add(a, b): + return a + b + +def test_add(): + assert add(1, 2) == 3 + assert add(-1, -1) == -2 +``` + +Run the test with the command `pytest test_example.py`. + +### Test Fixtures + +Test fixtures are special setup functions that prepare the testing environment. Unlike regular variables or functions, fixtures are managed by the testing framework and can be easily shared between tests: + +```python +import pytest + +@pytest.fixture +def sample_data(): + return [1, 2, 3, 4, 5] + +def test_sum(sample_data): + assert sum(sample_data) == 15 + +def test_length(sample_data): + assert len(sample_data) == 5 +``` + +### Mock Objects + +The `unittest.mock` module is used to replace parts of your system under test: + +```python +from unittest.mock import Mock + +# Create a mock object +mock_database = Mock() +mock_database.get_user.return_value = {"id": 1, "name": "Alice"} + +# Use the mock object +user = mock_database.get_user(1) +print(user["name"]) # Output: Alice + +# Verify the mock was called correctly +mock_database.get_user.assert_called_once_with(1) +``` + +### Test Coverage + +You can check how much of your code is covered by tests using the `coverage` module: + +```bash +pip install coverage +coverage run -m pytest test_example.py +coverage report +``` diff --git a/content/time.md b/content/time.md new file mode 100644 index 0000000..a797c83 --- /dev/null +++ b/content/time.md @@ -0,0 +1,105 @@ ++++ +title = "Time" ++++ + +## Time in Python + +Python provides several modules for working with dates and times. The most commonly used are `time` and `datetime`. + +### The `time` Module + +The `time` module provides functions for working with time-related operations: + +```python +import time + +# Get current timestamp in seconds since the epoch (January 1, 1970) +current_time = time.time() +print(current_time) # Output: 1716316800.1234 (example value) + +# Sleep for a specified number of seconds +time.sleep(1) # Pause execution for 1 second + +# Get formatted time +local_time = time.localtime() +formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time) +print(formatted_time) # Output: 2025-05-21 14:30:00 (example) +``` + +### The `datetime` Module + +The `datetime` module provides classes for manipulating dates and times. + +You would want to use is over the time modul in the case you need to work with dates and times in a more human-readable format, instead of just a timestamp. + +```python +from datetime import datetime, timedelta + +# Get current date and time +now = datetime.now() +print(now) # Output: 2025-05-21 14:30:00.123456 (example) + +# Create a specific date and time +specific_date = datetime(2025, 5, 21, 14, 30) +print(specific_date) # Output: 2025-05-21 14:30:00 + +# Format a datetime +formatted = now.strftime("%Y-%m-%d %H:%M:%S") +print(formatted) # Output: 2025-05-21 14:30:00 + +# Parse a string into a datetime +date_string = "2025-05-21 14:30:00" +parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S") +print(parsed_date) # Output: 2025-05-21 14:30:00 +``` + +### Time Arithmetic + +You can perform arithmetic operations with `timedelta`: + +```python +from datetime import datetime, timedelta + +now = datetime.now() + +# Add 1 day +tomorrow = now + timedelta(days=1) +print(tomorrow) + +# Subtract 1 hour +one_hour_ago = now - timedelta(hours=1) +print(one_hour_ago) + +# Calculate difference between two datetimes +future_date = datetime(2025, 12, 31) +time_difference = future_date - now +print(f"Days until New Year: {time_difference.days}") +``` + +### Time Comparison + +Datetime objects can be easily compared using standard comparison operators: + +```python +from datetime import datetime + +date1 = datetime(2025, 5, 21, 14, 30) +date2 = datetime(2025, 5, 21, 15, 45) +date3 = datetime(2025, 5, 21, 14, 30) + +# Check if one time is later than another +print(date2 > date1) # Output: True + +# Check if times are equal +print(date1 == date3) # Output: True + +# Check if time is earlier +print(date1 < date2) # Output: True + +# Find the earliest/latest time +dates = [date2, date1, date3] +earliest = min(dates) +latest = max(dates) +print(f"Earliest: {earliest}") # Output: Earliest: 2025-05-21 14:30:00 +print(f"Latest: {latest}") # Output: Latest: 2025-05-21 15:45:00 +``` diff --git a/content/values.md b/content/values.md new file mode 100644 index 0000000..f34a36e --- /dev/null +++ b/content/values.md @@ -0,0 +1,20 @@ ++++ +title = "Values" ++++ + +## Values in Python + +In Python, a value is a piece of data that can be assigned to a variable or used in an expression. There are different types of values in Python, such as integers, floats, strings, and booleans. + +Here are some examples of values in Python: + +```python +# Integer value +x = 42 +# Float value +y = 3.14 +# String value +name = "John Carmack" +# Boolean value +is_active = True +``` diff --git a/content/variables.md b/content/variables.md new file mode 100644 index 0000000..dec7c59 --- /dev/null +++ b/content/variables.md @@ -0,0 +1,32 @@ ++++ +title = "Variables" ++++ + +## Variables in Python + +Variables are explicitly declared and dynamically typed in Python. There is no way to declare the variable, they are created when a value is assigned to them. + +```python +foo = 42 +bar = "Hello, World!" +``` + +Because python's variables are dynamically typed, their type can change at any time. + +```python +foo = 42 +foo = "Hello, World!" # foo is now a string +``` + +To check the type of a variable, we can use the `type()` function. + +```python +foo = 42 +print(type(foo)) # Output: +``` + +There are no ways to declare constants in Python, so the best practice to simulate a constant is to use a variable and use an uppercase naming as stated in [constant](https://peps.python.org/pep-0008/#constants) section of [PEP8](https://realpython.com/python-pep8/). + +```python +PI = 3.14159 +``` diff --git a/content/while.md b/content/while.md new file mode 100644 index 0000000..4963cf9 --- /dev/null +++ b/content/while.md @@ -0,0 +1,33 @@ ++++ +title = "While" ++++ + +## While in Python + +The `while` keyword is used to create a loop that continues to execute as long as a condition is true. + +```python +count = 0 +while count < 5: + print(count) + count += 1 +# Output: 0, 1, 2, 3, 4 +``` + +The `break` keyword can be used to exit the loop prematurely. + +The `continue` keyword can be used to skip the rest of the code block and continue with the next iteration of the loop. + +```python +count = 0 +while count < 5: + if count == 0: + continue + + if count == 3: + break + + print(count) + count += 1 +# Output: 0, 2 +``` diff --git a/data/pages.yaml b/data/pages.yaml new file mode 100644 index 0000000..466e96e --- /dev/null +++ b/data/pages.yaml @@ -0,0 +1,63 @@ +pages: + - title: "Hello World" + url: "/hello-world" + - title: "Values" + url: "/values" + - title: "Numbers" + url: "/numbers" + - title: "Strings" + url: "/strings" + - title: "Formatting" + url: "/formatting" + - title: "Boolean" + url: "/boolean" + - title: "Variables" + url: "/variables" + - title: "Operators" + url: "/operators" + - title: "Loop" + url: "/loop" + - title: "While" + url: "/while" + - title: "If Else" + url: "/if-else" + - title: "Switch" + url: "/switch" + - title: "List" + url: "/list" + - title: "Sets and Tuples" + url: "/sets-tuples" + - title: "Dictionaries" + url: "/dictionaries" + - title: "Functions" + url: "/functions" + - title: "Decorators" + url: "/decorators" + - title: "Enums" + url: "/enums" + - title: "Classes" + url: "/classes" + - title: "Modules and Packages" + url: "/modules-packages" + - title: "Errors" + url: "/errors" + - title: "Testing" + url: "/testing" + - title: "Time" + url: "/time" + - title: "Static Typing" + url: "/static-typing" + - title: "JSON" + url: "/json" + - title: "CSV" + url: "/csv" + - title: "Regular Expressions" + url: "/regex" + - title: "Args and Kwargs" + url: "/args-kwargs" + - title: "Random Numbers" + url: "/random-numbers" + - title: "Logging" + url: "/logging" + - title: "Multi-threading" + url: "/multi-threading" diff --git a/themes/hugo-bearblog/layouts/_default/baseof.html b/themes/hugo-bearblog/layouts/_default/baseof.html index 6e6a549..5fba090 100644 --- a/themes/hugo-bearblog/layouts/_default/baseof.html +++ b/themes/hugo-bearblog/layouts/_default/baseof.html @@ -18,6 +18,10 @@ {{- partial "style.html" . -}} + + + + diff --git a/themes/hugo-bearblog/layouts/_default/single.html b/themes/hugo-bearblog/layouts/_default/single.html index 7d57351..37ef2a5 100644 --- a/themes/hugo-bearblog/layouts/_default/single.html +++ b/themes/hugo-bearblog/layouts/_default/single.html @@ -12,9 +12,21 @@

{{ .Title }}

{{ .Content }} -

- {{ range (.GetTerms "tags") }} - #{{ .LinkTitle }} - {{ end }} -

+{{ $pages := .Site.Data.pages.pages }} +{{ $nextPage := "" }} + +{{ range $index, $element := $pages }} +{{ if eq $element.title $.Title }} +{{ $nextIndex := add $index 1 }} +{{ if lt $nextIndex (len $pages) }} +{{ $nextPage = index $pages $nextIndex }} +{{ end }} +{{ end }} +{{ end }} + +{{ if $nextPage }} +
+ Next example: {{ $nextPage.title }} +
{{ end }} +{{ end }} \ No newline at end of file diff --git a/themes/hugo-bearblog/layouts/index.html b/themes/hugo-bearblog/layouts/index.html index 9983b08..95bf1c7 100644 --- a/themes/hugo-bearblog/layouts/index.html +++ b/themes/hugo-bearblog/layouts/index.html @@ -1,3 +1,6 @@ {{ define "main" }} {{ .Content }} +{{ range .Site.Data.pages.pages }} +
  • {{ .title }}
  • {{ end }} +{{ end }} \ No newline at end of file diff --git a/themes/hugo-bearblog/layouts/partials/footer.html b/themes/hugo-bearblog/layouts/partials/footer.html index 8eca955..9201462 100644 --- a/themes/hugo-bearblog/layouts/partials/footer.html +++ b/themes/hugo-bearblog/layouts/partials/footer.html @@ -1 +1,2 @@ -{{ if ne .Site.Params.hideMadeWithLine true }}Made with Hugo ʕ•ᴥ•ʔ Bear{{ end }} +Source code | Inspired by GoByExample \ No newline at end of file diff --git a/themes/hugo-bearblog/layouts/partials/style.html b/themes/hugo-bearblog/layouts/partials/style.html index 770a81b..645a985 100644 --- a/themes/hugo-bearblog/layouts/partials/style.html +++ b/themes/hugo-bearblog/layouts/partials/style.html @@ -12,6 +12,15 @@ color: #444; } + footer { + font-size: small; + color: #a0a0a0; + + a { + color: #a0a0a0; + } + } + h1, h2, h3, diff --git a/themes/hugo-bearblog/static/highlight/.DS_Store b/themes/hugo-bearblog/static/highlight/.DS_Store new file mode 100644 index 0000000..28ca8bb Binary files /dev/null and b/themes/hugo-bearblog/static/highlight/.DS_Store differ diff --git a/themes/hugo-bearblog/static/highlight/LICENSE b/themes/hugo-bearblog/static/highlight/LICENSE new file mode 100644 index 0000000..2250cc7 --- /dev/null +++ b/themes/hugo-bearblog/static/highlight/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2006, Ivan Sagalaev. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/themes/hugo-bearblog/static/highlight/highlight.min.js b/themes/hugo-bearblog/static/highlight/highlight.min.js new file mode 100644 index 0000000..1eeb707 --- /dev/null +++ b/themes/hugo-bearblog/static/highlight/highlight.min.js @@ -0,0 +1,349 @@ +/*! + Highlight.js v11.9.0 (git: b7ec4bfafc) + (c) 2006-2024 undefined and other contributors + License: BSD-3-Clause + */ +var hljs=function(){"use strict";function e(t){ +return t instanceof Map?t.clear=t.delete=t.set=()=>{ +throw Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=()=>{ +throw Error("set is read-only") +}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach((n=>{ +const i=t[n],s=typeof i;"object"!==s&&"function"!==s||Object.isFrozen(i)||e(i) +})),t}class t{constructor(e){ +void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1} +ignoreMatch(){this.isMatchIgnored=!0}}function n(e){ +return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'") +}function i(e,...t){const n=Object.create(null);for(const t in e)n[t]=e[t] +;return t.forEach((e=>{for(const t in e)n[t]=e[t]})),n}const s=e=>!!e.scope +;class o{constructor(e,t){ +this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){ +this.buffer+=n(e)}openNode(e){if(!s(e))return;const t=((e,{prefix:t})=>{ +if(e.startsWith("language:"))return e.replace("language:","language-") +;if(e.includes(".")){const n=e.split(".") +;return[`${t}${n.shift()}`,...n.map(((e,t)=>`${e}${"_".repeat(t+1)}`))].join(" ") +}return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)} +closeNode(e){s(e)&&(this.buffer+="")}value(){return this.buffer}span(e){ +this.buffer+=``}}const r=(e={})=>{const t={children:[]} +;return Object.assign(t,e),t};class a{constructor(){ +this.rootNode=r(),this.stack=[this.rootNode]}get top(){ +return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){ +this.top.children.push(e)}openNode(e){const t=r({scope:e}) +;this.add(t),this.stack.push(t)}closeNode(){ +if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){ +for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)} +walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){ +return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t), +t.children.forEach((t=>this._walk(e,t))),e.closeNode(t)),e}static _collapse(e){ +"string"!=typeof e&&e.children&&(e.children.every((e=>"string"==typeof e))?e.children=[e.children.join("")]:e.children.forEach((e=>{ +a._collapse(e)})))}}class c extends a{constructor(e){super(),this.options=e} +addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){ +this.closeNode()}__addSublanguage(e,t){const n=e.root +;t&&(n.scope="language:"+t),this.add(n)}toHTML(){ +return new o(this,this.options).value()}finalize(){ +return this.closeAllNodes(),!0}}function l(e){ +return e?"string"==typeof e?e:e.source:null}function g(e){return h("(?=",e,")")} +function u(e){return h("(?:",e,")*")}function d(e){return h("(?:",e,")?")} +function h(...e){return e.map((e=>l(e))).join("")}function f(...e){const t=(e=>{ +const t=e[e.length-1] +;return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{} +})(e);return"("+(t.capture?"":"?:")+e.map((e=>l(e))).join("|")+")"} +function p(e){return RegExp(e.toString()+"|").exec("").length-1} +const b=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./ +;function m(e,{joinWith:t}){let n=0;return e.map((e=>{n+=1;const t=n +;let i=l(e),s="";for(;i.length>0;){const e=b.exec(i);if(!e){s+=i;break} +s+=i.substring(0,e.index), +i=i.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?s+="\\"+(Number(e[1])+t):(s+=e[0], +"("===e[0]&&n++)}return s})).map((e=>`(${e})`)).join(t)} +const E="[a-zA-Z]\\w*",x="[a-zA-Z_]\\w*",w="\\b\\d+(\\.\\d+)?",y="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",_="\\b(0b[01]+)",O={ +begin:"\\\\[\\s\\S]",relevance:0},v={scope:"string",begin:"'",end:"'", +illegal:"\\n",contains:[O]},k={scope:"string",begin:'"',end:'"',illegal:"\\n", +contains:[O]},N=(e,t,n={})=>{const s=i({scope:"comment",begin:e,end:t, +contains:[]},n);s.contains.push({scope:"doctag", +begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)", +end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0}) +;const o=f("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/) +;return s.contains.push({begin:h(/[ ]+/,"(",o,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),s +},S=N("//","$"),M=N("/\\*","\\*/"),R=N("#","$");var j=Object.freeze({ +__proto__:null,APOS_STRING_MODE:v,BACKSLASH_ESCAPE:O,BINARY_NUMBER_MODE:{ +scope:"number",begin:_,relevance:0},BINARY_NUMBER_RE:_,COMMENT:N, +C_BLOCK_COMMENT_MODE:M,C_LINE_COMMENT_MODE:S,C_NUMBER_MODE:{scope:"number", +begin:y,relevance:0},C_NUMBER_RE:y,END_SAME_AS_BEGIN:e=>Object.assign(e,{ +"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{ +t.data._beginMatch!==e[1]&&t.ignoreMatch()}}),HASH_COMMENT_MODE:R,IDENT_RE:E, +MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:{begin:"\\.\\s*"+x,relevance:0}, +NUMBER_MODE:{scope:"number",begin:w,relevance:0},NUMBER_RE:w, +PHRASAL_WORDS_MODE:{ +begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ +},QUOTE_STRING_MODE:k,REGEXP_MODE:{scope:"regexp",begin:/\/(?=[^/\n]*\/)/, +end:/\/[gimuy]*/,contains:[O,{begin:/\[/,end:/\]/,relevance:0,contains:[O]}]}, +RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~", +SHEBANG:(e={})=>{const t=/^#![ ]*\// +;return e.binary&&(e.begin=h(t,/.*\b/,e.binary,/\b.*/)),i({scope:"meta",begin:t, +end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)}, +TITLE_MODE:{scope:"title",begin:E,relevance:0},UNDERSCORE_IDENT_RE:x, +UNDERSCORE_TITLE_MODE:{scope:"title",begin:x,relevance:0}});function A(e,t){ +"."===e.input[e.index-1]&&t.ignoreMatch()}function I(e,t){ +void 0!==e.className&&(e.scope=e.className,delete e.className)}function T(e,t){ +t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)", +e.__beforeBegin=A,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords, +void 0===e.relevance&&(e.relevance=0))}function L(e,t){ +Array.isArray(e.illegal)&&(e.illegal=f(...e.illegal))}function B(e,t){ +if(e.match){ +if(e.begin||e.end)throw Error("begin & end are not supported with match") +;e.begin=e.match,delete e.match}}function P(e,t){ +void 0===e.relevance&&(e.relevance=1)}const D=(e,t)=>{if(!e.beforeMatch)return +;if(e.starts)throw Error("beforeMatch cannot be used with starts") +;const n=Object.assign({},e);Object.keys(e).forEach((t=>{delete e[t] +})),e.keywords=n.keywords,e.begin=h(n.beforeMatch,g(n.begin)),e.starts={ +relevance:0,contains:[Object.assign(n,{endsParent:!0})] +},e.relevance=0,delete n.beforeMatch +},H=["of","and","for","in","not","or","if","then","parent","list","value"],C="keyword" +;function $(e,t,n=C){const i=Object.create(null) +;return"string"==typeof e?s(n,e.split(" ")):Array.isArray(e)?s(n,e):Object.keys(e).forEach((n=>{ +Object.assign(i,$(e[n],t,n))})),i;function s(e,n){ +t&&(n=n.map((e=>e.toLowerCase()))),n.forEach((t=>{const n=t.split("|") +;i[n[0]]=[e,U(n[0],n[1])]}))}}function U(e,t){ +return t?Number(t):(e=>H.includes(e.toLowerCase()))(e)?0:1}const z={},W=e=>{ +console.error(e)},X=(e,...t)=>{console.log("WARN: "+e,...t)},G=(e,t)=>{ +z[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),z[`${e}/${t}`]=!0) +},K=Error();function F(e,t,{key:n}){let i=0;const s=e[n],o={},r={} +;for(let e=1;e<=t.length;e++)r[e+i]=s[e],o[e+i]=!0,i+=p(t[e-1]) +;e[n]=r,e[n]._emit=o,e[n]._multi=!0}function Z(e){(e=>{ +e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope, +delete e.scope)})(e),"string"==typeof e.beginScope&&(e.beginScope={ +_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope +}),(e=>{if(Array.isArray(e.begin)){ +if(e.skip||e.excludeBegin||e.returnBegin)throw W("skip, excludeBegin, returnBegin not compatible with beginScope: {}"), +K +;if("object"!=typeof e.beginScope||null===e.beginScope)throw W("beginScope must be object"), +K;F(e,e.begin,{key:"beginScope"}),e.begin=m(e.begin,{joinWith:""})}})(e),(e=>{ +if(Array.isArray(e.end)){ +if(e.skip||e.excludeEnd||e.returnEnd)throw W("skip, excludeEnd, returnEnd not compatible with endScope: {}"), +K +;if("object"!=typeof e.endScope||null===e.endScope)throw W("endScope must be object"), +K;F(e,e.end,{key:"endScope"}),e.end=m(e.end,{joinWith:""})}})(e)}function V(e){ +function t(t,n){ +return RegExp(l(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":"")) +}class n{constructor(){ +this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0} +addRule(e,t){ +t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]), +this.matchAt+=p(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null) +;const e=this.regexes.map((e=>e[1]));this.matcherRe=t(m(e,{joinWith:"|" +}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex +;const t=this.matcherRe.exec(e);if(!t)return null +;const n=t.findIndex(((e,t)=>t>0&&void 0!==e)),i=this.matchIndexes[n] +;return t.splice(0,n),Object.assign(t,i)}}class s{constructor(){ +this.rules=[],this.multiRegexes=[], +this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){ +if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n +;return this.rules.slice(e).forEach((([e,n])=>t.addRule(e,n))), +t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){ +return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){ +this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){ +const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex +;let n=t.exec(e) +;if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else{ +const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)} +return n&&(this.regexIndex+=n.position+1, +this.regexIndex===this.count&&this.considerAll()),n}} +if(e.compilerExtensions||(e.compilerExtensions=[]), +e.contains&&e.contains.includes("self"))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.") +;return e.classNameAliases=i(e.classNameAliases||{}),function n(o,r){const a=o +;if(o.isCompiled)return a +;[I,B,Z,D].forEach((e=>e(o,r))),e.compilerExtensions.forEach((e=>e(o,r))), +o.__beforeBegin=null,[T,L,P].forEach((e=>e(o,r))),o.isCompiled=!0;let c=null +;return"object"==typeof o.keywords&&o.keywords.$pattern&&(o.keywords=Object.assign({},o.keywords), +c=o.keywords.$pattern, +delete o.keywords.$pattern),c=c||/\w+/,o.keywords&&(o.keywords=$(o.keywords,e.case_insensitive)), +a.keywordPatternRe=t(c,!0), +r&&(o.begin||(o.begin=/\B|\b/),a.beginRe=t(a.begin),o.end||o.endsWithParent||(o.end=/\B|\b/), +o.end&&(a.endRe=t(a.end)), +a.terminatorEnd=l(a.end)||"",o.endsWithParent&&r.terminatorEnd&&(a.terminatorEnd+=(o.end?"|":"")+r.terminatorEnd)), +o.illegal&&(a.illegalRe=t(o.illegal)), +o.contains||(o.contains=[]),o.contains=[].concat(...o.contains.map((e=>(e=>(e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map((t=>i(e,{ +variants:null},t)))),e.cachedVariants?e.cachedVariants:q(e)?i(e,{ +starts:e.starts?i(e.starts):null +}):Object.isFrozen(e)?i(e):e))("self"===e?o:e)))),o.contains.forEach((e=>{n(e,a) +})),o.starts&&n(o.starts,r),a.matcher=(e=>{const t=new s +;return e.contains.forEach((e=>t.addRule(e.begin,{rule:e,type:"begin" +}))),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end" +}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t})(a),a}(e)}function q(e){ +return!!e&&(e.endsWithParent||q(e.starts))}class J extends Error{ +constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}} +const Y=n,Q=i,ee=Symbol("nomatch"),te=n=>{ +const i=Object.create(null),s=Object.create(null),o=[];let r=!0 +;const a="Could not find the language '{}', did you forget to load/include a language module?",l={ +disableAutodetect:!0,name:"Plain text",contains:[]};let p={ +ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i, +languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-", +cssSelector:"pre code",languages:null,__emitter:c};function b(e){ +return p.noHighlightRe.test(e)}function m(e,t,n){let i="",s="" +;"object"==typeof t?(i=e, +n=t.ignoreIllegals,s=t.language):(G("10.7.0","highlight(lang, code, ...args) has been deprecated."), +G("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"), +s=e,i=t),void 0===n&&(n=!0);const o={code:i,language:s};N("before:highlight",o) +;const r=o.result?o.result:E(o.language,o.code,n) +;return r.code=o.code,N("after:highlight",r),r}function E(e,n,s,o){ +const c=Object.create(null);function l(){if(!N.keywords)return void M.addText(R) +;let e=0;N.keywordPatternRe.lastIndex=0;let t=N.keywordPatternRe.exec(R),n="" +;for(;t;){n+=R.substring(e,t.index) +;const s=_.case_insensitive?t[0].toLowerCase():t[0],o=(i=s,N.keywords[i]);if(o){ +const[e,i]=o +;if(M.addText(n),n="",c[s]=(c[s]||0)+1,c[s]<=7&&(j+=i),e.startsWith("_"))n+=t[0];else{ +const n=_.classNameAliases[e]||e;u(t[0],n)}}else n+=t[0] +;e=N.keywordPatternRe.lastIndex,t=N.keywordPatternRe.exec(R)}var i +;n+=R.substring(e),M.addText(n)}function g(){null!=N.subLanguage?(()=>{ +if(""===R)return;let e=null;if("string"==typeof N.subLanguage){ +if(!i[N.subLanguage])return void M.addText(R) +;e=E(N.subLanguage,R,!0,S[N.subLanguage]),S[N.subLanguage]=e._top +}else e=x(R,N.subLanguage.length?N.subLanguage:null) +;N.relevance>0&&(j+=e.relevance),M.__addSublanguage(e._emitter,e.language) +})():l(),R=""}function u(e,t){ +""!==e&&(M.startScope(t),M.addText(e),M.endScope())}function d(e,t){let n=1 +;const i=t.length-1;for(;n<=i;){if(!e._emit[n]){n++;continue} +const i=_.classNameAliases[e[n]]||e[n],s=t[n];i?u(s,i):(R=s,l(),R=""),n++}} +function h(e,t){ +return e.scope&&"string"==typeof e.scope&&M.openNode(_.classNameAliases[e.scope]||e.scope), +e.beginScope&&(e.beginScope._wrap?(u(R,_.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap), +R=""):e.beginScope._multi&&(d(e.beginScope,t),R="")),N=Object.create(e,{parent:{ +value:N}}),N}function f(e,n,i){let s=((e,t)=>{const n=e&&e.exec(t) +;return n&&0===n.index})(e.endRe,i);if(s){if(e["on:end"]){const i=new t(e) +;e["on:end"](n,i),i.isMatchIgnored&&(s=!1)}if(s){ +for(;e.endsParent&&e.parent;)e=e.parent;return e}} +if(e.endsWithParent)return f(e.parent,n,i)}function b(e){ +return 0===N.matcher.regexIndex?(R+=e[0],1):(T=!0,0)}function m(e){ +const t=e[0],i=n.substring(e.index),s=f(N,e,i);if(!s)return ee;const o=N +;N.endScope&&N.endScope._wrap?(g(), +u(t,N.endScope._wrap)):N.endScope&&N.endScope._multi?(g(), +d(N.endScope,e)):o.skip?R+=t:(o.returnEnd||o.excludeEnd||(R+=t), +g(),o.excludeEnd&&(R=t));do{ +N.scope&&M.closeNode(),N.skip||N.subLanguage||(j+=N.relevance),N=N.parent +}while(N!==s.parent);return s.starts&&h(s.starts,e),o.returnEnd?0:t.length} +let w={};function y(i,o){const a=o&&o[0];if(R+=i,null==a)return g(),0 +;if("begin"===w.type&&"end"===o.type&&w.index===o.index&&""===a){ +if(R+=n.slice(o.index,o.index+1),!r){const t=Error(`0 width match regex (${e})`) +;throw t.languageName=e,t.badRule=w.rule,t}return 1} +if(w=o,"begin"===o.type)return(e=>{ +const n=e[0],i=e.rule,s=new t(i),o=[i.__beforeBegin,i["on:begin"]] +;for(const t of o)if(t&&(t(e,s),s.isMatchIgnored))return b(n) +;return i.skip?R+=n:(i.excludeBegin&&(R+=n), +g(),i.returnBegin||i.excludeBegin||(R=n)),h(i,e),i.returnBegin?0:n.length})(o) +;if("illegal"===o.type&&!s){ +const e=Error('Illegal lexeme "'+a+'" for mode "'+(N.scope||"")+'"') +;throw e.mode=N,e}if("end"===o.type){const e=m(o);if(e!==ee)return e} +if("illegal"===o.type&&""===a)return 1 +;if(I>1e5&&I>3*o.index)throw Error("potential infinite loop, way more iterations than matches") +;return R+=a,a.length}const _=O(e) +;if(!_)throw W(a.replace("{}",e)),Error('Unknown language: "'+e+'"') +;const v=V(_);let k="",N=o||v;const S={},M=new p.__emitter(p);(()=>{const e=[] +;for(let t=N;t!==_;t=t.parent)t.scope&&e.unshift(t.scope) +;e.forEach((e=>M.openNode(e)))})();let R="",j=0,A=0,I=0,T=!1;try{ +if(_.__emitTokens)_.__emitTokens(n,M);else{for(N.matcher.considerAll();;){ +I++,T?T=!1:N.matcher.considerAll(),N.matcher.lastIndex=A +;const e=N.matcher.exec(n);if(!e)break;const t=y(n.substring(A,e.index),e) +;A=e.index+t}y(n.substring(A))}return M.finalize(),k=M.toHTML(),{language:e, +value:k,relevance:j,illegal:!1,_emitter:M,_top:N}}catch(t){ +if(t.message&&t.message.includes("Illegal"))return{language:e,value:Y(n), +illegal:!0,relevance:0,_illegalBy:{message:t.message,index:A, +context:n.slice(A-100,A+100),mode:t.mode,resultSoFar:k},_emitter:M};if(r)return{ +language:e,value:Y(n),illegal:!1,relevance:0,errorRaised:t,_emitter:M,_top:N} +;throw t}}function x(e,t){t=t||p.languages||Object.keys(i);const n=(e=>{ +const t={value:Y(e),illegal:!1,relevance:0,_top:l,_emitter:new p.__emitter(p)} +;return t._emitter.addText(e),t})(e),s=t.filter(O).filter(k).map((t=>E(t,e,!1))) +;s.unshift(n);const o=s.sort(((e,t)=>{ +if(e.relevance!==t.relevance)return t.relevance-e.relevance +;if(e.language&&t.language){if(O(e.language).supersetOf===t.language)return 1 +;if(O(t.language).supersetOf===e.language)return-1}return 0})),[r,a]=o,c=r +;return c.secondBest=a,c}function w(e){let t=null;const n=(e=>{ +let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"" +;const n=p.languageDetectRe.exec(t);if(n){const t=O(n[1]) +;return t||(X(a.replace("{}",n[1])), +X("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"} +return t.split(/\s+/).find((e=>b(e)||O(e)))})(e);if(b(n))return +;if(N("before:highlightElement",{el:e,language:n +}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e) +;if(e.children.length>0&&(p.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."), +console.warn("https://github.com/highlightjs/highlight.js/wiki/security"), +console.warn("The element with unescaped HTML:"), +console.warn(e)),p.throwUnescapedHTML))throw new J("One of your code blocks includes unescaped HTML.",e.innerHTML) +;t=e;const i=t.textContent,o=n?m(i,{language:n,ignoreIllegals:!0}):x(i) +;e.innerHTML=o.value,e.dataset.highlighted="yes",((e,t,n)=>{const i=t&&s[t]||n +;e.classList.add("hljs"),e.classList.add("language-"+i) +})(e,n,o.language),e.result={language:o.language,re:o.relevance, +relevance:o.relevance},o.secondBest&&(e.secondBest={ +language:o.secondBest.language,relevance:o.secondBest.relevance +}),N("after:highlightElement",{el:e,result:o,text:i})}let y=!1;function _(){ +"loading"!==document.readyState?document.querySelectorAll(p.cssSelector).forEach(w):y=!0 +}function O(e){return e=(e||"").toLowerCase(),i[e]||i[s[e]]} +function v(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach((e=>{ +s[e.toLowerCase()]=t}))}function k(e){const t=O(e) +;return t&&!t.disableAutodetect}function N(e,t){const n=e;o.forEach((e=>{ +e[n]&&e[n](t)}))} +"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(()=>{ +y&&_()}),!1),Object.assign(n,{highlight:m,highlightAuto:x,highlightAll:_, +highlightElement:w, +highlightBlock:e=>(G("10.7.0","highlightBlock will be removed entirely in v12.0"), +G("10.7.0","Please use highlightElement now."),w(e)),configure:e=>{p=Q(p,e)}, +initHighlighting:()=>{ +_(),G("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")}, +initHighlightingOnLoad:()=>{ +_(),G("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.") +},registerLanguage:(e,t)=>{let s=null;try{s=t(n)}catch(t){ +if(W("Language definition for '{}' could not be registered.".replace("{}",e)), +!r)throw t;W(t),s=l} +s.name||(s.name=e),i[e]=s,s.rawDefinition=t.bind(null,n),s.aliases&&v(s.aliases,{ +languageName:e})},unregisterLanguage:e=>{delete i[e] +;for(const t of Object.keys(s))s[t]===e&&delete s[t]}, +listLanguages:()=>Object.keys(i),getLanguage:O,registerAliases:v, +autoDetection:k,inherit:Q,addPlugin:e=>{(e=>{ +e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{ +e["before:highlightBlock"](Object.assign({block:t.el},t)) +}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{ +e["after:highlightBlock"](Object.assign({block:t.el},t))})})(e),o.push(e)}, +removePlugin:e=>{const t=o.indexOf(e);-1!==t&&o.splice(t,1)}}),n.debugMode=()=>{ +r=!1},n.safeMode=()=>{r=!0},n.versionString="11.9.0",n.regex={concat:h, +lookahead:g,either:f,optional:d,anyNumberOfTimes:u} +;for(const t in j)"object"==typeof j[t]&&e(j[t]);return Object.assign(n,j),n +},ne=te({});return ne.newInstance=()=>te({}),ne}() +;"object"==typeof exports&&"undefined"!=typeof module&&(module.exports=hljs);/*! `python` grammar compiled for Highlight.js 11.9.0 */ +(()=>{var e=(()=>{"use strict";return e=>{ +const n=e.regex,a=/[\p{XID_Start}_]\p{XID_Continue}*/u,s=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],i={ +$pattern:/[A-Za-z]\w+|__\w+__/,keyword:s, +built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"], +literal:["__debug__","Ellipsis","False","None","NotImplemented","True"], +type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"] +},t={className:"meta",begin:/^(>>>|\.\.\.) /},r={className:"subst",begin:/\{/, +end:/\}/,keywords:i,illegal:/#/},l={begin:/\{\{/,relevance:0},b={ +className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{ +begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/, +contains:[e.BACKSLASH_ESCAPE,t],relevance:10},{ +begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/, +contains:[e.BACKSLASH_ESCAPE,t],relevance:10},{ +begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/, +contains:[e.BACKSLASH_ESCAPE,t,l,r]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/, +end:/"""/,contains:[e.BACKSLASH_ESCAPE,t,l,r]},{begin:/([uU]|[rR])'/,end:/'/, +relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{ +begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/, +end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/, +contains:[e.BACKSLASH_ESCAPE,l,r]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/, +contains:[e.BACKSLASH_ESCAPE,l,r]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE] +},o="[0-9](_?[0-9])*",c=`(\\b(${o}))?\\.(${o})|\\b(${o})\\.`,d="\\b|"+s.join("|"),g={ +className:"number",relevance:0,variants:[{ +begin:`(\\b(${o})|(${c}))[eE][+-]?(${o})[jJ]?(?=${d})`},{begin:`(${c})[jJ]?`},{ +begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{ +begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})` +},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${o})[jJ](?=${d})` +}]},p={className:"comment",begin:n.lookahead(/# type:/),end:/$/,keywords:i, +contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={ +className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/, +end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i, +contains:["self",t,g,b,e.HASH_COMMENT_MODE]}]};return r.contains=[b,g,t],{ +name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:i, +illegal:/(<\/|\?)|=>/,contains:[t,g,{begin:/\bself\b/},{beginKeywords:"if", +relevance:0},{match:/\bor\b/,scope:"keyword"},b,p,e.HASH_COMMENT_MODE,{ +match:[/\bdef/,/\s+/,a],scope:{1:"keyword",3:"title.function"},contains:[m]},{ +variants:[{match:[/\bclass/,/\s+/,a,/\s*/,/\(\s*/,a,/\s*\)/]},{ +match:[/\bclass/,/\s+/,a]}],scope:{1:"keyword",3:"title.class", +6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/, +contains:[g,m,b]}]}}})();hljs.registerLanguage("python",e)})(); \ No newline at end of file diff --git a/themes/hugo-bearblog/static/highlight/styles/monokai.min.css b/themes/hugo-bearblog/static/highlight/styles/monokai.min.css new file mode 100644 index 0000000..448d85d --- /dev/null +++ b/themes/hugo-bearblog/static/highlight/styles/monokai.min.css @@ -0,0 +1 @@ +pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}.hljs{background:#272822;color:#ddd}.hljs-keyword,.hljs-literal,.hljs-name,.hljs-selector-tag,.hljs-strong,.hljs-tag{color:#f92672}.hljs-code{color:#66d9ef}.hljs-attribute,.hljs-link,.hljs-regexp,.hljs-symbol{color:#bf79db}.hljs-addition,.hljs-built_in,.hljs-bullet,.hljs-emphasis,.hljs-section,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-string,.hljs-subst,.hljs-template-tag,.hljs-template-variable,.hljs-title,.hljs-type,.hljs-variable{color:#a6e22e}.hljs-class .hljs-title,.hljs-title.class_{color:#fff}.hljs-comment,.hljs-deletion,.hljs-meta,.hljs-quote{color:#75715e}.hljs-doctag,.hljs-keyword,.hljs-literal,.hljs-section,.hljs-selector-id,.hljs-selector-tag,.hljs-title,.hljs-type{font-weight:700} \ No newline at end of file