├── multiply.py ├── mysql ├── datalocks.sql ├── 3-data-modelling.txt ├── 13-clustered-index.sql ├── 12-deadlocks.sql ├── 4-create-table.sql ├── 11-row-locks.sql ├── 9-isolation-levels.sql ├── 10-table-locks.sql ├── 6-update-delete.sql ├── 2-mysql-installation.txt └── 5-insert-data.sql ├── ingress ├── ingressclass.yaml ├── ingress.yaml ├── frontend2service.yaml ├── frontend1service.yaml ├── ingress-modified.yaml ├── ingress-foo-modified.yaml ├── frontend2-dep.yaml ├── frontend1-dep.yaml ├── application.yaml └── aws-deploy.yaml ├── conditional_statements.py ├── 13_pdb.py ├── Dockerfile_example ├── 10_oops_part2.py ├── oracle_db_example.py ├── k8s_kube_proxy_cmds.txt ├── 1_variables.py ├── go ├── interfaces │ └── main.go ├── sync-waitgroup │ └── main.go ├── contexts │ └── main.go └── channel │ └── main.go ├── find_duplicate_words.py ├── test_multiply.py ├── backend.yaml ├── kubernetes ├── cordon-drain.txt └── serviceaccount.txt ├── 6_tuples.py ├── mysql-program.py ├── 7_list_comprehension.py ├── balanced_brackets.py ├── unittest_examply.py ├── 15_pickle.py ├── 9_oops_part1.py ├── 17_generators.py ├── postgres └── jdbc_ssl_connector.java ├── 12_asyncio.py ├── logging_example.py ├── 14_mocks.py ├── 5_dictionaries.py ├── 4_sets.py ├── insertion_sort.py ├── 11_oops_part3.py ├── bubblesort.py ├── terraform_aws_ec2_webapp.tf ├── 8_functions.py ├── 16_subprocess.sql ├── 3_lists.py └── functions_and_decorators.py /multiply.py: -------------------------------------------------------------------------------- 1 | def multiply(*args): 2 | num = 1 3 | for x in args: 4 | num = num * x 5 | return num 6 | 7 | -------------------------------------------------------------------------------- /mysql/datalocks.sql: -------------------------------------------------------------------------------- 1 | select ENGINE_TRANSACTION_ID, LOCK_DATA, OBJECT_NAME, LOCK_MODE, LOCK_STATUS from performance_schema.data_locks; 2 | -------------------------------------------------------------------------------- /ingress/ingressclass.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: IngressClass 3 | metadata: 4 | name: nginx-class 5 | spec: 6 | controller: k8s.io/ingress-nginx 7 | -------------------------------------------------------------------------------- /conditional_statements.py: -------------------------------------------------------------------------------- 1 | age = 10 2 | if age < 13: 3 | print("You're a child") 4 | elif age >= 13 and age < 18: 5 | print("You're a teenager.") 6 | elif age >= 18: 7 | print("You're an Adult.") 8 | else: 9 | print("Huh???") 10 | -------------------------------------------------------------------------------- /mysql/3-data-modelling.txt: -------------------------------------------------------------------------------- 1 | Link to my spreadsheets 2 | 3 | Link 1: https://docs.google.com/spreadsheets/d/1nM7ReoTb5fsH3egoC4mLBgRSlY4kLWMXnVcyGTKdTJU/edit?usp=sharing 4 | 5 | Link 2: https://docs.google.com/spreadsheets/d/1nuaTmwhGrTh4BPaZLQzb_I8M0PBfFRGnA1Gn-OhH2gI/edit?usp=sharing 6 | -------------------------------------------------------------------------------- /13_pdb.py: -------------------------------------------------------------------------------- 1 | def square_and_multiply(*args): 2 | num = 1 3 | for x in args: 4 | num = num * (x**2) 5 | return num 6 | 7 | def multiply(*args): 8 | num = 1 9 | for x in args: 10 | num = num * x 11 | return num 12 | 13 | result1 = square_and_multiply(2,3,4) 14 | 15 | result2 = multiply(2,3,4) 16 | -------------------------------------------------------------------------------- /mysql/13-clustered-index.sql: -------------------------------------------------------------------------------- 1 | 2 | CREATE TABLE PRODUCTS_1 ( 3 | PRODUCT_ID int NOT NULL AUTO_INCREMENT, 4 | PRODUCT_NAME varchar(200) NOT NULL, 5 | PRODUCT_TYPE varchar(45) NOT NULL, 6 | PRICE decimal(10,2) NOT NULL, 7 | QUANTITY int NOT NULL default 0, 8 | PRIMARY KEY (PRODUCT_ID) 9 | ) ENGINE=InnoDB; 10 | 11 | alter table PRODUCTS_1 ADD CONSTRAINT PRODUCTS_ISBN UNIQUE (ISBN); 12 | -------------------------------------------------------------------------------- /Dockerfile_example: -------------------------------------------------------------------------------- 1 | # set base image 2 | FROM python:3.8 3 | 4 | # set the working directory in the container 5 | WORKDIR /var/tmp/jenkins 6 | 7 | # install dependencies 8 | RUN pip install requests 9 | 10 | # copy the content of the local src directory to the working directory 11 | COPY packages/ . 12 | 13 | # command to run on container start 14 | CMD [ "python", "./feature1.py" ] 15 | -------------------------------------------------------------------------------- /mysql/12-deadlocks.sql: -------------------------------------------------------------------------------- 1 | #Session 1 2 | 3 | update PRODUCTS set quantity=quantity+25 where product_id=1; 4 | 5 | #Session 2 6 | 7 | update PRODUCTS set price=price+2 where product_id=2; 8 | 9 | update PRODUCTS set price=price+2 where product_id=1; 10 | 11 | #Session 1 12 | 13 | update PRODUCTS set quantity=quantity+10 where product_id=2; 14 | #ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction 15 | -------------------------------------------------------------------------------- /mysql/4-create-table.sql: -------------------------------------------------------------------------------- 1 | 2 | -- please check my data modelling lesson to see how I create ECOMM_STORE schema 3 | 4 | use ECOMM_STORE; 5 | 6 | 7 | CREATE TABLE PRODUCTS_1 ( 8 | PRODUCT_ID int NOT NULL AUTO_INCREMENT, 9 | PRODUCT_NAME varchar(200) NOT NULL, 10 | PRODUCT_TYPE varchar(45) NOT NULL, 11 | PRICE decimal(10,2) NOT NULL, 12 | QUANTITY int NOT NULL default 0, 13 | PRIMARY KEY (PRODUCT_ID), 14 | UNIQUE KEY PRODUCT_NAME_UNIQUE (PRODUCT_NAME) 15 | ) ENGINE=InnoDB; 16 | -------------------------------------------------------------------------------- /10_oops_part2.py: -------------------------------------------------------------------------------- 1 | class Phones: 2 | 3 | def __init__(self, brand, color): 4 | self.brand = brand 5 | self.color = color 6 | 7 | def show_config(self): 8 | print("Color: ", self.color) 9 | print("Brand: ", self.brand) 10 | 11 | class Iphones(Phones): 12 | def __init__(self, brand, color, model): 13 | super().__init__(brand, color) 14 | self.model = model 15 | 16 | def show_config(self): 17 | super().show_config() 18 | print("Model: ", self.model) 19 | 20 | i = Iphones("Apple", "White", "Iphone 11") 21 | i.show_config() 22 | -------------------------------------------------------------------------------- /oracle_db_example.py: -------------------------------------------------------------------------------- 1 | import cx_Oracle 2 | #import click 3 | 4 | #@click.command() 5 | #@click.argument('sql') 6 | def main(): 7 | sql="select file#, name from v$datafile" 8 | db_user = "test_user" 9 | db_pass = "xx#" 10 | dbun = "db" 11 | db_dsn = cx_Oracle.makedsn("host", 1521, service_name=dbun) 12 | #print(db_dsn) 13 | conn = cx_Oracle.connect(db_user, db_pass, dsn=db_dsn) #mode=cx_Oracle.SYSDBA 14 | cursor = conn.cursor() 15 | cursor.execute(sql) 16 | res = cursor.fetchall() 17 | print(res) 18 | 19 | 20 | 21 | main() 22 | -------------------------------------------------------------------------------- /k8s_kube_proxy_cmds.txt: -------------------------------------------------------------------------------- 1 | kubectl get pods -l k8s-app=kube-proxy -n kube-system -o wide 2 | 3 | kubectl get deploy -o wide 4 | 5 | kubectl create deploy hello-world --image=nginx --replicas=3 6 | 7 | kubectl get deploy -o wide 8 | 9 | kubectl get pods -o wide 10 | 11 | kubectl get svc 12 | 13 | kubectl get svc kubernetes 14 | 15 | kubectl describe svc kubernetes 16 | 17 | kubectl cluster-info 18 | 19 | kubectl expose deploy/hello-world --port 8080 --target-port 80 --type NodePort 20 | 21 | kubectl describe svc hello-world 22 | 23 | kubectl get endpoints 24 | 25 | iptables -L KUBE-NODEPORTS -t nat 26 | -------------------------------------------------------------------------------- /1_variables.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Let's assume you have a small ecommerce/shopify website. 3 | You just had your first day of sale. At the end of the day,you want to calculate your total sales amount and the profit you made that day. 4 | ''' 5 | number_of_orders_today = 200 6 | average_price_of_orders = 25 7 | profit_margin = 0.10 8 | end_of_line_statement = "The End" 9 | 10 | print("Total Sale Amount: ") 11 | total_sales = number_of_orders_today*average_price_of_orders 12 | print(total_sales) 13 | print("My profit margin is: ") 14 | print(profit_margin) 15 | print("Profit: ") 16 | print(total_sales*profit_margin) 17 | print(end_of_line_statement) 18 | -------------------------------------------------------------------------------- /go/interfaces/main.go: -------------------------------------------------------------------------------- 1 | // Go interfaces 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | type Speak interface { 10 | greet() 11 | } 12 | 13 | type Dog struct { 14 | Name string 15 | } 16 | 17 | type Cat struct { 18 | Name string 19 | } 20 | 21 | func (c Cat) greet() { 22 | fmt.Println(c.Name, "says meow!") 23 | } 24 | 25 | func (d Dog) greet() { 26 | fmt.Println(d.Name, "says woof!") 27 | } 28 | 29 | func main() { 30 | 31 | var s Speak 32 | 33 | d1 := Dog{"Oscar"} 34 | s = d1 // implicit implementation 35 | s.greet() 36 | 37 | c1 := Cat{"Mittens"} 38 | s = c1 // runtime polymorphism 39 | s.greet() 40 | 41 | } 42 | -------------------------------------------------------------------------------- /ingress/ingress.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: ingress-rules 5 | annotations: 6 | ingress.kubernetes.io/rewrite-target: / 7 | spec: 8 | rules: 9 | - http: 10 | paths: 11 | - path: /httpd 12 | pathType: Exact 13 | backend: 14 | service: 15 | name: frontend1service 16 | port: 17 | number: 80 18 | - path: /nginx 19 | pathType: Exact 20 | backend: 21 | service: 22 | name: frontend2service 23 | port: 24 | number: 80 25 | -------------------------------------------------------------------------------- /find_duplicate_words.py: -------------------------------------------------------------------------------- 1 | str = "hi and hi hello and" 2 | str_list = str.split() 3 | #print(str_list) 4 | #Solution 1 O(n^2) 5 | 6 | duplicate_words = set() 7 | 8 | for word in str_list: #O(n) 9 | count = str_list.count(word) #O(n) 10 | if count > 1: 11 | duplicate_words.add(word) 12 | 13 | #print(duplicate_words) 14 | 15 | #Solution 2 O(n) 16 | str = "hi and hi hello and" 17 | str_list = str.split() 18 | 19 | count = {} 20 | duplicate_words = set() 21 | for word in str_list: 22 | count[word] = count.get(word, 0) + 1 23 | print(count) 24 | if count[word] > 1: 25 | duplicate_words.add(word) 26 | 27 | print(duplicate_words) 28 | -------------------------------------------------------------------------------- /go/sync-waitgroup/main.go: -------------------------------------------------------------------------------- 1 | // In this lesson, let's look at sync.WaitGroup 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "sync" 8 | "time" 9 | ) 10 | 11 | func myFunc2(wg *sync.WaitGroup) { 12 | time.Sleep(1 * time.Second) 13 | fmt.Println("Hello from myFunc2!") 14 | wg.Done() 15 | } 16 | 17 | func myFunc1(wg *sync.WaitGroup) { 18 | time.Sleep(1 * time.Second) 19 | fmt.Println("Hello from myFunc1!") 20 | wg.Done() 21 | } 22 | 23 | func main() { 24 | 25 | var wg sync.WaitGroup 26 | wg.Add(2) 27 | //go myFunc1() 28 | //time.Sleep(3*time.Second) 29 | go myFunc1(&wg) 30 | go myFunc2(&wg) 31 | wg.Wait() 32 | fmt.Println("Bye!") 33 | } 34 | -------------------------------------------------------------------------------- /ingress/frontend2service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | creationTimestamp: "2023-05-08T05:28:20Z" 5 | labels: 6 | app: frontend2 7 | name: frontend2service 8 | namespace: default 9 | resourceVersion: "72164" 10 | uid: 693b1ac7-42a2-4bed-ab64-81e5120717fe 11 | spec: 12 | clusterIP: 10.100.10.82 13 | clusterIPs: 14 | - 10.100.10.82 15 | internalTrafficPolicy: Cluster 16 | ipFamilies: 17 | - IPv4 18 | ipFamilyPolicy: SingleStack 19 | ports: 20 | - port: 80 21 | protocol: TCP 22 | targetPort: 80 23 | selector: 24 | app: frontend2 25 | sessionAffinity: None 26 | type: ClusterIP 27 | status: 28 | loadBalancer: {} 29 | -------------------------------------------------------------------------------- /ingress/frontend1service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | creationTimestamp: "2023-05-08T05:27:42Z" 5 | labels: 6 | app: frontend1 7 | name: frontend1service 8 | namespace: default 9 | resourceVersion: "72053" 10 | uid: 87a6fd6c-3896-4a66-8db0-5ea70fbb8953 11 | spec: 12 | clusterIP: 10.100.57.211 13 | clusterIPs: 14 | - 10.100.57.211 15 | internalTrafficPolicy: Cluster 16 | ipFamilies: 17 | - IPv4 18 | ipFamilyPolicy: SingleStack 19 | ports: 20 | - port: 80 21 | protocol: TCP 22 | targetPort: 80 23 | selector: 24 | app: frontend1 25 | sessionAffinity: None 26 | type: ClusterIP 27 | status: 28 | loadBalancer: {} 29 | -------------------------------------------------------------------------------- /ingress/ingress-modified.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | annotations: 5 | nginx.ingress.kubernetes.io/rewrite-target: / 6 | name: ingress-rules 7 | namespace: default 8 | spec: 9 | ingressClassName: nginx-class 10 | rules: 11 | - http: 12 | paths: 13 | - backend: 14 | service: 15 | name: frontend1service 16 | port: 17 | number: 80 18 | path: /httpd 19 | pathType: Exact 20 | - backend: 21 | service: 22 | name: frontend2service 23 | port: 24 | number: 80 25 | path: /nginx 26 | pathType: Exact 27 | -------------------------------------------------------------------------------- /test_multiply.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from multiply import * 4 | 5 | class TestMultiply(unittest.TestCase): 6 | def test1(self): 7 | result = multiply(10,20,30) 8 | self.assertEqual(result, 6000) 9 | 10 | def test2(self): 11 | result = multiply(10,20,30) 12 | self.assertTrue(result == 5000) 13 | 14 | def test3(self): 15 | result = multiply(10,20,30) 16 | self.assertFalse(result == 5000) 17 | 18 | def test4(self): 19 | result = multiply(10,20,30) 20 | self.assertIsNotNone(result) 21 | 22 | if __name__ == '__main__': 23 | unittest.main() 24 | 25 | 26 | #https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual -------------------------------------------------------------------------------- /go/contexts/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "context" // <-- this guy 6 | "fmt" 7 | "os" 8 | "time" 9 | ) 10 | 11 | func sleepAndTalk(ctx context.Context, t time.Duration, message string) { 12 | ch := make(chan bool) 13 | go func() { 14 | time.Sleep(t) 15 | fmt.Println(message) 16 | ch <- true 17 | }() 18 | for { 19 | select { 20 | case <-ctx.Done(): 21 | return 22 | case <-ch: 23 | return 24 | } 25 | } 26 | } 27 | 28 | func main() { 29 | 30 | //Make a background context 31 | ctx := context.Background() 32 | ctx, cancel := context.WithCancel(ctx) 33 | 34 | go func() { 35 | s := bufio.NewScanner(os.Stdin) 36 | s.Scan() 37 | cancel() 38 | }() 39 | 40 | sleepAndTalk(ctx, 10*time.Second, "Hello") 41 | 42 | } 43 | -------------------------------------------------------------------------------- /mysql/11-row-locks.sql: -------------------------------------------------------------------------------- 1 | #session 1 2 | 3 | set autocommit=0; 4 | 5 | set session transaction isolation level read committed; 6 | 7 | update PRODUCTS set quantity=quantity+50 where PRODUCT_ID=1; 8 | 9 | commit; 10 | 11 | #session 2 12 | 13 | set autocommit=0; 14 | 15 | set session transaction isolation level read committed; 16 | 17 | update PRODUCTS set quantity=quantity-1 where PRODUCT_ID=1; 18 | 19 | select * from PRODUCTS; 20 | 21 | #session 3 22 | 23 | set autocommit=0; 24 | 25 | set session transaction isolation level read committed; 26 | 27 | update PRODUCTS set quantity=quantity-1 where PRODUCT_ID=2; 28 | 29 | # MySQL Workbench 30 | 31 | select * from performance_schema.data_locks; 32 | 33 | show processlist; 34 | 35 | select * from information_schema.processlist; 36 | -------------------------------------------------------------------------------- /ingress/ingress-foo-modified.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: ingress-rules 5 | namespace: default 6 | spec: 7 | ingressClassName: nginx-class 8 | rules: 9 | - host: httpd.executeoncommand.click 10 | http: 11 | paths: 12 | - path: / 13 | pathType: Prefix 14 | backend: 15 | service: 16 | name: frontend1service 17 | port: 18 | number: 80 19 | - host: nginx.executeoncommand.click 20 | http: 21 | paths: 22 | - path: / 23 | pathType: Prefix 24 | backend: 25 | service: 26 | name: frontend2service 27 | port: 28 | number: 80 29 | -------------------------------------------------------------------------------- /backend.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | labels: 5 | env: qa 6 | name: my-application 7 | spec: 8 | containers: 9 | - image: busybox 10 | name: myapp-container 11 | command: ['sh', '-c', 'echo The app is running! && sleep 3600'] 12 | initContainers: 13 | - image: python:3.8-slim 14 | name: init-database 15 | command: ['sh', '-c', 'pip install mysql-connector-python && until python /tmp/mysql-program.py; do echo waiting for db initialization; sleep 2; done'] 16 | volumeMounts: 17 | - name: mysqlprogram 18 | mountPath: /tmp 19 | volumes: 20 | - name: mysqlprogram 21 | configMap: 22 | name: mysql-program 23 | items: 24 | - key: mysql-program.py 25 | path: mysql-program.py 26 | -------------------------------------------------------------------------------- /kubernetes/cordon-drain.txt: -------------------------------------------------------------------------------- 1 | kubectl get nodes 2 | 3 | kubectl cordon node1 4 | 5 | kubectl get nodes 6 | 7 | kubectl run test-pod --image=busybox -- sleep 300 8 | 9 | kubectl uncordon node1 10 | 11 | kubectl run test-pod2 --image=busybox -- sleep 300 12 | 13 | kubectl create deploy some-deployment --image=busybox --replicas=2 -- sleep 300 14 | 15 | kubectl create deploy test-deploy --image=busybox --replicas=5 -- sleep 300 16 | 17 | kubectl get pod -o wide 18 | 19 | kubectl drain node2 20 | 21 | kubectl drain node2 --ignore-daemonsets 22 | 23 | kubectl get node node2 24 | NAME STATUS ROLES AGE VERSION 25 | node2 Ready,SchedulingDisabled 180d v1.20.5 26 | 27 | kubectl uncordon node2 28 | 29 | kubectl rollout restart deployment/test-deploy 30 | 31 | kubectl delete deploy test-deploy 32 | -------------------------------------------------------------------------------- /6_tuples.py: -------------------------------------------------------------------------------- 1 | Tuple is an ordered collection of objects, that is immutable. 2 | 3 | list_1 = ['Banana', 'Apple', 'Water Melon', 'Pineapple', 'Mango'] #List 4 | 5 | tuple_1 = ('Banana', 'Apple', 'Water Melon', 'Pineapple', 'Mango') #Tuple 6 | 7 | set_1 = { "v1", "v2", "v3"} #set 8 | 9 | #unordered vs ordered data structure 10 | 11 | print(set_1) 12 | 13 | print(tuple_1) 14 | 15 | #immutable 16 | 17 | list_1[0] = "Kiwi" 18 | 19 | tuple_1[0] = "Kiwi" 20 | 21 | # List or a mutable object inside tuple 22 | 23 | tuple_2 = ('Cherry', 'Kiwi', ['Strawberry']) 24 | 25 | tuple_2[2].append('Blueberry') 26 | 27 | # Packing and Unpacking 28 | 29 | tuple_3 = ('Banana', 'Apple', 'Water Melon') 30 | 31 | (fruit_1, fruit_2, fruit_3) = tuple_3 32 | 33 | fruit_1, fruit_2, fruit_3 = tuple_3 34 | 35 | # Swapping 36 | 37 | a = 3 38 | b = 4 39 | 40 | a, b 41 | b, a 42 | 43 | a, b = b, a 44 | -------------------------------------------------------------------------------- /mysql-program.py: -------------------------------------------------------------------------------- 1 | import mysql.connector 2 | from mysql.connector import Error 3 | 4 | try: 5 | connection = mysql.connector.connect(host='service ip', 6 | database='mysql', 7 | user='root', 8 | password='abc') 9 | if connection.is_connected(): 10 | db_Info = connection.get_server_info() 11 | print("Connected to MySQL Server version ", db_Info) 12 | cursor = connection.cursor() 13 | cursor.execute("select database();") 14 | record = cursor.fetchone() 15 | print("You're connected to database: ", record) 16 | 17 | except Error as e: 18 | print("Error while connecting to MySQL", e) 19 | finally: 20 | if connection.is_connected(): 21 | cursor.close() 22 | connection.close() 23 | print("MySQL connection is closed") 24 | -------------------------------------------------------------------------------- /mysql/9-isolation-levels.sql: -------------------------------------------------------------------------------- 1 | #session 1 2 | set autocommit=0; 3 | start transaction; 4 | drop table ECOMM_STORE.t1; 5 | create table ECOMM_STORE.t1 ( c1 int primary key); 6 | insert into ECOMM_STORE.t1 values (1); 7 | commit; 8 | 9 | update ECOMM_STORE.t1 set c1 = 2 where c1 = 1; 10 | 11 | 12 | #session 2 13 | set session transaction isolation level read committed; 14 | show variables like '%isolation%'; 15 | select * from ECOMM_STORE.t1; 16 | 17 | show session variables like '%isolation%'; 18 | set session transaction isolation level read uncommitted; 19 | show session variables like '%isolation%'; 20 | select * from ECOMM_STORE.t1; 21 | 22 | set session transaction isolation level repeatable read; 23 | show variables like '%isolation%'; 24 | select * from ECOMM_STORE.t1; 25 | 26 | set session transaction isolation level serializable; 27 | show session variables like '%isolation%'; 28 | select * from ECOMM_STORE.t1; 29 | -------------------------------------------------------------------------------- /7_list_comprehension.py: -------------------------------------------------------------------------------- 1 | #[expression for item in iterable_object] 2 | 3 | #Find the cubes of the even numbers between 0 and 10 4 | 5 | #Using for loop 6 | 7 | even_cubes = [] 8 | for num in range(0,11,2): 9 | even_cubes.append(num**3) 10 | 11 | print("Even Cubes:", even_cubes) 12 | 13 | #Using Map 14 | 15 | def calculate_cube(num): 16 | return num**3 17 | 18 | result = map(calculate_cube,range(0,11,2)) 19 | 20 | print(list(result)) 21 | 22 | #List comprehension 23 | 24 | even_cubes = [ num**3 for num in range(0,11,2) ] 25 | 26 | print("Even Cubes:", even_cubes) 27 | 28 | 29 | #Using a function instead of expression 30 | 31 | def calculate_power(num, power): 32 | return num**power 33 | 34 | result = [ calculate_power(num,3) for num in range(0,11,2) ] 35 | 36 | print(result) 37 | 38 | 39 | #Using if condition 40 | 41 | def calculate_power(num, power): 42 | return num**power 43 | 44 | result = [ calculate_power(num,3) for num in range(0,11) if num % 2 == 0 ] 45 | 46 | print(result) 47 | -------------------------------------------------------------------------------- /balanced_brackets.py: -------------------------------------------------------------------------------- 1 | open_brackets = ["[","{","("] 2 | close_brackets = ["]","}",")"] 3 | bracket_pairs = {"]":"[", "}":"{", ")":"("} 4 | def isBalanced(str): 5 | stack = [] 6 | for i in str: 7 | if i in open_brackets or i in close_brackets: 8 | if i in open_brackets: 9 | stack.append(i) 10 | elif i in close_brackets: 11 | if (len(stack) > 0): 12 | top_element = stack.pop() 13 | if top_element != bracket_pairs[i]: 14 | return "Unbalanced String." 15 | else: 16 | return "Unbalanced String" 17 | if len(stack) == 0: 18 | return "Balanced String" 19 | else: 20 | return "Unbalanced String" 21 | 22 | # Main 23 | mystring1 = "{[]{()}}" 24 | mystring2 = "{123(456[.768])}" 25 | mystring3 = "(1+3)-(2-3))" 26 | print(f"{mystring1} is {isBalanced(mystring1)}") 27 | print(f"{mystring2} is {isBalanced(mystring2)}") 28 | print(f"{mystring3} is {isBalanced(mystring3)}") 29 | -------------------------------------------------------------------------------- /mysql/10-table-locks.sql: -------------------------------------------------------------------------------- 1 | insert into PRODUCTS values (1,'The Common Path To Uncommon Success','Book',16.99,40); 2 | insert into PRODUCTS values (2,'Tiny Habits','Book',20.39,100); 3 | 4 | #session 1 5 | 6 | mysql> set autocommit=0; 7 | Query OK, 0 rows affected (0.00 sec) 8 | 9 | mysql> lock table PRODUCTS write; 10 | Query OK, 0 rows affected (0.00 sec) 11 | 12 | mysql> unlock TABLES; 13 | 14 | update PRODUCTS set quantity=quantity+60 where PRODUCT_ID=1; 15 | 16 | commit; 17 | 18 | #session 2 19 | 20 | mysql> set autocommit=0; 21 | 22 | mysql> update PRODUCTS set quantity=quantity-2 where PRODUCT_ID=1; 23 | 24 | update PRODUCTS set quantity=quantity-2 where PRODUCT_ID=1; 25 | 26 | commit; 27 | 28 | #session 3 29 | 30 | mysql> select * from PRODUCTS; 31 | 32 | update PRODUCTS set quantity=quantity-2 where PRODUCT_ID=2; 33 | 34 | commit; 35 | 36 | 37 | # MySQL Workbench 38 | 39 | select * from performance_schema.data_locks; 40 | 41 | show processlist; 42 | 43 | select * from information_schema.processlist; 44 | -------------------------------------------------------------------------------- /unittest_examply.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class TestStringMethods(unittest.TestCase): 4 | 5 | def setUp(self): 6 | pass 7 | 8 | # Returns True if the string contains 4 a. 9 | def test_strings_a(self): 10 | self.assertEqual( 'a'*4, 'aaaa') 11 | 12 | # Returns True if the string is in upper case. 13 | def test_upper(self): 14 | self.assertEqual('foo'.upper(), 'FOO') 15 | 16 | # Returns TRUE if the string is in uppercase 17 | # else returns False. 18 | def test_isupper(self): 19 | self.assertTrue('FOO'.isupper()) 20 | self.assertFalse('Foo'.isupper()) 21 | 22 | # Returns true if the string is stripped and 23 | # matches the given output. 24 | def test_strip(self): 25 | s = 'geeksforgeeks' 26 | self.assertEqual(s.strip('geek'), 'sforgeeks') 27 | 28 | # Returns true if the string splits and matches 29 | # the given output. 30 | def test_split(self): 31 | s = 'hello world' 32 | self.assertEqual(s.split(), ['hello', 'world']) 33 | with self.assertRaises(TypeError): 34 | s.split(2) 35 | 36 | if __name__ == '__main__': 37 | unittest.main() 38 | -------------------------------------------------------------------------------- /15_pickle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Pickle / Unpickle 3 | - helps you to serialize/deserialize objects or data structures 4 | - Serialization is the process of converting an object state into a format that can be saved into a file or memory. 5 | - can be used as cache 6 | - support many object types but there are limitations (Database connections, lambda, threads etc.) 7 | - dump/dumps and load/loads 8 | ''' 9 | 10 | import time 11 | import pickle 12 | import os 13 | 14 | def generate_even_squares(numbers): 15 | even_list = [] 16 | for num in numbers: 17 | if num % 2 == 0: 18 | even_list.append(num*num) 19 | 20 | return even_list 21 | 22 | t1 = time.time() 23 | 24 | if os.path.exists("even.pickle"): 25 | file = open('even.pickle', 'rb') 26 | even_squares = pickle.load(file) 27 | file.close() 28 | else: 29 | even_squares = generate_even_squares(range(30000000)) 30 | file = open('even.pickle', 'wb') 31 | pickle.dump(even_squares, file) 32 | file.close() 33 | 34 | print(even_squares[:20]) 35 | 36 | t2 = time.time() 37 | time_diff = t2 - t1 38 | 39 | print(round(time_diff,1), "secs") 40 | -------------------------------------------------------------------------------- /mysql/6-update-delete.sql: -------------------------------------------------------------------------------- 1 | USE ECOMM_STORE; 2 | 3 | select * from PRODUCTS; 4 | 5 | UPDATE PRODUCTS 6 | SET 7 | quantity = quantity + 50 8 | WHERE 9 | product_id = 1; 10 | 11 | commit; 12 | 13 | select * from PRODUCTS; 14 | 15 | UPDATE PRODUCTS 16 | SET 17 | quantity = quantity + 50 18 | WHERE 19 | product_id in (1,2,3); 20 | 21 | commit; 22 | 23 | select * from PRODUCTS; 24 | 25 | UPDATE PRODUCTS 26 | SET quantity = CASE 27 | WHEN product_id = 1 THEN quantity + 50 28 | WHEN product_id = 2 THEN quantity + 100 29 | ELSE 100 30 | END 31 | WHERE 32 | product_id in (1,2,3); 33 | 34 | commit; 35 | 36 | select * from PRODUCTS; 37 | 38 | DELETE FROM PRODUCTS 39 | WHERE PRODUCT_ID = 3; 40 | 41 | commit; 42 | 43 | select * from PRODUCTS; 44 | 45 | select * from PRODUCTS_3; 46 | 47 | DELETE FROM PRODUCTS_3 48 | WHERE quantity < 10; 49 | 50 | select * from PRODUCTS_3; 51 | 52 | DELETE FROM PRODUCTS_3 53 | LIMIT 10; 54 | 55 | commit; 56 | 57 | select * from PRODUCTS_3; 58 | 59 | DELETE FROM PRODUCTS_3 60 | ORDER BY PRODUCT_ID 61 | LIMIT 10; 62 | 63 | COMMIT; 64 | -------------------------------------------------------------------------------- /9_oops_part1.py: -------------------------------------------------------------------------------- 1 | class Avengers: 2 | 3 | __team = [] 4 | _name = "Avengers" 5 | headquarters = "890 Fifth Avenue, Manhattan, New York City, NY" 6 | 7 | def __init__(self, director): 8 | self._director = director 9 | 10 | def get_name(self): 11 | return Avengers._name 12 | 13 | def get_director(self): 14 | return self._director 15 | 16 | def add_hero(self, hero): 17 | Avengers.__team.append(hero) 18 | 19 | def show_team(self): 20 | print(Avengers.__team) 21 | 22 | class NickFury(Avengers): 23 | 24 | def __init__(self): 25 | 26 | self.original_name = "Nicholas Joseph Fury" 27 | self.birth_place = "Alabama" 28 | self.health = 100 29 | 30 | class Talos(Avengers): 31 | 32 | def __init__(self): 33 | 34 | self.original_name = "Talos the Skrull" 35 | self.birth_place = "Tarnax IV" 36 | self.health = 100 37 | 38 | nf = NickFury() 39 | av1 = Avengers(nf.original_name) 40 | print(av1.headquarters) 41 | print(av1._director) 42 | 43 | ta = Talos() 44 | av2 = Avengers(ta.original_name) 45 | print(av2.headquarters) 46 | print(av2._director) 47 | 48 | #nf.add_hero("Captain America") 49 | #nf.show_team() 50 | -------------------------------------------------------------------------------- /17_generators.py: -------------------------------------------------------------------------------- 1 | # Normal method 2 | import memory_profiler 3 | 4 | def generate_even_squares(numbers): 5 | even_list = [] 6 | for num in numbers: 7 | if num % 2 == 0: 8 | even_list.append(num*num) 9 | 10 | return even_list 11 | 12 | m1 = memory_profiler.memory_usage() 13 | es = generate_even_squares(range(30000000)) 14 | 15 | counter=0 16 | for x in es: 17 | if counter > 10: 18 | break 19 | print(x) 20 | counter = counter + 1 21 | 22 | m2 = memory_profiler.memory_usage() 23 | print("Memory used (mb): ", round(m2[0]-m1[0])) 24 | 25 | 26 | # Generator method 27 | import memory_profiler 28 | def generate_even_squares(numbers): 29 | even_list = [] 30 | for num in numbers: 31 | if num % 2 == 0: 32 | yield (num*num) 33 | 34 | m1 = memory_profiler.memory_usage() 35 | es = generate_even_squares(range(10000)) 36 | ''' 37 | print(next(es)) 38 | print(next(es)) 39 | print(next(es)) 40 | ''' 41 | counter=0 42 | for x in es: 43 | if counter > 10: 44 | break 45 | print(x) 46 | counter = counter + 1 47 | 48 | m2 = memory_profiler.memory_usage() 49 | print("Memory used (mb): ", round(m2[0]-m1[0])) 50 | -------------------------------------------------------------------------------- /mysql/2-mysql-installation.txt: -------------------------------------------------------------------------------- 1 | yum install wget -y 2 | 3 | wget https://dev.mysql.com/get/mysql80-community-release-el8-1.noarch.rpm 4 | 5 | md5sum mysql80-community-release-el8-1.noarch.rpm 6 | 7 | First, add the MySQL Yum repository to your system's repository list. 8 | This is a one-time operation, which can be performed by installing an RPM provided by MySQL. Follow these steps: 9 | 10 | rpm -ivh mysql80-community-release-el8-1.noarch.rpm 11 | 12 | https://dev.mysql.com/doc/refman/8.0/en/linux-installation-yum-repo.html 13 | (EL8 systems only) EL8-based systems such as RHEL8 and 14 | Oracle Linux 8 include a MySQL module that is enabled by default. 15 | Unless this module is disabled, it masks packages provided by MySQL repositories 16 | 17 | yum module disable mysql 18 | 19 | yum install mysql-community-server 20 | 21 | systemctl start mysqld 22 | 23 | systemctl status mysqld 24 | 25 | ps -ef | grep mysql 26 | 27 | cat /var/log/mysqld.log|grep temp 28 | 29 | mysql -u root -p mysql 30 | 31 | mysqladmin -u root -p password 32 | 33 | mysql -u root -p mysql 34 | 35 | select * from mysql.time_zone; 36 | 37 | mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql 38 | -------------------------------------------------------------------------------- /postgres/jdbc_ssl_connector.java: -------------------------------------------------------------------------------- 1 | package com.postgresqlexample; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | 7 | public class ConnectDB { 8 | 9 | private final String url = "jdbc:postgresql://aa.bbb.ccc.dd/postgres?sslmode=require&sslcert=/root/.postgresql/postgresql.crt&sslkey=/root/.postgresql/postgresql.pk8&sslrootcert=/root/.postgresql/root.crt&sslpassword="; 10 | 11 | private final String user = "postgres"; 12 | private final String password = "password"; 13 | 14 | /** 15 | * Connect to the PostgreSQL database 16 | * 17 | * @return a Connection object 18 | */ 19 | public Connection connect() { 20 | Connection conn = null; 21 | try { 22 | conn = DriverManager.getConnection(url, user, password); 23 | System.out.println("Connected to the PostgreSQL server successfully."); 24 | } catch (SQLException e) { 25 | System.out.println(e.getMessage()); 26 | } 27 | 28 | return conn; 29 | } 30 | 31 | public static void main(String[] args) { 32 | 33 | ConnectDB db = new ConnectDB(); 34 | db.connect(); 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /12_asyncio.py: -------------------------------------------------------------------------------- 1 | #Install these packages first. 2 | #pip install --upgrade pip aiohttp aiofiles 3 | 4 | #Sequential program example 5 | 6 | import time 7 | 8 | def make_coffee(): 9 | print("Start Making Coffee...") 10 | time.sleep(10) 11 | print("Finish Making Coffee...") 12 | 13 | def make_toast(): 14 | print("Start making toast...") 15 | time.sleep(10) 16 | print("Finish making toast...") 17 | 18 | 19 | def morning_routine(): 20 | make_coffee() 21 | make_toast() 22 | 23 | 24 | t1 = time.perf_counter() 25 | morning_routine() 26 | elapsed = time.perf_counter() - t1 27 | print(f"Time Taken: {elapsed:0.2f} seconds.") 28 | 29 | #async program example 30 | 31 | import asyncio 32 | import time 33 | 34 | async def make_coffee(): 35 | print("Start Making Coffee...") 36 | await asyncio.sleep(10) 37 | print("Finish Making Coffee...") 38 | 39 | async def make_toast(): 40 | print("Start making toast...") 41 | await asyncio.sleep(10) 42 | print("Finish making toast...") 43 | 44 | async def morning_routine(): 45 | await asyncio.gather(make_coffee(), make_toast()) 46 | 47 | 48 | t1 = time.perf_counter() 49 | asyncio.run(morning_routine()) 50 | elapsed = time.perf_counter() - t1 51 | print(f"Time Taken: {elapsed:0.2f} seconds.") 52 | -------------------------------------------------------------------------------- /logging_example.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import logging 4 | 5 | logging.debug('This is a debug message') 6 | logging.info('This is an info message') 7 | logging.warning('This is a warning message') 8 | logging.error('This is an error message') 9 | logging.critical('This is a critical message') 10 | 11 | # 12 | 13 | import logging 14 | 15 | logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s') 16 | logging.warning('This will get logged to a file') 17 | 18 | # Create a custom logger 19 | logger = logging.getLogger("wrapper") 20 | 21 | # Create handlers 22 | c_handler = logging.StreamHandler() 23 | f_handler = logging.FileHandler('file.log') 24 | c_handler.setLevel(logging.WARNING) 25 | f_handler.setLevel(logging.ERROR) 26 | 27 | # Create formatters and add it to handlers 28 | c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s') 29 | f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 30 | c_handler.setFormatter(c_format) 31 | f_handler.setFormatter(f_format) 32 | 33 | # Add handlers to the logger 34 | logger.addHandler(c_handler) 35 | logger.addHandler(f_handler) 36 | 37 | logger.warning('This is a warning') 38 | logger.error('This is an error') 39 | -------------------------------------------------------------------------------- /14_mocks.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest.mock import Mock 3 | from requests.exceptions import Timeout 4 | 5 | cx_Oracle = Mock() 6 | 7 | def query_database(sql): 8 | 9 | db_user = "blah" 10 | db_pass = "blah" 11 | db_dsn = '(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = tcp)(host = host1) (Port = 1525))) (CONNECT_DATA = (SID = orcl)))' 12 | 13 | try: 14 | res = cx_Oracle.connect(db_user, db_pass, dsn=db_dsn).cursor().execute(sql).fetchall() 15 | print("Query executed successfully.") 16 | except: 17 | print("Insert the error into a log table.") 18 | 19 | return res[0][0] 20 | 21 | class TestDatabase(unittest.TestCase): 22 | def test1_query_database(self): 23 | sql = "select max(id) from orders" 24 | cx_Oracle.connect().cursor().execute(sql).fetchall.return_value = [(100,)] 25 | self.assertEqual(query_database(sql), 100) 26 | 27 | def test2_query_database(self): 28 | sql = "select max(id) from orders" 29 | cx_Oracle.connect().cursor().execute(sql).fetchall.side_effect = [[(100,)], Timeout] 30 | self.assertEqual(query_database(sql), 100) 31 | with self.assertRaises(Exception): 32 | query_database(sql) 33 | 34 | if __name__ == '__main__': 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /5_dictionaries.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Definition 3 | 4 | A dictionary is a collection of key/value pairs, very similar to lists except you use keys instead of indexes to access the values in it. 5 | 6 | Syntax: 7 | 8 | d = { key1: val1, key2: val2, ... } 9 | 10 | A key can be of any immutable data type. 11 | 12 | ''' 13 | 14 | 15 | #d = { [1,2] : True } 16 | #print(d) 17 | d = { (1,2) : True } 18 | print(d) 19 | 20 | 21 | emails = {} or dict() 22 | 23 | emails = { "David" : "david.r@abc.com" } 24 | 25 | #Accessing 26 | emails = { "David" : "david.r@abc.com" } 27 | 28 | print (emails["David"]) 29 | 30 | print (emails["Sam"]) 31 | 32 | print (emails.get("Sam", None)) 33 | 34 | #Add 35 | emails["Brian"] = "brian123@testmail.com" 36 | emails["Tom"] = "tom.sawyer@xyz.com" 37 | 38 | #Modify 39 | emails["David"] = "david.s@abc.com" 40 | 41 | #Remove 42 | del emails["David"] 43 | 44 | #update 45 | new_emails = { "David" : "david.r@xyz.com", "Sam" : "sam.wes@testmail.com" } 46 | 47 | emails.update(new_emails) 48 | 49 | #pop, popitem 50 | 51 | element = emails.pop("Sam") 52 | print(element) 53 | 54 | emails["Sam"] = "sam.wes@testmail.com" 55 | element = emails.popitem() 56 | print(element) 57 | 58 | #items, keys and values 59 | emails.items() 60 | emails.keys() 61 | emails.values() 62 | 63 | #len 64 | len(email) 65 | 66 | #clear 67 | emails.clear() 68 | print(emails) 69 | -------------------------------------------------------------------------------- /mysql/5-insert-data.sql: -------------------------------------------------------------------------------- 1 | desc ECOMM_STORE.PRODUCTS_1; 2 | 3 | INSERT INTO `ECOMM_STORE`.`PRODUCTS_1` 4 | (`PRODUCT_NAME`, 5 | `PRODUCT_TYPE`, 6 | `PRICE`, 7 | `QUANTITY`) 8 | VALUES 9 | ('Deep Work','Book',14.99,100); 10 | 11 | INSERT INTO `ECOMM_STORE`.`PRODUCTS_1` 12 | (`PRODUCT_ID`, 13 | `PRODUCT_NAME`, 14 | `PRODUCT_TYPE`, 15 | `PRICE`, 16 | `QUANTITY`) 17 | VALUES 18 | (2,'Digital Minimalism','Book',18.99,150); 19 | 20 | INSERT INTO `ECOMM_STORE`.`PRODUCTS_1` 21 | (`PRODUCT_ID`, 22 | `PRODUCT_NAME`, 23 | `PRODUCT_TYPE`, 24 | `PRICE`, 25 | `QUANTITY`) 26 | VALUES 27 | (10,'Art of possibilities','Book',10.99,50); 28 | 29 | INSERT INTO `ECOMM_STORE`.`PRODUCTS_1` 30 | (`PRODUCT_NAME`, 31 | `PRODUCT_TYPE`, 32 | `PRICE`, 33 | `QUANTITY`) 34 | VALUES 35 | ('Mind at its Home','Book',12.99,100); 36 | 37 | 38 | TRUNCATE TABLE ECOMM_STORE.PRODUCTS_1; 39 | 40 | insert into `ECOMM_STORE`.`PRODUCTS_1` 41 | SELECT `PRODUCTS_3`.`PRODUCT_ID`, 42 | `PRODUCTS_3`.`PRODUCT_NAME`, 43 | `PRODUCTS_3`.`PRODUCT_TYPE`, 44 | `PRODUCTS_3`.`PRICE`, 45 | `PRODUCTS_3`.`QUANTITY` 46 | FROM `ECOMM_STORE`.`PRODUCTS_3`; 47 | 48 | TRUNCATE TABLE ECOMM_STORE.PRODUCTS_1; 49 | 50 | INSERT INTO `ECOMM_STORE`.`PRODUCTS_1` 51 | (`PRODUCT_NAME`, 52 | `PRODUCT_TYPE`, 53 | `PRICE`, 54 | `QUANTITY`) 55 | VALUES 56 | ('Deep Work','Book',14.99,100),('Mind at its Home','Book',12.99,100); 57 | -------------------------------------------------------------------------------- /4_sets.py: -------------------------------------------------------------------------------- 1 | #set_variable_name = set() 2 | 3 | #Caveat while initializing an empty set 4 | vegetables = set() 5 | print(type(vegetables)) 6 | vegetables = {} 7 | print(type(vegetables)) 8 | 9 | vegetables = {"Potatoes", "Carrots", "Cauliflower", "Broccoli", "Bell Pepper"} 10 | 11 | print(vegetables) 12 | print(type(vegetables)) 13 | 14 | vegetables = set(["Potatoes", "Carrots", "Cauliflower", "Broccoli", "Bell Pepper"]) 15 | 16 | print(vegetables) 17 | print(type(vegetables)) 18 | 19 | vegetables = set("Potatoes") 20 | print(vegetables) 21 | print(type(vegetables)) 22 | 23 | #Mixed datatype set 24 | vegetables = {"Potatoes", "Carrots", "Cauliflower", "Broccoli", "Bell Pepper", 12} 25 | print(vegetables) 26 | 27 | #vegetables = {"Potatoes", "Carrots", "Cauliflower", "Broccoli", "Bell Pepper", [1,2]} 28 | #lst = [1,2] 29 | #print(lst.__hash__()) 30 | #num = 1 31 | #print(num.__hash__()) 32 | 33 | vegetables.remove(12) 34 | print(vegetables) 35 | #vegetables.remove(12) 36 | #print(vegetables) 37 | vegetables.discard(12) 38 | print(vegetables) 39 | 40 | vegetables2 = set() 41 | vegetables2.add("Egg Plant") 42 | vegetables2.add("Sweet Potatoes") 43 | vegetables2.add("Green Beans") 44 | print(vegetables2) 45 | 46 | print(vegetables | vegetables2) 47 | 48 | vegetables2.add("Potatoes") 49 | print(vegetables2) 50 | 51 | print(vegetables & vegetables2) 52 | 53 | print(vegetables - vegetables2) 54 | 55 | vegetables2.pop() 56 | print(vegetables2) 57 | -------------------------------------------------------------------------------- /insertion_sort.py: -------------------------------------------------------------------------------- 1 | 2 | # Insertion Sort 3 | ''' 4 | Code with bells and whistles 5 | def displayList(arr): 6 | surround_arr = ["--" for num in arr] 7 | surround_arr = "-----" + '--'.join(surround_arr) 8 | arr = [str(num) for num in arr] 9 | array = "| " + ' | '.join(arr) + " |" 10 | print(surround_arr) 11 | print(array) 12 | print(surround_arr) 13 | 14 | cards = [6, 8, 5, 4, 3] 15 | displayList(cards) #Aesthetics 16 | hit_key = input() 17 | for new_card_pos in range(1, len(cards)): 18 | key_card = cards[new_card_pos] 19 | print("Key card = ",key_card) #Aesthetics 20 | comparing_pointer = new_card_pos - 1 21 | while comparing_pointer >= 0 and key_card < cards[comparing_pointer]: 22 | cards[comparing_pointer+1] = cards[comparing_pointer] 23 | cards[comparing_pointer] = " " #Aesthetics 24 | comparing_pointer = comparing_pointer - 1 25 | displayList(cards) #Aesthetics 26 | cards[comparing_pointer+1] = key_card 27 | displayList(cards) #Aesthetics 28 | hit_key = input() #Aesthetics 29 | ''' 30 | 31 | cards = [6, 8, 5, 4, 3] 32 | for new_card_pos in range(1, len(cards)): 33 | key_card = cards[new_card_pos] 34 | comparing_pointer = new_card_pos - 1 35 | while comparing_pointer >= 0 and key_card < cards[comparing_pointer]: 36 | cards[comparing_pointer+1] = cards[comparing_pointer] 37 | comparing_pointer = comparing_pointer - 1 38 | cards[comparing_pointer+1] = key_card 39 | 40 | # Worst case O(n^2) [8,6,5,4,3] 41 | # Best case O(n) [3,4,5,6,8] 42 | -------------------------------------------------------------------------------- /11_oops_part3.py: -------------------------------------------------------------------------------- 1 | # ability to leverage the same interface for different underlying forms such as data types or classes 2 | 3 | # Polymorphism allows for flexibility and loose coupling so that code can be extended and easily maintained over time. 4 | 5 | 6 | # Polymorphism - the condition of occurring in several different forms 7 | 8 | + 9 | [] 10 | 11 | print(5 + 6) 12 | print("Hello" + "World") 13 | 14 | str = "Hello" 15 | str[0] 16 | 17 | l = ["a","b","c","d"] 18 | l[2] 19 | 20 | 21 | # creating class methods as Python allows different classes to have methods with the same name 22 | 23 | class Browser: 24 | def __init__(self): 25 | print("Browser is created.") 26 | 27 | def open_website(self, address): 28 | print(f"Going to www.{address}.com") 29 | 30 | def About(): 31 | print("I am a Browser.") 32 | 33 | class Chrome(Browser): 34 | def __init__(self): 35 | print("Chrome Browser Created") 36 | 37 | def About(self): 38 | print("Version: 83.0.4103.116 64-bit") 39 | 40 | def Extension(self): 41 | print("I have lots of cool extensions.") 42 | 43 | 44 | class Firefox(Browser): 45 | def __init__(self): 46 | print("Firefox Browser Created") 47 | 48 | def About(self): 49 | print("Version: 78.0.1 64-bit") 50 | 51 | def AddOn(self): 52 | print("I have lots of cool Add-ons") 53 | 54 | 55 | c = Chrome() 56 | f = Firefox() 57 | 58 | 59 | for browse in (c, f): 60 | browse.About() 61 | 62 | c.open_website("google") 63 | f.open_website("facebook") 64 | c.About() 65 | f.About() 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /bubblesort.py: -------------------------------------------------------------------------------- 1 | def displayList(arr): 2 | surround_arr = ["--" for num in arr] 3 | surround_arr = "-----" + '--'.join(surround_arr) + "----" 4 | arr = [str(num) for num in arr] 5 | array = "| " + ' | '.join(arr) + " |" 6 | print(surround_arr) 7 | print(array) 8 | print(surround_arr) 9 | 10 | def displayIndex(arr, j): 11 | arr = [" " for num in arr] 12 | arr[j] = "\u2191" 13 | arr_str1 = " " + ' '.join(arr) + " " 14 | print(arr_str1) 15 | arr[j] = "j" 16 | arr[j+1] = "j+1" 17 | arr_str2 = " " + ' '.join(arr) 18 | print(arr_str2) 19 | 20 | 21 | def bubble_sort(mylist): 22 | n = len(mylist) 23 | count = 0 24 | swap = True 25 | 26 | print("Initial List: ") 27 | displayList(mylist) 28 | print() 29 | 30 | for i in range(n-1): 31 | if swap: 32 | swap = False 33 | print() 34 | print(f"Iteration# {i+1}") 35 | for j in range(0, n-i-1): 36 | displayList(mylist) 37 | displayIndex(mylist,j) 38 | count = count + 1 39 | print() 40 | print(f"Step# {count}") 41 | print() 42 | if mylist[j] > mylist[j+1] : 43 | print() 44 | print(f"{mylist[j]} is greater than {mylist[j+1]}.") 45 | print(f"Swap - {mylist[j]} \u2194 {mylist[j+1]}") 46 | print() 47 | mylist[j], mylist[j+1] = mylist[j+1], mylist[j] 48 | swap = True 49 | 50 | displayList(mylist) 51 | 52 | mylist = [19, 23, 10, 19, 32, 60, 87] 53 | bubble_sort(mylist) 54 | 55 | ''' 56 | (n-1) + (n-2) + (n-3) + ..... + 3 + 2 + 1 57 | 58 | sum of a sequence (n values) = n*(n+1)/2 59 | 60 | Sum = n(n-1)/2 = (n^2 - n)/2 61 | i.e O(n^2) / O(1) 62 | ''' 63 | -------------------------------------------------------------------------------- /ingress/frontend2-dep.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | annotations: 5 | deployment.kubernetes.io/revision: "1" 6 | creationTimestamp: "2023-05-08T05:27:59Z" 7 | generation: 1 8 | labels: 9 | app: frontend2 10 | name: frontend2 11 | namespace: default 12 | resourceVersion: "72126" 13 | uid: f3d249ad-4baa-41c1-9154-7be2ca0eb38a 14 | spec: 15 | progressDeadlineSeconds: 600 16 | replicas: 1 17 | revisionHistoryLimit: 10 18 | selector: 19 | matchLabels: 20 | app: frontend2 21 | strategy: 22 | rollingUpdate: 23 | maxSurge: 25% 24 | maxUnavailable: 25% 25 | type: RollingUpdate 26 | template: 27 | metadata: 28 | creationTimestamp: null 29 | labels: 30 | app: frontend2 31 | spec: 32 | containers: 33 | - image: nginx 34 | imagePullPolicy: Always 35 | name: nginx 36 | ports: 37 | - containerPort: 80 38 | protocol: TCP 39 | resources: {} 40 | terminationMessagePath: /dev/termination-log 41 | terminationMessagePolicy: File 42 | dnsPolicy: ClusterFirst 43 | restartPolicy: Always 44 | schedulerName: default-scheduler 45 | securityContext: {} 46 | terminationGracePeriodSeconds: 30 47 | status: 48 | availableReplicas: 1 49 | conditions: 50 | - lastTransitionTime: "2023-05-08T05:28:04Z" 51 | lastUpdateTime: "2023-05-08T05:28:04Z" 52 | message: Deployment has minimum availability. 53 | reason: MinimumReplicasAvailable 54 | status: "True" 55 | type: Available 56 | - lastTransitionTime: "2023-05-08T05:27:59Z" 57 | lastUpdateTime: "2023-05-08T05:28:04Z" 58 | message: ReplicaSet "frontend2-5fd5864b" has successfully progressed. 59 | reason: NewReplicaSetAvailable 60 | status: "True" 61 | type: Progressing 62 | observedGeneration: 1 63 | readyReplicas: 1 64 | replicas: 1 65 | updatedReplicas: 1 66 | -------------------------------------------------------------------------------- /ingress/frontend1-dep.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | annotations: 5 | deployment.kubernetes.io/revision: "1" 6 | creationTimestamp: "2023-05-08T05:26:52Z" 7 | generation: 1 8 | labels: 9 | app: frontend1 10 | name: frontend1 11 | namespace: default 12 | resourceVersion: "71949" 13 | uid: 805dfe36-7d3e-4139-aa5a-53213a635203 14 | spec: 15 | progressDeadlineSeconds: 600 16 | replicas: 1 17 | revisionHistoryLimit: 10 18 | selector: 19 | matchLabels: 20 | app: frontend1 21 | strategy: 22 | rollingUpdate: 23 | maxSurge: 25% 24 | maxUnavailable: 25% 25 | type: RollingUpdate 26 | template: 27 | metadata: 28 | creationTimestamp: null 29 | labels: 30 | app: frontend1 31 | spec: 32 | containers: 33 | - image: httpd 34 | imagePullPolicy: Always 35 | name: httpd 36 | ports: 37 | - containerPort: 80 38 | protocol: TCP 39 | resources: {} 40 | terminationMessagePath: /dev/termination-log 41 | terminationMessagePolicy: File 42 | dnsPolicy: ClusterFirst 43 | restartPolicy: Always 44 | schedulerName: default-scheduler 45 | securityContext: {} 46 | terminationGracePeriodSeconds: 30 47 | status: 48 | availableReplicas: 1 49 | conditions: 50 | - lastTransitionTime: "2023-05-08T05:26:59Z" 51 | lastUpdateTime: "2023-05-08T05:26:59Z" 52 | message: Deployment has minimum availability. 53 | reason: MinimumReplicasAvailable 54 | status: "True" 55 | type: Available 56 | - lastTransitionTime: "2023-05-08T05:26:52Z" 57 | lastUpdateTime: "2023-05-08T05:26:59Z" 58 | message: ReplicaSet "frontend1-555c45b8fc" has successfully progressed. 59 | reason: NewReplicaSetAvailable 60 | status: "True" 61 | type: Progressing 62 | observedGeneration: 1 63 | readyReplicas: 1 64 | replicas: 1 65 | updatedReplicas: 1 66 | -------------------------------------------------------------------------------- /terraform_aws_ec2_webapp.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_providers { 3 | aws = { 4 | source = "hashicorp/aws" 5 | version = "~> 3.0" 6 | } 7 | } 8 | } 9 | 10 | # Configure the AWS Provider 11 | provider "aws" { 12 | region = "us-east-1" 13 | } 14 | 15 | data "aws_ami" "amazon_linux2_ami" { 16 | most_recent = true 17 | owners = ["amazon"] 18 | 19 | filter { 20 | name = "image-id" 21 | values = ["ami-04d29b6f966df1537"] 22 | } 23 | } 24 | 25 | 26 | resource "aws_security_group" "allow_webapp_traffic" { 27 | name = "allow_webapp_traffic" 28 | description = "Allow inbound traffic" 29 | 30 | ingress { 31 | from_port = 80 32 | to_port = 80 33 | protocol = "tcp" 34 | cidr_blocks = ["0.0.0.0/0"] 35 | } 36 | 37 | ingress { 38 | from_port = 22 39 | to_port = 22 40 | protocol = "tcp" 41 | cidr_blocks = ["0.0.0.0/0"] 42 | } 43 | 44 | egress { 45 | from_port = 0 46 | to_port = 0 47 | protocol = "-1" 48 | cidr_blocks = ["0.0.0.0/0"] 49 | } 50 | 51 | tags = { 52 | Name = "allow_my_laptop" 53 | } 54 | } 55 | 56 | resource "aws_instance" "webapp" { 57 | ami = data.aws_ami.amazon_linux2_ami.id 58 | instance_type = "t2.micro" 59 | vpc_security_group_ids = [aws_security_group.allow_webapp_traffic.id] 60 | key_name = "temp_key" 61 | 62 | user_data = <<-EOF 63 | #!/bin/bash 64 | sudo yum update -y 65 | sudo yum install httpd -y 66 | sudo service httpd start 67 | sudo chkconfig httpd on 68 | echo "

