feat: added examples_tutorials
This commit is contained in:
@@ -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()
|
||||
Executable
+13
@@ -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)
|
||||
@@ -0,0 +1,4 @@
|
||||
name,age
|
||||
tom, 22
|
||||
sam, 32
|
||||
mary, 19
|
||||
|
Executable
+22
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import logging
|
||||
logging.basicConfig(level=logging.INFO, format="%(funcName)s %(levelname)s: %(message)s")
|
||||
|
||||
def while_loop() -> None:
|
||||
"""
|
||||
while loop which requires a counter
|
||||
"""
|
||||
counter: int = 1
|
||||
while counter <= 5:
|
||||
logging.info(counter)
|
||||
counter += 1
|
||||
|
||||
def for_loop() -> None:
|
||||
"""
|
||||
for loop which puts the counter inline
|
||||
"""
|
||||
for i in range(5):
|
||||
logging.info(i)
|
||||
|
||||
# Main function
|
||||
def main() -> None:
|
||||
"""
|
||||
Both functions will log a message 5 times, but the for loop is so much simpler
|
||||
"""
|
||||
while_loop()
|
||||
for_loop()
|
||||
|
||||
|
||||
# Call main function
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Binary file not shown.
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Demonstrate how to use asyncio
|
||||
"""
|
||||
|
||||
# Imports
|
||||
import asyncio
|
||||
|
||||
async def doit():
|
||||
print('Start doing...')
|
||||
await asyncio.sleep(2)
|
||||
print('Done!')
|
||||
|
||||
# Main function
|
||||
async def main() -> None:
|
||||
print('Main starts...')
|
||||
job_queue = []
|
||||
for i in range(3):
|
||||
job_queue.append(doit())
|
||||
await asyncio.gather(*job_queue)
|
||||
print('Main ends...')
|
||||
|
||||
|
||||
# Call main function
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user