feat: added examples_tutorials

This commit is contained in:
xpk
2025-11-26 23:20:41 +08:00
parent 96ef5cb42e
commit 9d044c20c9
16 changed files with 201 additions and 70 deletions
-13
View File
@@ -1,13 +0,0 @@
#!/usr/bin/env python3
# Python data types
# list = [value1, value2, value3,...valueN]
# set = {value1, value2, value3,...valueN}
# dict = { key1:value1, key2:value2,...keyN:valueN }
# Sample use of list of dict
datagroup = [{'name': '203.60.15.113/32', 'data': ''}, {'name': '222.186.30.174/32', 'data': ''},{'name': '120.136.32.106/32', 'data': ''}]
newrecord = {'name': '1.2.3.4/32', 'data': ''}
datagroup.append(newrecord)
print(datagroup)
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
# Imports
import threading
import multiprocessing
import concurrent.futures
import time
def task(name):
"""
Dummy function which pretends to do some work
"""
print(f"Thread {name}: Starting...")
time.sleep(1)
print(f"Thread {name}: Finishing.")
def threading_example():
"""
threading: not truly concurrent as GIL (Global Interpreter Lock) limits 1 process for each bytecode execution.
it does allow the process to do more work while other threads are not busy.
threading is relatively light-weight
"""
threads = []
for i in range(3):
threads.append(threading.Thread(target=task, args=(i,)))
for i in threads:
i.start()
for i in threads:
i.join()
print("threading_example: All threads completed.")
def multiprocessing_example():
"""
multiprocessing: True parallel execution on multiple CPU cores. Tasks are ran on independent processes.
More resource expensive compared to threading
"""
mp = []
for i in range(3):
mp.append(multiprocessing.Process(target=task, args=(i,)))
for i in mp:
i.start()
for i in mp:
i.join()
print("multiprocessing_example: Done with all calculations!")
def concurrent_futures_example():
"""
high-level implementation of threading. facilitate result consolidation
for high-level implemetnation of multiprocessing, use ProcessPoolExecutor
"""
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
for i in range(3):
executor.submit(task, i)
print("concurrent_futures_example: All threads completed.")
# Main function
def main() -> None:
threading_example()
multiprocessing_example()
concurrent_futures_example()
# Call main function
if __name__ == '__main__':
main()
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
"""
Python data types
list = [value1, value2, value3,...valueN]
set = {value1, value2, value3,...valueN}
dict = { key1:value1, key2:value2,...keyN:valueN }
"""
list_of_dict = [{'name': '203.60.15.113/32', 'data': ''}, {'name': '222.186.30.174/32', 'data': ''},{'name': '120.136.32.106/32', 'data': ''}]
new_record = {'name': '1.2.3.4/32', 'data': ''}
list_of_dict.append(new_record)
print(list_of_dict)
+4
View File
@@ -0,0 +1,4 @@
name,age
tom, 22
sam, 32
mary, 19
1 name age
2 tom 22
3 sam 32
4 mary 19
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
import duckdb
# Create an in-memory DuckDB connection
con = duckdb.connect(':memory:')
# first query which selects a number
r1 = con.sql("SELECT 42 AS i")
con.sql("SELECT i * 2 AS k FROM r1").show()
# create a table. insert a row and query the table
con.sql("CREATE TABLE test (i INTEGER)")
con.sql("INSERT INTO test VALUES (42)")
con.table("test").show()
# read a csv into duckdb
csvt = con.read_csv("duck.csv")
con.sql("SELECT * FROM csvt WHERE name = 'tom'").show()
# explicitly close the connection
con.close()
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
# Main function
def main() -> None:
"""
Number formatting in f-string using format specifiers
The following prints will output
314%
3.14
12,345
00012345
12345
len(str(var1)) = 8
"""
var1: float = 3.141516
var2: float = 12345
print(f"{var1: .0%}")
print(f"{var1: .2f}")
print(f"{var2: ,}")
print(f"{var2: 09}")
print(f"{var2: >10}")
print(f"{len(str(var1)) = }")
# Call main function
if __name__ == '__main__':
main()
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
def square(x: int) -> int:
return x ** 2
# Main function
def main() -> None:
"""
lambda: a one-liner anonymous function. in its simplest form, it just a function.
for example, the following can be rewritten with a add_1 function which returns x + 1
"""
add_1 = lambda x: x + 1
result = add_1(1)
print(result)
"""
map function: apply a function to every element in an iterable
returns a map object which can then be casted to a list
"""
numbers = range(1,10)
# square is the function and numbers is the iterable where elements will be sent from
results = list(map(square, numbers))
print(results)
"""
implement the same map function with lambda
"""
results2 = list(map(lambda x: x ** 2, numbers))
print(results2)
"""
filter function: apply function to every element. if true, keep the element. if false, reject it
"""
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
# Call main function
if __name__ == '__main__':
main()
@@ -1,19 +1,21 @@
#!/usr/bin/python3 #!/usr/bin/env python3
r"""
Python loops demo
License: This program is released under the MIT License
"""
import logging import logging
logging.basicConfig(level=logging.INFO, format="%(funcName)s %(levelname)s: %(message)s") logging.basicConfig(level=logging.INFO, format="%(funcName)s %(levelname)s: %(message)s")
def while_loop() -> None: def while_loop() -> None:
"""
while loop which requires a counter
"""
counter: int = 1 counter: int = 1
while counter <= 5: while counter <= 5:
logging.info(counter) logging.info(counter)
counter += 1 counter += 1
def for_loop() -> None: def for_loop() -> None:
"""
for loop which puts the counter inline
"""
for i in range(5): for i in range(5):
logging.info(i) logging.info(i)
@@ -21,7 +23,6 @@ def for_loop() -> None:
def main() -> None: def main() -> None:
""" """
Both functions will log a message 5 times, but the for loop is so much simpler Both functions will log a message 5 times, but the for loop is so much simpler
""" """
while_loop() while_loop()
for_loop() for_loop()
Binary file not shown.
@@ -1,9 +1,6 @@
#!/usr/bin/python3 #!/usr/bin/env python3
""" """
Documentation
Demonstrate how to use asyncio Demonstrate how to use asyncio
License: This program is released under the MIT License
""" """
# Imports # Imports
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python3
"""
Use terminaltables to draw a nice table
"""
from terminaltables import SingleTable
def main():
table_data = [
["Heading1", "Heading2"],
["row1 column1", "row1 column2"],
["row2 column1", "row2 column2"],
["row3 column1", "row3 column2"],
]
t1 = SingleTable(table_data)
print(t1.table)
if __name__ == '__main__':
main()
-11
View File
@@ -1,11 +0,0 @@
#!/usr/bin/python3
import logging
logging.basicConfig(format='%(levelname)s: %(message)s',level=logging.DEBUG)
logging.debug('Debug message')
logging.info('Info message')
logging.warning('Warning message')
logging.error('Error message')
logging.critical('Critical message')
-7
View File
@@ -1,7 +0,0 @@
#!/usr/bin/python3
msg = ""
msg += "Line 1"
msg += "Line 2"
print(msg)
-11
View File
@@ -1,11 +0,0 @@
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])
print(x);
-10
View File
@@ -1,10 +0,0 @@
from terminaltables import SingleTable
table_data = [
["Heading1", "Heading2"],
["row1 column1", "row1 column2"],
["row2 column1", "row2 column2"],
["row3 column1", "row3 column2"],
]
t1 = SingleTable(table_data)
print(t1.table)
-8
View File
@@ -1,8 +0,0 @@
#!/usr/bin/env python
import os, time
fileage = os.path.getmtime('/var/log/ufw.log');
if time.time() - fileage > 7200:
print ('File is > 2 hours old')