📘 PYTHON
■ LIST
arr = [1, 2, 3, 4, 5] arr.append(x) # Add to end arr.pop() # Remove from end arr.pop(0) # Remove first arr.insert(i, x) # Insert at index arr[1:3] # Slice [2, 3] arr[::-1] # Reverse len(arr) # Length arr.sort() # Sort in-place sorted(arr) # New sorted list sorted(arr, reverse=True) sorted(arr, key=lambda x: -x) x in arr # Check exists arr.index(x) # Find index arr.count(x) # Count x arr.remove(x) # Remove first x min(arr) max(arr) sum(arr)
■ DICT
d = {'a': 1, 'b': 2} d['c'] = 3 # Add/Update d.get('x', 0) # Get with default d.keys() # All keys d.values() # All values d.items() # (k, v) pairs 'a' in d # Check key exists del d['a'] # Delete key d.pop('a', None) # Remove & return d.setdefault('a',0) # Get or set d.update({'c': 3}) # Merge dicts
■ STRING
s.upper() s.lower() s.title() s.strip() # Trim whitespace s.split(' ') # Split to list ' '.join(list) # Join to string s.replace('a','b') # Replace all s[::-1] # Reverse s.find('x') # Index or -1 s.startswith('hi') # Bool f'Hello {name}' # f-string f'{x:.2f}' # 2 decimals s.isdigit() # All digits? s.isalpha() # All letters?
■ SET
s = {1, 2, 3} s = set() # Empty set s.add(4) # Add one s.remove(1) # Error if none s.discard(1) # Safe remove s1 & s2 # Intersection s1 | s2 # Union s1 - s2 # Difference x in s # Check O(1)
■ COUNTER
from collections import Counter c = Counter('aabbbc') # Counter({'b':3, 'a':2, 'c':1}) c = Counter([1,1,2,3,3,3]) c.most_common(2) # [(3,3),(1,2)] c['a'] # Get count c['a'] += 1 # Increment
■ DEFAULTDICT
from collections import defaultdict d = defaultdict(list) d['key'].append(1) # No KeyError! d = defaultdict(int) d['count'] += 1 # Starts at 0 d = defaultdict(set) d['key'].add('a')
■ DEQUE (FAST QUEUE)
from collections import deque q = deque([1, 2, 3]) q.append(4) # Right O(1) q.appendleft(0) # Left O(1) q.pop() # Right O(1) q.popleft() # Left O(1) q[0] q[-1] # Peek ends
■ HEAPQ (MIN HEAP)
import heapq heapq.heapify(arr) # To min heap heapq.heappush(h, x) # Add O(logn) heapq.heappop(h) # Pop smallest h[0] # Peek min heapq.nlargest(k, arr) heapq.nsmallest(k, arr) # Max heap: negate values heapq.heappush(h, -x)
■ COMPREHENSION
[x*2 for x in arr] [x for x in arr if x % 2 == 0] [x*2 for x in arr if x % 2 == 0] # Dict comprehension {k: len(k) for k in words} # Set comprehension {x % 10 for x in arr}
■ LOOP TECHNIQUES
for i in range(5): # 0,1,2,3,4 for i in range(2, 5): # 2,3,4 for i in range(0, 10, 2): # 0,2,4,6,8 for i in range(5, 0, -1): # 5,4,3,2,1 for i, v in enumerate(arr): for i, v in enumerate(arr, 1): for a, b in zip(list1, list2): for k, v in d.items():
■ BUILT-IN FUNCTIONS
len() sum() min() max() abs() round(3.14159, 2) # 3.14 pow(2, 3) # 8 divmod(10, 3) # (3, 1) sorted(arr) # New sorted list sorted(arr, key=len) reversed(arr) # Iterator any([F, T, F]) # True all([T, T, T]) # True map(func, arr) filter(func, arr)
■ TYPE CONVERSION
int('42') # 42 int('101', 2) # 5 (binary) str(42) # '42' float('3.14') # 3.14 bool(0) bool('') # False list('abc') # ['a','b','c'] tuple([1,2]) # (1, 2) set([1,2,2]) # {1, 2} ''.join(['a','b']) # 'ab'
■ COMMON PITFALLS
WrongCorrect
d.keysd.keys()
d[sorted(s)]d[tuple(sorted(s))]
x == Nonex is None
stack.pop()if stack: stack.pop()
arr.sort()sorted(arr) # new
■ TWO SUM
def two_sum(nums, target): seen = {} for i, num in enumerate(nums): need = target - num if need in seen: return [seen[need], i] seen[num] = i return []
■ VALID PARENTHESES
def is_valid(s): stack = [] m = {')':'(', ']':'[', '}':'{'} for c in s: if c in m: if not stack or \ stack.pop() != m[c]: return False else: stack.append(c) return len(stack) == 0
■ SLIDING WINDOW
def max_sum(nums, k): window = sum(nums[:k]) best = window for i in range(k, len(nums)): window += nums[i] - nums[i-k] best = max(best, window) return best
■ BINARY SEARCH
def binary_search(nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 return -1
■ BFS TEMPLATE
def bfs(start): queue = deque([start]) visited = {start} while queue: node = queue.popleft() for nb in get_neighbors(node): if nb not in visited: visited.add(nb) queue.append(nb)
☸️ KUBERNETES
■ CORE RESOURCES
ResourcePurpose
PodSmallest deployable unit
DeploymentManage Pod replicas
ServiceStable network endpoint
ConfigMapNon-sensitive config
SecretSensitive data (base64)
PV/PVCPersistent storage
IngressHTTP/HTTPS routing
StatefulSetStateful apps (DB)
DaemonSetOne Pod per Node
■ SERVICE TYPES
TypeAccessUse
ClusterIPInternalPod-to-Pod
NodePortNode:30000+Dev/Test
LoadBalancerExternal IPProduction
■ SERVICE YAML
apiVersion: v1 kind: Service metadata: name: my-service spec: type: ClusterIP selector: app: my-app # Match Pod label ports: - port: 80 # Service port targetPort: 3000
■ POD STATES
StateMeaning
PendingWaiting to schedule
RunningAt least 1 running
CrashLoopBackOffCrash + restart
ImagePullBackOffCan't pull image
■ DEPLOYMENT YAML
apiVersion: apps/v1 kind: Deployment metadata: name: my-deploy spec: replicas: 3 selector: matchLabels: app: my-app # Must match! template: metadata: labels: app: my-app # Same here! spec: containers: - name: app image: nginx:1.21 ports: - containerPort: 80
■ DEPLOYMENT STRATEGY
# RollingUpdate (zero downtime) strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 # Max extra maxUnavailable: 0 # 0=no downtime # Recreate (has downtime) strategy: type: Recreate
■ PROBES
ProbeOn Failure
livenessRestart container
readinessRemove from Service
startupBlock other probes
livenessProbe: httpGet: path: /healthz port: 8080 initialDelaySeconds: 15 periodSeconds: 10 failureThreshold: 3
■ RESOURCES
resources: requests: # Guaranteed memory: 256Mi cpu: 250m # 0.25 CPU limits: # Maximum memory: 512Mi cpu: 500m # 1000m = 1 CPU
■ CONFIGMAP / SECRET
# Import ALL envFrom: - configMapRef: name: app-config # Single key (use KeyRef!) env: - name: DB_HOST valueFrom: configMapKeyRef: name: app-config key: DATABASE_HOST # Mount as files volumeMounts: - name: config-vol mountPath: /etc/config volumes: - name: config-vol configMap: name: app-config
■ NODESELECTOR & TOLERATION
# NodeSelector nodeSelector: zone: us-east-1a # Tolerations tolerations: - key: dedicated operator: Equal value: database effect: NoSchedule
■ POD PENDING DEBUG
CauseFix
Insufficient cpu/memLower requests
NodeSelector missFix labels
Taint not toleratedAdd toleration
PVC unboundCheck StorageClass
■ APIVERSION
ResourceapiVersion
Pod, Service, ConfigMapv1
Deployment, StatefulSetapps/v1
Ingressnetworking.k8s.io/v1
Job, CronJobbatch/v1
■ KUBECTL VIEW
kubectl get pods kubectl get pods -A # All NS kubectl get pods -o wide # More info kubectl get all kubectl describe pod <n> # Details! kubectl logs <pod> kubectl logs <pod> -f # Follow kubectl logs <pod> --tail=50
■ KUBECTL DEBUG
kubectl exec -it <pod> -- /bin/bash kubectl exec -it <pod> -- sh kubectl port-forward <pod> 8080:80 kubectl port-forward svc/<s> 8080:80 kubectl top nodes kubectl top pods
■ KUBECTL DEPLOYMENT
kubectl apply -f manifest.yaml kubectl delete -f manifest.yaml kubectl scale deploy <n> --replicas=5 kubectl rollout status deploy/<n> kubectl rollout history deploy/<n> kubectl rollout undo deploy/<n> kubectl rollout undo deploy/<n> \ --to-revision=2 kubectl rollout restart deploy/<n>
■ KUBECTL DELETE
kubectl delete pod <n> kubectl delete pod <n> --force \ --grace-period=0 kubectl delete pods --all
🖥️ VIRTUALIZATION
■ HYPERVISOR TYPES
Type 1 (Bare Metal) Type 2 (Hosted) ──────────────────── ──────────────────── ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ VM │ │ VM │ │ VM │ │ VM │ └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘ ┌──▼──────▼──┐ ┌──▼──────▼──┐ │ Hypervisor │ │ Hypervisor │ └─────┬──────┘ └─────┬──────┘ │ ┌─────▼──────┐ │ │ Host OS │ ┌─────▼──────┐ └─────┬──────┘ │ Hardware │ ┌─────▼──────┐ └────────────┘ │ Hardware │ └────────────┘ Type 1: ESXi, Hyper-V Type 2: VirtualBox, VMware WS
■ VM vs CONTAINER
特性VMContainer
隔離完整 OS共享 Kernel
啟動分鐘級秒級
資源GB 級MB 級
密度10-20/台100+/台
適用不同 OS微服務
■ vSPHERE 組件
vSphere = 套件品牌
ESXi = Type 1 Hypervisor(裝在實體機)
vCenter = 集中管理平台(提供 HA/DRS/vMotion)

Cluster = 多台 ESXi 組成資源池
■ VxRail (HCI)
VxRail = Dell 硬體 + VMware vSAN

優點:
  • Compute+Storage+Network 整合
  • 快速部署(數小時)
  • 橫向擴展(加節點)
  • 單一廠商支援
■ HA vs FT vs DRS
功能說明停機
HA故障自動重啟 VM1-5 分鐘
FT影子 VM 即時接管零停機
DRS自動負載平衡-
■ vMOTION
vMotion = 熱遷移 VM(不停機)

必要條件:
  • ✅ 共享儲存
  • ✅ vMotion 網路(建議 10Gbps)
  • ✅ 相容 CPU(同廠商)
  • ✅ 同一個 vCenter

Storage vMotion = 遷移硬碟檔案
■ SNAPSHOT
Snapshot = 快速回復點

⚠️ 注意:
  • 不是備份!
  • 不要超過 2-3 個
  • 不要保留超過 72 小時
SnapshotBackup
目的快速回復長期保護
位置同一儲存異地
■ RESOURCE MANAGEMENT
設定說明
Reservation保證最少資源(訂位)
Limit最多能用的上限
Share競爭時的優先級
■ STORAGE TYPES
類型存取用途
DASBlock本地碟
NASFile檔案共享
SANBlock高效能
■ DATASTORE TYPES
類型說明
VMFSVMware 專用,Block
NFS網路檔案系統
vSAN軟體定義,本地碟整合
■ vSAN
vSAN = 本地硬碟整合成共享儲存池

Disk Group = 1 SSD (Cache) + N HDD/SSD (Capacity)
FTT副本最少 Host效率
011100%
12350%
23533%
公式:最少 Host = 2 × FTT + 1
■ RAID LEVELS
RAID說明容量可壞
0Striping100%0
1Mirror50%1
5Stripe+ParityN-11
10Mirror+Stripe50%每組1
資料庫推薦:RAID 10
■ THIN vs THICK
ThinThick
分配按需分配立即分配
空間省空間佔空間
效能稍慢較好
■ NETWORK LAYERS
名稱設備/協定
L7ApplicationHTTP, DNS
L4TransportTCP, UDP
L3NetworkIP, Router
L2Data LinkMAC, Switch
■ COMMON PORTS
Port服務Port服務
22SSH443HTTPS
80HTTP3389RDP
53DNS3260iSCSI
■ IP & SUBNET
私有 IP:
• 10.0.0.0/8
• 172.16.0.0/12
• 192.168.0.0/16

/24 = 255.255.255.0 = 254 台
■ VLAN & DHCP
VLAN = 用軟體切分網路
• 隔離不同環境(Prod/Dev)
• 跨 VLAN 需要 Router (L3)

DHCP = 自動分配 IP
• DORA: Discover→Offer→Request→Ack
• 提供:IP, Mask, Gateway, DNS
■ TROUBLESHOOTING
網路排查順序:

1. ping 127.0.0.1(自己)
2. ping 同網段(鄰居)
3. ping Gateway(大門)
4. ping 8.8.8.8(外部 IP)
5. ping google.com(DNS)

卡在哪步 = 問題在哪層
🐧 LINUX
■ FILE OPERATIONS
ls -la # List all + details ls -lh # Human readable size cd /path # Change directory cd .. # Parent directory cd - # Previous directory pwd # Current directory mkdir -p a/b/c # Create nested dirs touch file.txt # Create empty file cp -r src dst # Copy recursive mv old new # Move/rename rm -rf dir # Force delete (危險!)
■ VIEW FILES
cat file.txt # Show all head -n 20 file # First 20 lines tail -n 20 file # Last 20 lines tail -f log.txt # Follow (實時看log) less file.txt # Paginated (q退出) wc -l file.txt # Count lines
■ PERMISSIONS
# r=4, w=2, x=1 chmod 755 script.sh # rwxr-xr-x chmod 644 file.txt # rw-r--r-- chmod +x script.sh # Add execute chown user:group file chown -R user:group dir/
權限數字用途
rwxr-xr-x755腳本/目錄
rw-r--r--644一般檔案
rw-r-----640敏感檔案
rwx------700私密目錄
■ FIND & GREP
# Find files find /path -name "*.log" find /path -type f -size +100M find /path -mtime -7 # 7天內修改 # Search content grep "error" file.txt grep -i "error" file # Ignore case grep -r "error" /path/ # Recursive grep -n "error" file # Line numbers grep -c "error" file # Count grep -v "info" file # Exclude # Combine cat log | grep "error" | wc -l
■ PROCESS MANAGEMENT
ps aux # All processes ps aux | grep nginx top # Real-time monitor htop # Better top kill PID # Graceful kill kill -9 PID # Force kill killall nginx # Kill by name pkill -f "python" # Kill by pattern # Background ./script.sh & # Run in background nohup ./script.sh & # Keep after logout jobs # List bg jobs fg # Bring to foreground
■ TOP 5 RESOURCE USAGE
# Most CPU ps aux --sort=-%cpu | head -5 # Most Memory ps aux --sort=-%mem | head -5 # Largest files du -ah /path | sort -rh | head -10
■ SYSTEM INFO
uname -a # System info hostname # Hostname uptime # Uptime whoami # Current user df -h # Disk usage du -sh /path # Directory size free -h # Memory usage lscpu # CPU info
■ SERVICE (systemd)
systemctl start nginx systemctl stop nginx systemctl restart nginx systemctl status nginx systemctl enable nginx # 開機啟動 systemctl disable nginx # View logs journalctl -u nginx journalctl -u nginx -f # Follow journalctl -u nginx --since "1 hour ago"
■ COMPRESS / EXTRACT
# tar.gz tar -czvf archive.tar.gz files/ tar -xzvf archive.tar.gz # c=create, x=extract # z=gzip, v=verbose, f=file # zip zip -r archive.zip files/ unzip archive.zip
■ NETWORK
ip addr # Show IP (新) ifconfig # Show IP (舊) ping google.com # Test connection curl http://url # HTTP request wget http://url # Download file # Check port usage netstat -tulpn | grep 8080 ss -tulpn | grep 8080 lsof -i :8080
■ COMMON PORTS
PortService
22SSH
80HTTP
443HTTPS
3306MySQL
5432PostgreSQL
6379Redis
3389RDP
■ TEXT PROCESSING
sort file.txt # Sort sort -r file.txt # Reverse sort sort -n file.txt # Numeric sort uniq # Remove duplicates sort | uniq -c # Count duplicates cut -d',' -f1 file # Get column 1 awk '{print $1}' # Get field 1 sed 's/old/new/g' # Replace all
■ TROUBLESHOOTING
網路排查順序:
1. ping 127.0.0.1(自己)
2. ping 同網段(鄰居)
3. ping Gateway(大門)
4. ping 8.8.8.8(外部IP)
5. ping google.com(DNS)

服務排查:
1. systemctl status
2. journalctl -u service
3. tail -f /var/log/*