Your terraform deployment worked !!!

" | sudo tee /var/www/html/index.html 69 | hostname -f >> /var/www/html/index.html 70 | EOF 71 | 72 | tags = { 73 | Name = "myfirsttfinstance" 74 | } 75 | } 76 | 77 | output "instance_ip" { 78 | value = aws_instance.webapp.public_ip 79 | } 80 | -------------------------------------------------------------------------------- /8_functions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Function 3 | 4 | a function is a self-contained block of code that encapsulates a specific task or related group of tasks 5 | ''' 6 | 7 | def my_func(): 8 | print("This is my function.") 9 | 10 | my_func() 11 | 12 | def my_func(): 13 | """ 14 | This is a dummy function. 15 | """ 16 | print("This is my function.") 17 | 18 | ''' 19 | 20 | Why do we need them? 21 | 22 | - Code Reusability 23 | - Chunking 24 | Breaking a large task into smaller, bite-sized sub-tasks helps make the large task easier to think about and manage. 25 | As programs become more complicated, it becomes increasingly beneficial to modularize them in this way. 26 | - ETL 27 | 28 | ''' 29 | 30 | def after_tax(price): 31 | print(price * 1.1) 32 | 33 | def after_tax(price, tax_percent): 34 | print(price * (1 + (tax_percent/100))) 35 | 36 | def after_tax(price, tax_percent=10): 37 | print(price * (1 + (tax_percent/100))) 38 | 39 | def after_tax(price, tax_percent): 40 | return price * (1 + (tax_percent/100)) 41 | 42 | 43 | #When a parameter name in a Python function definition is preceded by an asterisk (*), it indicates argument tuple packing 44 | 45 | *args 46 | 47 | def multiply(*args): 48 | print("Parameters passed in", args) 49 | print("Type of args", type(args)) 50 | num = 1 51 | for x in args: 52 | num = num * x 53 | return num 54 | 55 | **kwargs 56 | 57 | def sample_func(**kwargs): 58 | print("Parameters passed in", kwargs) 59 | print("Type of kwargs", type(kwargs)) 60 | for k, v in kwargs.items(): 61 | print(key, val) 62 | 63 | #Python has a similar operator, the double asterisk (**), which can be used with Python function parameters and arguments to specify dictionary packing and unpacking. 64 | 65 | 66 | def say(msg): 67 | print(msg) 68 | 69 | def saytwice(msg): 70 | print(msg*2) 71 | 72 | def wrapper_func(func): 73 | msg = "Hello." 74 | func(msg) 75 | 76 | wrapper_func(say) 77 | 78 | wrapper_func(saytwice) 79 | 80 | 81 | -------------------------------------------------------------------------------- /16_subprocess.sql: -------------------------------------------------------------------------------- 1 | subprocess.run("echo 'Hello World'", shell=True) 2 | 3 | output = subprocess.run("echo 'Hello World'", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 4 | 5 | print(output) 6 | print(output.stdout) 7 | 8 | output = subprocess.run("echo Hello World", shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 9 | 10 | print(output) 11 | 12 | output = subprocess.run("echo 'Hello World", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 13 | 14 | print(output) 15 | 16 | from subprocess import Popen 17 | 18 | p = Popen(["sleep","5"]) 19 | #p.wait() 20 | 21 | from subprocess import Popen,PIPE 22 | 23 | p1 = Popen(["ls","-1"], stdout=PIPE) 24 | p2 = Popen(["grep", "subprocess"], stdin=p1.stdout, stdout=PIPE, universal_newlines=True) 25 | output = p2.stdout.readline() 26 | print(output) 27 | p1.stdout.close() 28 | 29 | output, error = p2.communicate() 30 | print(output) 31 | 32 | ### 33 | 34 | process = subprocess.Popen(['ping', '-c 4', 'python.org'], 35 | stdout=subprocess.PIPE, 36 | stderr=subprocess.PIPE, 37 | universal_newlines=True) 38 | 39 | while True: 40 | output = process.stdout.readline() 41 | print(output) 42 | 43 | return_code = process.poll() 44 | if return_code is not None: 45 | print('RETURN CODE', return_code) 46 | 47 | for output in process.stdout.readlines(): 48 | print(output) 49 | break 50 | 51 | 52 | proc = subprocess.Popen(['ping', '-c 5', 'google.com'], 53 | stdout=subprocess.PIPE, 54 | stderr=subprocess.STDOUT) 55 | 56 | try: 57 | outs, _ = proc.communicate(timeout=10) 58 | print('RETURN CODE', proc.returncode) 59 | print(outs.decode('utf-8')) 60 | except subprocess.TimeoutExpired: 61 | print('subprocess did not terminate in time') 62 | proc.terminate() 63 | -------------------------------------------------------------------------------- /3_lists.py: -------------------------------------------------------------------------------- 1 | list_name = list() 2 | print(list_name) 3 | 4 | 5 | string_list = ["one", "two", "three"] 6 | print(string_list) 7 | num_list = [1, 2, 3] 8 | print(num_list) 9 | mixed_list = [1, 2, 3, "one", "two", "three", [4, 5, 6], {"key":"value"}] 10 | print(mixed_list) 11 | 12 | 13 | vegetables = ["Potatoes", "Carrots", "Cauliflower", "Broccoli", "Bell Pepper"] 14 | 15 | print(vegetables) 16 | 17 | print(vegetables[0]) 18 | 19 | print(vegetables[3]) 20 | 21 | print(vegetables[-1]) 22 | 23 | #Slicing 24 | 25 | print(vegetables[0:3]) #2nd number is exclusive 26 | 27 | print(vegetables[2:]) #Absence of a number after colon - assumes last position 28 | 29 | print(vegetables[:4]) #Absence of a number before colon - assumes first position (0) 30 | 31 | print(vegetables[-2:]) #Last 2 items 32 | 33 | print(vegetables[::-1]) #Print list in reverse order 34 | 35 | print(vegetables[::1]) 36 | 37 | print(vegetables[::2]) 38 | 39 | vegetables2 = ["Sweet Potatoes", "Green Beans", "Egg plant"] 40 | 41 | #Concatenate 42 | 43 | print(vegetables + vegetables2) 44 | 45 | #useful functions 46 | 47 | print(dir(vegetables)) 48 | 49 | help(vegetables.extend) 50 | 51 | vegetables.append("Cabbage") 52 | print(vegetables) 53 | vegetables.pop() 54 | print(vegetables) 55 | vegetables.remove("Carrots") 56 | print(vegetables) 57 | vegetables.extend(vegetables2) 58 | print(vegetables) 59 | vegetables.insert(0, "Spinach") 60 | print(vegetables) 61 | vegetables.sort() 62 | print(vegetables) 63 | vegetables.sort(reverse=True) 64 | sorted_vegetables = sorted(vegetables) 65 | print(vegetables) 66 | print(sorted_vegetables) 67 | print(vegetables) 68 | print(vegetables.index("Green Beans")) 69 | 70 | vegetables3 = vegetables 71 | print(vegetables3) 72 | vegetables3.remove("Sweet Potatoes") 73 | print(vegetables3) 74 | print(vegetables) 75 | 76 | vegetables3 = vegetables.copy() 77 | print(vegetables3) 78 | vegetables3.remove("Egg plant") 79 | print(vegetables3) 80 | print(vegetables) 81 | print(vegetables.count("Spinach")) 82 | vegetables.append("Spinach") 83 | print(vegetables) 84 | print(vegetables.count("Spinach")) 85 | 86 | print(len(vegetables)) 87 | 88 | numbers = [10,20,30,40,50] 89 | print(min(numbers)) 90 | print(max(numbers)) 91 | 92 | print(10 in numbers) 93 | print(11 not in numbers) 94 | 95 | vegetables3.clear() 96 | print(vegetables3) 97 | -------------------------------------------------------------------------------- /go/channel/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // Example 0 6 | func dummy_func() { 7 | fmt.Println("dummy_func") 8 | } 9 | func main() { 10 | go dummy_func() 11 | fmt.Println("end of main") 12 | } 13 | 14 | 15 | // Example 1 16 | 17 | package main 18 | 19 | import "fmt" 20 | 21 | func dummy_func(ch chan int) { 22 | // receive a value from channel 23 | val := <-ch 24 | fmt.Println(val) 25 | } 26 | func main() { 27 | // create a channel 28 | ch := make(chan int) 29 | // trigger a parallel go routine 30 | go dummy_func(ch) 31 | // send a value into the channel 32 | ch <- 10 33 | } 34 | 35 | // Example 2 36 | 37 | package main 38 | 39 | import ( 40 | "fmt" 41 | //"flag" 42 | ) 43 | 44 | func dummy_func(ch chan int) { 45 | // receive a value from channel 46 | val := <-ch 47 | fmt.Println(val) 48 | 49 | //send a value again 50 | ch <- val*2 51 | } 52 | func main() { 53 | fmt.Println("Welcome to main function") 54 | 55 | //flag statements for user input 56 | var input_value int 57 | input_value = 10 58 | //flag.IntVar(&input_value, "v", 10, "Input value to send/receive via channel." ) 59 | //flag.Parse() 60 | 61 | // create a channel 62 | ch := make(chan int) 63 | 64 | // trigger a parallel go routine 65 | go dummy_func(ch) 66 | 67 | // send a value into the channel 68 | ch <- input_value 69 | 70 | // receive a value from channel 71 | response := <- ch 72 | fmt.Println(response) 73 | 74 | } 75 | 76 | // example 3 77 | 78 | 79 | package main 80 | 81 | import( 82 | "fmt" 83 | "time" 84 | "math/rand" 85 | ) 86 | 87 | func routine1(ch chan int, min int, max int) { 88 | 89 | rand.Seed(time.Now().UnixNano()) 90 | t := rand.Intn(max - min) + min 91 | fmt.Println("routine 1 is waiting: ", t, "secs") 92 | time.Sleep(time.Duration(t)*time.Second) 93 | 94 | ch <- t 95 | } 96 | 97 | func routine2(ch chan int, min int, max int) { 98 | 99 | rand.Seed(time.Now().UnixNano()) 100 | t := rand.Intn(max - min) + min 101 | fmt.Println("routine 2 is waiting: ", t, "secs") 102 | time.Sleep(time.Duration(t)*time.Second) 103 | 104 | ch <- t 105 | } 106 | 107 | func main(){ 108 | 109 | min := 1 110 | max := 10 111 | 112 | ch1:= make(chan int) 113 | ch2:= make(chan int) 114 | 115 | go routine1(ch1, min, max) 116 | go routine2(ch2, min, max) 117 | 118 | select{ 119 | 120 | case <- ch1: 121 | fmt.Println("routine 1 finished") 122 | 123 | case <- ch2: 124 | fmt.Println("routine 2 finished") 125 | } 126 | 127 | fmt.Println("end of main function") 128 | 129 | } 130 | -------------------------------------------------------------------------------- /kubernetes/serviceaccount.txt: -------------------------------------------------------------------------------- 1 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl delete pod test-pod; kubectl delete -f saRoleBinding.yaml; kubectl delete -f Role.yaml; kubectl delete sa newsa 2 | 3 | 4 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl get sa 5 | NAME SECRETS AGE 6 | default 1 190d 7 | mysa 1 3d16h 8 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl get secret 9 | NAME TYPE DATA AGE 10 | default-token-rspfg kubernetes.io/service-account-token 3 190d 11 | mysa-token-m2vvp kubernetes.io/service-account-token 3 3d16h 12 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl create sa newsa 13 | serviceaccount/newsa created 14 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl get secret 15 | NAME TYPE DATA AGE 16 | newsa-token-npxgk kubernetes.io/service-account-token 3 27s 17 | 18 | root@ip-172-31-30-83:/home/ubuntu/sa# cat pod-sa.yaml 19 | apiVersion: v1 20 | kind: Pod 21 | metadata: 22 | labels: 23 | run: test-pod 24 | name: test-pod 25 | spec: 26 | serviceAccount: newsa 27 | containers: 28 | - image: nginx 29 | name: test-pod 30 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl apply -f pod-sa.yaml 31 | pod/test-pod created 32 | 33 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl describe pod test-pod 34 | 35 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl get service 36 | NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE 37 | kubernetes ClusterIP 10.96.0.1 443/TCP 182d 38 | 39 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl exec -it test-pod -- bash 40 | root@test-pod:/# ls -l /var/run/secrets/kubernetes.io/serviceaccount 41 | total 0 42 | lrwxrwxrwx 1 root root 13 Mar 19 22:28 ca.crt -> ..data/ca.crt 43 | lrwxrwxrwx 1 root root 16 Mar 19 22:28 namespace -> ..data/namespace 44 | lrwxrwxrwx 1 root root 12 Mar 19 22:28 token -> ..data/token 45 | 46 | root@test-pod:/# TOKEN=`cat /var/run/secrets/kubernetes.io/serviceaccount/token` 47 | root@test-pod:/# curl https://kubernetes -k --header "Authorization: Bearer $TOKEN" 48 | { 49 | "kind": "Status", 50 | "apiVersion": "v1", 51 | "metadata": { 52 | 53 | }, 54 | "status": "Failure", 55 | "message": "forbidden: User \"system:serviceaccount:default:newsa\" cannot get path \"/\"", 56 | "reason": "Forbidden", 57 | "details": { 58 | 59 | }, 60 | "code": 403 61 | } 62 | 63 | root@ip-172-31-30-83:/home/ubuntu/sa# cat Role.yaml 64 | apiVersion: rbac.authorization.k8s.io/v1 65 | kind: Role 66 | metadata: 67 | namespace: default 68 | name: pod-read-only 69 | rules: 70 | - apiGroups: [""] 71 | resources: ["pods"] 72 | verbs: ["get", "watch", "list"] 73 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl get role 74 | NAME CREATED AT 75 | pod-ro 2021-12-03T00:09:39Z 76 | 77 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl apply -f Role.yaml 78 | role.rbac.authorization.k8s.io/pod-read-only created 79 | 80 | root@ip-172-31-30-83:/home/ubuntu/sa# kubectl apply -f saRoleBinding.yaml 81 | rolebinding.rbac.authorization.k8s.io/bind-pod-read-only created 82 | 83 | kubectl exec -it test-pod -- bash 84 | 85 | echo "deb http://us.archive.ubuntu.com/ubuntu vivid main universe" >> /etc/apt/sources.list 86 | apt-get update 87 | apt-get install jq 88 | 89 | root@test-pod:/# curl https://kubernetes/api/v1/namespaces/default/pods -k --header "Authorization: Bearer $TOKEN" | jq '.items[].metadata.name' 90 | 91 | "some-deployment-6dfcc5b79f-cvjtc" 92 | "some-deployment-6dfcc5b79f-hvbqp" 93 | "test-pod" 94 | -------------------------------------------------------------------------------- /ingress/application.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | annotations: 5 | deployment.kubernetes.io/revision: "1" 6 | creationTimestamp: "2023-05-08T05:26:52Z" 7 | generation: 1 8 | labels: 9 | app: frontend1 10 | name: frontend1 11 | namespace: default 12 | resourceVersion: "71949" 13 | uid: 805dfe36-7d3e-4139-aa5a-53213a635203 14 | spec: 15 | progressDeadlineSeconds: 600 16 | replicas: 1 17 | revisionHistoryLimit: 10 18 | selector: 19 | matchLabels: 20 | app: frontend1 21 | strategy: 22 | rollingUpdate: 23 | maxSurge: 25% 24 | maxUnavailable: 25% 25 | type: RollingUpdate 26 | template: 27 | metadata: 28 | creationTimestamp: null 29 | labels: 30 | app: frontend1 31 | spec: 32 | containers: 33 | - image: httpd 34 | imagePullPolicy: Always 35 | name: httpd 36 | ports: 37 | - containerPort: 80 38 | protocol: TCP 39 | resources: {} 40 | terminationMessagePath: /dev/termination-log 41 | terminationMessagePolicy: File 42 | dnsPolicy: ClusterFirst 43 | restartPolicy: Always 44 | schedulerName: default-scheduler 45 | securityContext: {} 46 | terminationGracePeriodSeconds: 30 47 | status: 48 | availableReplicas: 1 49 | conditions: 50 | - lastTransitionTime: "2023-05-08T05:26:59Z" 51 | lastUpdateTime: "2023-05-08T05:26:59Z" 52 | message: Deployment has minimum availability. 53 | reason: MinimumReplicasAvailable 54 | status: "True" 55 | type: Available 56 | - lastTransitionTime: "2023-05-08T05:26:52Z" 57 | lastUpdateTime: "2023-05-08T05:26:59Z" 58 | message: ReplicaSet "frontend1-555c45b8fc" has successfully progressed. 59 | reason: NewReplicaSetAvailable 60 | status: "True" 61 | type: Progressing 62 | observedGeneration: 1 63 | readyReplicas: 1 64 | replicas: 1 65 | updatedReplicas: 1 66 | --- 67 | apiVersion: apps/v1 68 | kind: Deployment 69 | metadata: 70 | annotations: 71 | deployment.kubernetes.io/revision: "1" 72 | creationTimestamp: "2023-05-08T05:27:59Z" 73 | generation: 1 74 | labels: 75 | app: frontend2 76 | name: frontend2 77 | namespace: default 78 | resourceVersion: "72126" 79 | uid: f3d249ad-4baa-41c1-9154-7be2ca0eb38a 80 | spec: 81 | progressDeadlineSeconds: 600 82 | replicas: 1 83 | revisionHistoryLimit: 10 84 | selector: 85 | matchLabels: 86 | app: frontend2 87 | strategy: 88 | rollingUpdate: 89 | maxSurge: 25% 90 | maxUnavailable: 25% 91 | type: RollingUpdate 92 | template: 93 | metadata: 94 | creationTimestamp: null 95 | labels: 96 | app: frontend2 97 | spec: 98 | containers: 99 | - image: nginx 100 | imagePullPolicy: Always 101 | name: nginx 102 | ports: 103 | - containerPort: 80 104 | protocol: TCP 105 | resources: {} 106 | terminationMessagePath: /dev/termination-log 107 | terminationMessagePolicy: File 108 | dnsPolicy: ClusterFirst 109 | restartPolicy: Always 110 | schedulerName: default-scheduler 111 | securityContext: {} 112 | terminationGracePeriodSeconds: 30 113 | status: 114 | availableReplicas: 1 115 | conditions: 116 | - lastTransitionTime: "2023-05-08T05:28:04Z" 117 | lastUpdateTime: "2023-05-08T05:28:04Z" 118 | message: Deployment has minimum availability. 119 | reason: MinimumReplicasAvailable 120 | status: "True" 121 | type: Available 122 | - lastTransitionTime: "2023-05-08T05:27:59Z" 123 | lastUpdateTime: "2023-05-08T05:28:04Z" 124 | message: ReplicaSet "frontend2-5fd5864b" has successfully progressed. 125 | reason: NewReplicaSetAvailable 126 | status: "True" 127 | type: Progressing 128 | observedGeneration: 1 129 | readyReplicas: 1 130 | replicas: 1 131 | updatedReplicas: 1 132 | --- 133 | apiVersion: v1 134 | kind: Service 135 | metadata: 136 | creationTimestamp: "2023-05-08T05:27:42Z" 137 | labels: 138 | app: frontend1 139 | name: frontend1service 140 | namespace: default 141 | resourceVersion: "72053" 142 | uid: 87a6fd6c-3896-4a66-8db0-5ea70fbb8953 143 | spec: 144 | clusterIP: 10.100.57.211 145 | clusterIPs: 146 | - 10.100.57.211 147 | internalTrafficPolicy: Cluster 148 | ipFamilies: 149 | - IPv4 150 | ipFamilyPolicy: SingleStack 151 | ports: 152 | - port: 80 153 | protocol: TCP 154 | targetPort: 80 155 | selector: 156 | app: frontend1 157 | sessionAffinity: None 158 | type: ClusterIP 159 | status: 160 | loadBalancer: {} 161 | --- 162 | apiVersion: v1 163 | kind: Service 164 | metadata: 165 | creationTimestamp: "2023-05-08T05:28:20Z" 166 | labels: 167 | app: frontend2 168 | name: frontend2service 169 | namespace: default 170 | resourceVersion: "72164" 171 | uid: 693b1ac7-42a2-4bed-ab64-81e5120717fe 172 | spec: 173 | clusterIP: 10.100.10.82 174 | clusterIPs: 175 | - 10.100.10.82 176 | internalTrafficPolicy: Cluster 177 | ipFamilies: 178 | - IPv4 179 | ipFamilyPolicy: SingleStack 180 | ports: 181 | - port: 80 182 | protocol: TCP 183 | targetPort: 80 184 | selector: 185 | app: frontend2 186 | sessionAffinity: None 187 | type: ClusterIP 188 | status: 189 | loadBalancer: {} 190 | -------------------------------------------------------------------------------- /functions_and_decorators.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Function 3 | 4 | a function is a self-contained block of code that encapsulates a specific task or related group of tasks 5 | ''' 6 | 7 | def my_func(): 8 | print("This is my function.") 9 | 10 | my_func() 11 | 12 | def my_func(): 13 | """ 14 | This is a dummy function. 15 | """ 16 | print("This is my function.") 17 | 18 | ''' 19 | 20 | Why do we need them? 21 | 22 | - Code Reusability 23 | - Chunking 24 | Breaking a large task into smaller, bite-sized sub-tasks helps make the large task easier to think about and manage. 25 | As programs become more complicated, it becomes increasingly beneficial to modularize them in this way. 26 | - ETL 27 | 28 | ''' 29 | 30 | def after_tax(price): 31 | print(price * 1.1) 32 | 33 | def after_tax(price, tax_percent): 34 | print(price * (1 + (tax_percent/100))) 35 | 36 | def after_tax(price, tax_percent=10): 37 | print(price * (1 + (tax_percent/100))) 38 | 39 | def after_tax(price, tax_percent): 40 | return price * (1 + (tax_percent/100)) 41 | 42 | 43 | #When a parameter name in a Python function definition is preceded by an asterisk (*), it indicates argument tuple packing 44 | 45 | *args 46 | 47 | def multiply(*args): 48 | print("Parameters passed in", args) 49 | print("Type of args", type(args)) 50 | num = 1 51 | for x in args: 52 | num = num * x 53 | return num 54 | 55 | **kwargs 56 | 57 | def sample_func(**kwargs): 58 | print("Parameters passed in", kwargs) 59 | print("Type of kwargs", type(kwargs)) 60 | for k, v in kwargs.items(): 61 | print(key, val) 62 | 63 | #Python has a similar operator, the double asterisk (**), which can be used with Python function parameters and arguments to specify dictionary packing and unpacking. 64 | 65 | 66 | def say(msg): 67 | print(msg) 68 | 69 | def saytwice(msg): 70 | print(msg*2) 71 | 72 | def wrapper_func(func): 73 | msg = "Hello." 74 | func(msg) 75 | 76 | wrapper_func(say) 77 | 78 | wrapper_func(saytwice) 79 | 80 | 81 | import logging 82 | logging.basicConfig(filename='multiply.log', level=logging.INFO) 83 | 84 | 85 | def logger(func): 86 | def log_func(*args): 87 | logging.info( 88 | 'Running with arguments {}'.format(args)) 89 | func(*args) 90 | return log_func 91 | 92 | 93 | def multiply(*args): 94 | num = 1 95 | for x in args: 96 | num = num * x 97 | print(num) 98 | 99 | 100 | multiply_logger = logger(multiply) 101 | 102 | multiply_logger(2,3,4) 103 | multiply_logger(1,2,3) 104 | 105 | 106 | #1 Normal function call 107 | 108 | def outer_func(): 109 | message = "Hi" 110 | 111 | def inner_func(): 112 | print(message) 113 | 114 | return inner_func() 115 | 116 | outer_func() 117 | 118 | #2 First class function 119 | 120 | def outer_func(): 121 | message = "Hi" 122 | 123 | def inner_func(): 124 | print(message) 125 | 126 | return inner_func 127 | 128 | my_func = outer_func() 129 | my_func() 130 | 131 | #3 Closure / Free variable 132 | 133 | def outer_func(msg): 134 | 135 | def inner_func(): 136 | print(msg) 137 | 138 | return inner_func 139 | 140 | hi_func = outer_func("Hi") 141 | hi_func() 142 | 143 | #4 With arguments 144 | 145 | def double(): 146 | 147 | def inner_func(num): 148 | print(num*2) 149 | 150 | return inner_func 151 | 152 | twox = double() 153 | twox(2) 154 | 155 | #4.1 passing function as arguments 156 | 157 | def say(msg): 158 | print(msg) 159 | 160 | def saytwice(msg): 161 | print(msg*2) 162 | 163 | def outer_func(func): 164 | 165 | def inner_func(msg): 166 | func(msg) 167 | 168 | return inner_func 169 | 170 | hi_func1 = outer_func(say) 171 | hi_func1("Hi") 172 | 173 | hi_func2 = outer_func(saytwice) 174 | hi_func2("Hi") 175 | 176 | for f in (say, saytwice): 177 | of = outer_func(f) 178 | of("Hi") 179 | 180 | #5 *arguments 181 | 182 | def multiply(): 183 | 184 | def inner_func(*args): 185 | num = 1 186 | for x in args: 187 | num = num * x 188 | print(num) 189 | 190 | return inner_func 191 | 192 | calc = multiply() 193 | calc(2,3,4) 194 | calc(1,2,3) 195 | 196 | 197 | def decorator_function(original_function): 198 | def wrapper(): 199 | print(f"Wrapper ran before {original_function.__name__}") 200 | original_function() 201 | return wrapper 202 | 203 | def display(): 204 | print("Display function ran.") 205 | 206 | display = decorator_function(display) 207 | 208 | display() 209 | 210 | #8 211 | 212 | def decorator_function(original_function): 213 | def wrapper(): 214 | print(f"Wrapper ran before {original_function.__name__}") 215 | original_function() 216 | return wrapper 217 | 218 | @decorator_function 219 | def display(): 220 | print("Display function ran.") 221 | 222 | display() 223 | 224 | @decorator_function 225 | def display2(): 226 | print("Display2 function ran.") 227 | 228 | display2() 229 | 230 | #9 231 | 232 | class decorator_class(object): 233 | 234 | def __init__(self, original_function): 235 | self.original_function = original_function 236 | 237 | def __call__(self): 238 | print('call method before {}'.format(self.original_function.__name__)) 239 | self.original_function() 240 | 241 | @decorator_class 242 | def display3(): 243 | print("Display3 function ran.") 244 | 245 | display3() 246 | 247 | #10 248 | 249 | # Practical Examples 250 | 251 | from functools import wraps 252 | 253 | def my_logger(orig_func): 254 | import logging 255 | logging.basicConfig(filename='{}.log'.format(orig_func.__name__), level=logging.INFO) 256 | 257 | @wraps(orig_func) 258 | def wrapper(*args, **kwargs): 259 | logging.info( 260 | 'Ran with args: {}, and kwargs: {}'.format(args, kwargs)) 261 | return orig_func(*args, **kwargs) 262 | 263 | return wrapper 264 | 265 | def my_timer(orig_func): 266 | import time 267 | 268 | @wraps(orig_func) 269 | def wrapper(*args, **kwargs): 270 | t1 = time.time() 271 | result = orig_func(*args, **kwargs) 272 | t2 = time.time() - t1 273 | print('{} ran in: {} sec'.format(orig_func.__name__, t2)) 274 | return result 275 | 276 | return wrapper 277 | 278 | @my_logger 279 | @my_timer 280 | def display2(caller): 281 | import time 282 | time.sleep(1) 283 | print(f"Display function ran by {caller}.") 284 | 285 | display2("Bharath") 286 | -------------------------------------------------------------------------------- /ingress/aws-deploy.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | labels: 5 | app.kubernetes.io/instance: ingress-nginx 6 | app.kubernetes.io/name: ingress-nginx 7 | name: ingress-nginx 8 | --- 9 | apiVersion: v1 10 | automountServiceAccountToken: true 11 | kind: ServiceAccount 12 | metadata: 13 | labels: 14 | app.kubernetes.io/component: controller 15 | app.kubernetes.io/instance: ingress-nginx 16 | app.kubernetes.io/name: ingress-nginx 17 | app.kubernetes.io/part-of: ingress-nginx 18 | app.kubernetes.io/version: 1.7.1 19 | name: ingress-nginx 20 | namespace: ingress-nginx 21 | --- 22 | apiVersion: v1 23 | kind: ServiceAccount 24 | metadata: 25 | labels: 26 | app.kubernetes.io/component: admission-webhook 27 | app.kubernetes.io/instance: ingress-nginx 28 | app.kubernetes.io/name: ingress-nginx 29 | app.kubernetes.io/part-of: ingress-nginx 30 | app.kubernetes.io/version: 1.7.1 31 | name: ingress-nginx-admission 32 | namespace: ingress-nginx 33 | --- 34 | apiVersion: rbac.authorization.k8s.io/v1 35 | kind: Role 36 | metadata: 37 | labels: 38 | app.kubernetes.io/component: controller 39 | app.kubernetes.io/instance: ingress-nginx 40 | app.kubernetes.io/name: ingress-nginx 41 | app.kubernetes.io/part-of: ingress-nginx 42 | app.kubernetes.io/version: 1.7.1 43 | name: ingress-nginx 44 | namespace: ingress-nginx 45 | rules: 46 | - apiGroups: 47 | - "" 48 | resources: 49 | - namespaces 50 | verbs: 51 | - get 52 | - apiGroups: 53 | - "" 54 | resources: 55 | - configmaps 56 | - pods 57 | - secrets 58 | - endpoints 59 | verbs: 60 | - get 61 | - list 62 | - watch 63 | - apiGroups: 64 | - "" 65 | resources: 66 | - services 67 | verbs: 68 | - get 69 | - list 70 | - watch 71 | - apiGroups: 72 | - networking.k8s.io 73 | resources: 74 | - ingresses 75 | verbs: 76 | - get 77 | - list 78 | - watch 79 | - apiGroups: 80 | - networking.k8s.io 81 | resources: 82 | - ingresses/status 83 | verbs: 84 | - update 85 | - apiGroups: 86 | - networking.k8s.io 87 | resources: 88 | - ingressclasses 89 | verbs: 90 | - get 91 | - list 92 | - watch 93 | - apiGroups: 94 | - coordination.k8s.io 95 | resourceNames: 96 | - ingress-nginx-leader 97 | resources: 98 | - leases 99 | verbs: 100 | - get 101 | - update 102 | - apiGroups: 103 | - coordination.k8s.io 104 | resources: 105 | - leases 106 | verbs: 107 | - create 108 | - apiGroups: 109 | - "" 110 | resources: 111 | - events 112 | verbs: 113 | - create 114 | - patch 115 | - apiGroups: 116 | - discovery.k8s.io 117 | resources: 118 | - endpointslices 119 | verbs: 120 | - list 121 | - watch 122 | - get 123 | --- 124 | apiVersion: rbac.authorization.k8s.io/v1 125 | kind: Role 126 | metadata: 127 | labels: 128 | app.kubernetes.io/component: admission-webhook 129 | app.kubernetes.io/instance: ingress-nginx 130 | app.kubernetes.io/name: ingress-nginx 131 | app.kubernetes.io/part-of: ingress-nginx 132 | app.kubernetes.io/version: 1.7.1 133 | name: ingress-nginx-admission 134 | namespace: ingress-nginx 135 | rules: 136 | - apiGroups: 137 | - "" 138 | resources: 139 | - secrets 140 | verbs: 141 | - get 142 | - create 143 | --- 144 | apiVersion: rbac.authorization.k8s.io/v1 145 | kind: ClusterRole 146 | metadata: 147 | labels: 148 | app.kubernetes.io/instance: ingress-nginx 149 | app.kubernetes.io/name: ingress-nginx 150 | app.kubernetes.io/part-of: ingress-nginx 151 | app.kubernetes.io/version: 1.7.1 152 | name: ingress-nginx 153 | rules: 154 | - apiGroups: 155 | - "" 156 | resources: 157 | - configmaps 158 | - endpoints 159 | - nodes 160 | - pods 161 | - secrets 162 | - namespaces 163 | verbs: 164 | - list 165 | - watch 166 | - apiGroups: 167 | - coordination.k8s.io 168 | resources: 169 | - leases 170 | verbs: 171 | - list 172 | - watch 173 | - apiGroups: 174 | - "" 175 | resources: 176 | - nodes 177 | verbs: 178 | - get 179 | - apiGroups: 180 | - "" 181 | resources: 182 | - services 183 | verbs: 184 | - get 185 | - list 186 | - watch 187 | - apiGroups: 188 | - networking.k8s.io 189 | resources: 190 | - ingresses 191 | verbs: 192 | - get 193 | - list 194 | - watch 195 | - apiGroups: 196 | - "" 197 | resources: 198 | - events 199 | verbs: 200 | - create 201 | - patch 202 | - apiGroups: 203 | - networking.k8s.io 204 | resources: 205 | - ingresses/status 206 | verbs: 207 | - update 208 | - apiGroups: 209 | - networking.k8s.io 210 | resources: 211 | - ingressclasses 212 | verbs: 213 | - get 214 | - list 215 | - watch 216 | - apiGroups: 217 | - discovery.k8s.io 218 | resources: 219 | - endpointslices 220 | verbs: 221 | - list 222 | - watch 223 | - get 224 | --- 225 | apiVersion: rbac.authorization.k8s.io/v1 226 | kind: ClusterRole 227 | metadata: 228 | labels: 229 | app.kubernetes.io/component: admission-webhook 230 | app.kubernetes.io/instance: ingress-nginx 231 | app.kubernetes.io/name: ingress-nginx 232 | app.kubernetes.io/part-of: ingress-nginx 233 | app.kubernetes.io/version: 1.7.1 234 | name: ingress-nginx-admission 235 | rules: 236 | - apiGroups: 237 | - admissionregistration.k8s.io 238 | resources: 239 | - validatingwebhookconfigurations 240 | verbs: 241 | - get 242 | - update 243 | --- 244 | apiVersion: rbac.authorization.k8s.io/v1 245 | kind: RoleBinding 246 | metadata: 247 | labels: 248 | app.kubernetes.io/component: controller 249 | app.kubernetes.io/instance: ingress-nginx 250 | app.kubernetes.io/name: ingress-nginx 251 | app.kubernetes.io/part-of: ingress-nginx 252 | app.kubernetes.io/version: 1.7.1 253 | name: ingress-nginx 254 | namespace: ingress-nginx 255 | roleRef: 256 | apiGroup: rbac.authorization.k8s.io 257 | kind: Role 258 | name: ingress-nginx 259 | subjects: 260 | - kind: ServiceAccount 261 | name: ingress-nginx 262 | namespace: ingress-nginx 263 | --- 264 | apiVersion: rbac.authorization.k8s.io/v1 265 | kind: RoleBinding 266 | metadata: 267 | labels: 268 | app.kubernetes.io/component: admission-webhook 269 | app.kubernetes.io/instance: ingress-nginx 270 | app.kubernetes.io/name: ingress-nginx 271 | app.kubernetes.io/part-of: ingress-nginx 272 | app.kubernetes.io/version: 1.7.1 273 | name: ingress-nginx-admission 274 | namespace: ingress-nginx 275 | roleRef: 276 | apiGroup: rbac.authorization.k8s.io 277 | kind: Role 278 | name: ingress-nginx-admission 279 | subjects: 280 | - kind: ServiceAccount 281 | name: ingress-nginx-admission 282 | namespace: ingress-nginx 283 | --- 284 | apiVersion: rbac.authorization.k8s.io/v1 285 | kind: ClusterRoleBinding 286 | metadata: 287 | labels: 288 | app.kubernetes.io/instance: ingress-nginx 289 | app.kubernetes.io/name: ingress-nginx 290 | app.kubernetes.io/part-of: ingress-nginx 291 | app.kubernetes.io/version: 1.7.1 292 | name: ingress-nginx 293 | roleRef: 294 | apiGroup: rbac.authorization.k8s.io 295 | kind: ClusterRole 296 | name: ingress-nginx 297 | subjects: 298 | - kind: ServiceAccount 299 | name: ingress-nginx 300 | namespace: ingress-nginx 301 | --- 302 | apiVersion: rbac.authorization.k8s.io/v1 303 | kind: ClusterRoleBinding 304 | metadata: 305 | labels: 306 | app.kubernetes.io/component: admission-webhook 307 | app.kubernetes.io/instance: ingress-nginx 308 | app.kubernetes.io/name: ingress-nginx 309 | app.kubernetes.io/part-of: ingress-nginx 310 | app.kubernetes.io/version: 1.7.1 311 | name: ingress-nginx-admission 312 | roleRef: 313 | apiGroup: rbac.authorization.k8s.io 314 | kind: ClusterRole 315 | name: ingress-nginx-admission 316 | subjects: 317 | - kind: ServiceAccount 318 | name: ingress-nginx-admission 319 | namespace: ingress-nginx 320 | --- 321 | apiVersion: v1 322 | data: 323 | allow-snippet-annotations: "true" 324 | kind: ConfigMap 325 | metadata: 326 | labels: 327 | app.kubernetes.io/component: controller 328 | app.kubernetes.io/instance: ingress-nginx 329 | app.kubernetes.io/name: ingress-nginx 330 | app.kubernetes.io/part-of: ingress-nginx 331 | app.kubernetes.io/version: 1.7.1 332 | name: ingress-nginx-controller 333 | namespace: ingress-nginx 334 | --- 335 | apiVersion: v1 336 | kind: Service 337 | metadata: 338 | annotations: 339 | service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp 340 | service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: "true" 341 | service.beta.kubernetes.io/aws-load-balancer-type: nlb 342 | labels: 343 | app.kubernetes.io/component: controller 344 | app.kubernetes.io/instance: ingress-nginx 345 | app.kubernetes.io/name: ingress-nginx 346 | app.kubernetes.io/part-of: ingress-nginx 347 | app.kubernetes.io/version: 1.7.1 348 | name: ingress-nginx-controller 349 | namespace: ingress-nginx 350 | spec: 351 | externalTrafficPolicy: Local 352 | ipFamilies: 353 | - IPv4 354 | ipFamilyPolicy: SingleStack 355 | ports: 356 | - appProtocol: http 357 | name: http 358 | port: 80 359 | protocol: TCP 360 | targetPort: http 361 | - appProtocol: https 362 | name: https 363 | port: 443 364 | protocol: TCP 365 | targetPort: https 366 | selector: 367 | app.kubernetes.io/component: controller 368 | app.kubernetes.io/instance: ingress-nginx 369 | app.kubernetes.io/name: ingress-nginx 370 | type: LoadBalancer 371 | --- 372 | apiVersion: v1 373 | kind: Service 374 | metadata: 375 | labels: 376 | app.kubernetes.io/component: controller 377 | app.kubernetes.io/instance: ingress-nginx 378 | app.kubernetes.io/name: ingress-nginx 379 | app.kubernetes.io/part-of: ingress-nginx 380 | app.kubernetes.io/version: 1.7.1 381 | name: ingress-nginx-controller-admission 382 | namespace: ingress-nginx 383 | spec: 384 | ports: 385 | - appProtocol: https 386 | name: https-webhook 387 | port: 443 388 | targetPort: webhook 389 | selector: 390 | app.kubernetes.io/component: controller 391 | app.kubernetes.io/instance: ingress-nginx 392 | app.kubernetes.io/name: ingress-nginx 393 | type: ClusterIP 394 | --- 395 | apiVersion: apps/v1 396 | kind: Deployment 397 | metadata: 398 | labels: 399 | app.kubernetes.io/component: controller 400 | app.kubernetes.io/instance: ingress-nginx 401 | app.kubernetes.io/name: ingress-nginx 402 | app.kubernetes.io/part-of: ingress-nginx 403 | app.kubernetes.io/version: 1.7.1 404 | name: ingress-nginx-controller 405 | namespace: ingress-nginx 406 | spec: 407 | minReadySeconds: 0 408 | revisionHistoryLimit: 10 409 | selector: 410 | matchLabels: 411 | app.kubernetes.io/component: controller 412 | app.kubernetes.io/instance: ingress-nginx 413 | app.kubernetes.io/name: ingress-nginx 414 | template: 415 | metadata: 416 | labels: 417 | app.kubernetes.io/component: controller 418 | app.kubernetes.io/instance: ingress-nginx 419 | app.kubernetes.io/name: ingress-nginx 420 | app.kubernetes.io/part-of: ingress-nginx 421 | app.kubernetes.io/version: 1.7.1 422 | spec: 423 | containers: 424 | - args: 425 | - /nginx-ingress-controller 426 | - --publish-service=$(POD_NAMESPACE)/ingress-nginx-controller 427 | - --election-id=ingress-nginx-leader 428 | - --controller-class=k8s.io/ingress-nginx 429 | - --ingress-class=nginx 430 | - --configmap=$(POD_NAMESPACE)/ingress-nginx-controller 431 | - --validating-webhook=:8443 432 | - --validating-webhook-certificate=/usr/local/certificates/cert 433 | - --validating-webhook-key=/usr/local/certificates/key 434 | env: 435 | - name: POD_NAME 436 | valueFrom: 437 | fieldRef: 438 | fieldPath: metadata.name 439 | - name: POD_NAMESPACE 440 | valueFrom: 441 | fieldRef: 442 | fieldPath: metadata.namespace 443 | - name: LD_PRELOAD 444 | value: /usr/local/lib/libmimalloc.so 445 | image: registry.k8s.io/ingress-nginx/controller:v1.7.1@sha256:7244b95ea47bddcb8267c1e625fb163fc183ef55448855e3ac52a7b260a60407 446 | imagePullPolicy: IfNotPresent 447 | lifecycle: 448 | preStop: 449 | exec: 450 | command: 451 | - /wait-shutdown 452 | livenessProbe: 453 | failureThreshold: 5 454 | httpGet: 455 | path: /healthz 456 | port: 10254 457 | scheme: HTTP 458 | initialDelaySeconds: 10 459 | periodSeconds: 10 460 | successThreshold: 1 461 | timeoutSeconds: 1 462 | name: controller 463 | ports: 464 | - containerPort: 80 465 | name: http 466 | protocol: TCP 467 | - containerPort: 443 468 | name: https 469 | protocol: TCP 470 | - containerPort: 8443 471 | name: webhook 472 | protocol: TCP 473 | readinessProbe: 474 | failureThreshold: 3 475 | httpGet: 476 | path: /healthz 477 | port: 10254 478 | scheme: HTTP 479 | initialDelaySeconds: 10 480 | periodSeconds: 10 481 | successThreshold: 1 482 | timeoutSeconds: 1 483 | resources: 484 | requests: 485 | cpu: 100m 486 | memory: 90Mi 487 | securityContext: 488 | allowPrivilegeEscalation: true 489 | capabilities: 490 | add: 491 | - NET_BIND_SERVICE 492 | drop: 493 | - ALL 494 | runAsUser: 101 495 | volumeMounts: 496 | - mountPath: /usr/local/certificates/ 497 | name: webhook-cert 498 | readOnly: true 499 | dnsPolicy: ClusterFirst 500 | nodeSelector: 501 | kubernetes.io/os: linux 502 | serviceAccountName: ingress-nginx 503 | terminationGracePeriodSeconds: 300 504 | volumes: 505 | - name: webhook-cert 506 | secret: 507 | secretName: ingress-nginx-admission 508 | --- 509 | apiVersion: batch/v1 510 | kind: Job 511 | metadata: 512 | labels: 513 | app.kubernetes.io/component: admission-webhook 514 | app.kubernetes.io/instance: ingress-nginx 515 | app.kubernetes.io/name: ingress-nginx 516 | app.kubernetes.io/part-of: ingress-nginx 517 | app.kubernetes.io/version: 1.7.1 518 | name: ingress-nginx-admission-create 519 | namespace: ingress-nginx 520 | spec: 521 | template: 522 | metadata: 523 | labels: 524 | app.kubernetes.io/component: admission-webhook 525 | app.kubernetes.io/instance: ingress-nginx 526 | app.kubernetes.io/name: ingress-nginx 527 | app.kubernetes.io/part-of: ingress-nginx 528 | app.kubernetes.io/version: 1.7.1 529 | name: ingress-nginx-admission-create 530 | spec: 531 | containers: 532 | - args: 533 | - create 534 | - --host=ingress-nginx-controller-admission,ingress-nginx-controller-admission.$(POD_NAMESPACE).svc 535 | - --namespace=$(POD_NAMESPACE) 536 | - --secret-name=ingress-nginx-admission 537 | env: 538 | - name: POD_NAMESPACE 539 | valueFrom: 540 | fieldRef: 541 | fieldPath: metadata.namespace 542 | image: registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20230312-helm-chart-4.5.2-28-g66a760794@sha256:01d181618f270f2a96c04006f33b2699ad3ccb02da48d0f89b22abce084b292f 543 | imagePullPolicy: IfNotPresent 544 | name: create 545 | securityContext: 546 | allowPrivilegeEscalation: false 547 | nodeSelector: 548 | kubernetes.io/os: linux 549 | restartPolicy: OnFailure 550 | securityContext: 551 | fsGroup: 2000 552 | runAsNonRoot: true 553 | runAsUser: 2000 554 | serviceAccountName: ingress-nginx-admission 555 | --- 556 | apiVersion: batch/v1 557 | kind: Job 558 | metadata: 559 | labels: 560 | app.kubernetes.io/component: admission-webhook 561 | app.kubernetes.io/instance: ingress-nginx 562 | app.kubernetes.io/name: ingress-nginx 563 | app.kubernetes.io/part-of: ingress-nginx 564 | app.kubernetes.io/version: 1.7.1 565 | name: ingress-nginx-admission-patch 566 | namespace: ingress-nginx 567 | spec: 568 | template: 569 | metadata: 570 | labels: 571 | app.kubernetes.io/component: admission-webhook 572 | app.kubernetes.io/instance: ingress-nginx 573 | app.kubernetes.io/name: ingress-nginx 574 | app.kubernetes.io/part-of: ingress-nginx 575 | app.kubernetes.io/version: 1.7.1 576 | name: ingress-nginx-admission-patch 577 | spec: 578 | containers: 579 | - args: 580 | - patch 581 | - --webhook-name=ingress-nginx-admission 582 | - --namespace=$(POD_NAMESPACE) 583 | - --patch-mutating=false 584 | - --secret-name=ingress-nginx-admission 585 | - --patch-failure-policy=Fail 586 | env: 587 | - name: POD_NAMESPACE 588 | valueFrom: 589 | fieldRef: 590 | fieldPath: metadata.namespace 591 | image: registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20230312-helm-chart-4.5.2-28-g66a760794@sha256:01d181618f270f2a96c04006f33b2699ad3ccb02da48d0f89b22abce084b292f 592 | imagePullPolicy: IfNotPresent 593 | name: patch 594 | securityContext: 595 | allowPrivilegeEscalation: false 596 | nodeSelector: 597 | kubernetes.io/os: linux 598 | restartPolicy: OnFailure 599 | securityContext: 600 | fsGroup: 2000 601 | runAsNonRoot: true 602 | runAsUser: 2000 603 | serviceAccountName: ingress-nginx-admission 604 | --- 605 | apiVersion: networking.k8s.io/v1 606 | kind: IngressClass 607 | metadata: 608 | labels: 609 | app.kubernetes.io/component: controller 610 | app.kubernetes.io/instance: ingress-nginx 611 | app.kubernetes.io/name: ingress-nginx 612 | app.kubernetes.io/part-of: ingress-nginx 613 | app.kubernetes.io/version: 1.7.1 614 | name: nginx 615 | spec: 616 | controller: k8s.io/ingress-nginx 617 | --- 618 | apiVersion: admissionregistration.k8s.io/v1 619 | kind: ValidatingWebhookConfiguration 620 | metadata: 621 | labels: 622 | app.kubernetes.io/component: admission-webhook 623 | app.kubernetes.io/instance: ingress-nginx 624 | app.kubernetes.io/name: ingress-nginx 625 | app.kubernetes.io/part-of: ingress-nginx 626 | app.kubernetes.io/version: 1.7.1 627 | name: ingress-nginx-admission 628 | webhooks: 629 | - admissionReviewVersions: 630 | - v1 631 | clientConfig: 632 | service: 633 | name: ingress-nginx-controller-admission 634 | namespace: ingress-nginx 635 | path: /networking/v1/ingresses 636 | failurePolicy: Fail 637 | matchPolicy: Equivalent 638 | name: validate.nginx.ingress.kubernetes.io 639 | rules: 640 | - apiGroups: 641 | - networking.k8s.io 642 | apiVersions: 643 | - v1 644 | operations: 645 | - CREATE 646 | - UPDATE 647 | resources: 648 | - ingresses 649 | sideEffects: None 650 | --------------------------------------------------------------------------------