Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Practical Technical Cheat Sheet for Python, Linux, SQL and Software Testing

Tech 1

Python Programming Examples

Sorting

Selection Sort

def selection_sort(input_list):
    for idx in range(len(input_list)):
        min_pos = idx
        for sub_idx in range(idx + 1, len(input_list)):
            if input_list[sub_idx] < input_list[min_pos]:
                min_pos = sub_idx
        input_list[idx], input_list[min_pos] = input_list[min_pos], input_list[idx]
    return input_list

sample_list = [3, 2, 5, 1]
print(selection_sort(sample_list))

Built-in Sorted Function

sample_list = [3, 2, 5, 1]
print(sorted(sample_list, reverse=True))

Find Min/Max Values

sample_list = [3, 2, 5, 1, 5]
# Built-in method
print(max(sample_list))
print(min(sample_list))

# Custom implementation
def find_max(input_list):
    current_max = input_list[0]
    for num in input_list:
        if num > current_max:
            current_max = num
    return current_max

print(find_max(sample_list))

List Deduplication

original_list = [3, 2, 3, 5, 1, 5, 5]
# Using set
unique_list = list(set(original_list))
print(unique_list)

# Custom implementation preserving order
unique_ordered = []
for item in original_list:
    if item not in unique_ordered:
        unique_ordered.append(item)
print(unique_ordered)

Count Element Occurrences

original_list = [3, 2, 3, 5, 1, 5, 5]
# Using dictionary
count_dict = {}
for item in original_list:
    count_dict[item] = original_list.count(item)
print(count_dict)

# Alternative using collections.Counter
from collections import Counter
print(Counter(original_list))

Reverse a Sequence

test_str = "tom"
# Slicing method
reversed_str = test_str[::-1]
print(reversed_str)

# Using pop()
def reverse_with_pop(input_str):
    char_list = list(input_str)
    reversed_result = ""
    while char_list:
        reversed_result += char_list.pop()
    return reversed_result
print(reverse_with_pop(test_str))

# Index-based reversal
def reverse_by_index(input_str):
    char_list = list(input_str)
    reversed_result = ""
    length = len(char_list)
    for idx in range(length):
        reversed_result += char_list[length - 1 - idx]
    return reversed_result
print(reverse_by_index(test_str))

Recursive File Traversal

import os

def list_all_files(base_path):
    for entry in os.listdir(base_path):
        full_path = os.path.join(base_path, entry)
        if os.path.isdir(full_path):
            list_all_files(full_path)
        else:
            print(full_path)

target_dir = r"D:\test_cases"
list_all_files(target_dir)

Parameterized Decorator

def decorator_factory(option):
    def outer_wrapper(func):
        def inner_wrapper(*args, **kwargs):
            if option == 1:
                print("Applying decoration 1...")
            elif option == 2:
                print("Applying decoration 2...")
            func(*args, **kwargs)
        return inner_wrapper
    return outer_wrapper

@decorator_factory(2)
def sample_function():
    print("Operation completed successfully...")

sample_function()

Sort a Dictionary

sample_dict = {"1": "tom", "3": "Lily", "2": "Jim"}
# Sort by key using sorted()
sorted_items = sorted(sample_dict.items(), key=lambda x: x[0])
print(sorted_items)

# Alternative manual sorting
sorted_keys = sorted(sample_dict.keys())
sorted_values = [sample_dict[key] for key in sorted_keys]
sorted_dict = {k: v for k, v in zip(sorted_keys, sorted_values)}
print(sorted_dict)

Longest Common Prefix

def longest_common_prefix(str_list):
    if not str_list:
        return ""
    min_length = min(len(s) for s in str_list)
    common_prefix = ""
    for idx in range(min_length):
        current_char = str_list[0][idx]
        for s in str_list:
            if s[idx] != current_char:
                return common_prefix
        common_prefix += current_char
    return common_prefix

test_list = ["flight", "floor", "floy", "flower"]
print(longest_common_prefix(test_list))

Recursive Sum Calculation

def recursive_sum(n):
    if n <= 1:
        return 1
    return n + recursive_sum(n - 1)

print(recursive_sum(100))

Build Nested Menu Tree

menu_data = [
    {'id': 1, 'name': 'Main Menu', 'status': 1, 'parent_id': 0},
    {'id': 2, 'name': 'Submenu 1', 'status': 1, 'parent_id': 1},
    {'id': 3, 'name': 'Submenu 1.1', 'status': 1, 'parent_id': 2},
    # Add additional menu items as needed
]

def build_nested_menu(menu_items, parent_id=0):
    nested_menu = []
    for item in menu_items:
        if item['parent_id'] == parent_id:
            child_nodes = build_nested_menu(menu_items, item['id'])
            nested_menu.append({
                "name": item['name'],
                "children": child_nodes
            })
    return nested_menu

print(build_nested_menu(menu_data))

Find Consecutive Number Sequences

def find_consecutive_groups(num_list):
    if not num_list:
        return []
    consecutive_groups = []
    current_group = [num_list[0]]
    for num in num_list[1:]:
        if num == current_group[-1] + 1:
            current_group.append(num)
        else:
            if len(current_group) == 1:
                consecutive_groups.append(current_group[0])
            else:
                consecutive_groups.append([current_group[0], current_group[-1]])
            current_group = [num]
    # Add final group
    if len(current_group) == 1:
        consecutive_groups.append(current_group[0])
    else:
        consecutive_groups.append([current_group[0], current_group[-1]])
    return consecutive_groups

test_list = [1,2,3,5,6,8]
print(find_consecutive_groups(test_list))

LRU Cache Implementation

from collections import OrderedDict

class LRUCache:
    def __init__(self, max_size):
        self.max_size = max_size
        self.cache = OrderedDict()
    
    def put(self, key, value):
        if key in self.cache:
            self.cache.pop(key)
        if len(self.cache) >= self.max_size:
            self.cache.popitem(last=False)
        self.cache[key] = value
    
    def get(self, key):
        if key not in self.cache:
            return None
        # Move key to end to mark as recently used
        val = self.cache.pop(key)
        self.cache[key] = val
        return val

# Test usage
cache = LRUCache(3)
cache.put("1", "1")
cache.put("2", "2")
cache.put("1", "3")
print(cache.cache)
cache.get("1")
print(cache.cache)

Fibonacci for Frog Jump Problem

def frog_jump_recursive(n):
    """Calculate ways for frog to jump up n stairs, can jump 1 or 2 steps"""
    if n == 0 or n == 1:
        return 1
    elif n == 2:
        return 2
    else:
        return frog_jump_recursive(n-1) + frog_jump_recursive(n-2)

print(frog_jump_recursive(4))

Additional Utility Functions

# 99 Multiplication Table
def print_multiplication_table():
    for i in range(1, 10):
        for j in range(1, i+1):
            print(f"{j}*{i}={j*i}\t", end="")
        print()

# Prime Number Check
import math
def is_prime(num):
    if num <= 1:
        return False
    if num == 2:
        return True
    if num % 2 == 0:
        return False
    for divisor in range(3, int(math.sqrt(num)) +1, 2):
        if num % divisor == 0:
            return False
    return True

# Palindrome Check
def is_palindrome(input_str):
    reversed_str = input_str[::-1]
    return input_str == reversed_str

Linux Administration Commands

Network and Process Monitoring

  1. List all TCP/UDP connections: lsof -i
  2. Check process using port 80: lsof -i:80
  3. Find port for a specific process: lsof -i -P | grep influxd
  4. Kill process by port 80: lsof -i:80 | awk '{print $2}' | xargs kill or lsof -ti:8000 | xargs kill
  5. Kill all Python processes: ps aux | grep python | awk '{print $2}' | xargs kill

Log File Operations

  1. View lines 100-200: head -n 200 filename | tail -n 100
  2. View lines 5-6: head -n 6 filename | tail -n 1
  3. Search logs for keyword in last 100 lines: tail -n 100 filename | grep "keyword"

Disk and Directory Managemant

  1. Check top 3 largest top-level directories (including hidden files): du -h -d 1 | sort -hr | head -n 3
  2. Check top 3 largest top-level directories (excluding hidden files): du -sh * | sort -hr | head -n 3
  3. List disk partition usage: df -h

Compression and Extraction

  1. Extract tar file: tar -xvf archive.tar
  2. Create tar archive: tar -cvf archive.tar target_file/

Grep Usage

  1. Search file with line numbers: grep -n "keyword" filename
  2. Recursively search directory: grep -r "keyword" target_dir/
  3. Case-insensitive search: grep -i "keyword" filename
  4. Inverse search (exclude matches): grep -v "keyword" filename

System Monitoring

  1. View overall system load: w or uptime (shows 1/5/15 minute CPU load averages)
  2. Dynamic system resource monitor: top
  3. Memory usage summary: free -h, or refresh every 5 seconds with units in GB: free -g -t -s 5
  4. Detailed disk I/O stats: iostat, or extended stats: iostat -dx
  5. Virtual memory and system stats: vmstat

SQL Basics

Differences Between DELETE, TRUNCATE, DROP

  1. DELETE: Removes table rows, supports transaction rolllback
  2. TRUNCATE: Removes all table rows, no rollback support, faster than DELETE
  3. DROP: Deletes entire table structure, no rollback support

MySQL Query Order

Writing order: SELECTFROMJOINONWHEREGROUP BYHAVINGORDER BYLIMIT Execution order: FROMONJOINWHEREGROUP BYHAVINGSELECTDISTINCTORDER BYLIMIT

Grouping and Sorting Example

Group student data by gender, sort by age descending:

SELECT name, sex, age FROM student_users GROUP BY sex, age, name ORDER BY sex, age DESC;

Common Index Types

  1. Primary Key Index: Auto-created for primary key columns, supports auto-increment
  2. Unique Index: Prevents duplicate values, allows single NULL value
  3. Regular Index: Basic index for faster querying
  4. Composite Index: Uses left-most prefix matching for multi-column queries
  5. Full-Text Index: For efficient text search, not compatible with LIKE '%keyword%'
  6. Spatial Index: For geographic location data

Software Testing

Test Design Techniques

Equivalence partitioning, boundary value analysis, decision table testing

General Test Case Checklist

  1. Functional testing and state transitions
  2. UI/UX testing
  3. Performance testing (sharding, database scaling)
  4. Usability testing
  5. Compatibility testing
  6. Weak network testing
  7. Interruption testing
  8. Installation/uninstallation and version testing

API Testing Strategy

Cover these categories:

  1. Functional: Validate input/output data types, required/optional fields, file size/type limits, pagination, sorting, input validation, output correctness
  2. Performance: Response time, concurrent request handling
  3. Security: XSS/JS injection protection, sensitive data encryption, authentication/authorization
  4. Exception Handling: Network interruptions, database failures, idempotency
  5. Compatibility: New and legacy data compatibility
  6. End-to-end: Single interface and chained interface flows

Coupon System Test Cases

Functional

  • Full discount, percentage discount
  • Prevent negative/zero discount after calculation
  • Validate state before/after coupon use
  • Handle decimal precision
  • Expired coupon validation
  • Multi-coupon stacking rules
  • Coupon application order rules

Performance/Exception: Weak network, idempotency checks

Input Field Testing

Functional

  • Dropdown loading default data sorted by time descending
  • Search historical data
  • Exact and fuzzy (prefix/middle/suffix) search
  • Character limit validation
  • Pagination and sorting for search results
  • Invalid input handling (special characters, empty searches)

Performance: Response time validation

Security: XSS protection, authentication checks

Compatibility: Browser and screen resolution compatibility

Exception: Network interruptions, database failures, authentication errors

Performance Metrics and Testing

Key Performance Indicators

  1. Throughput: Number of requests processed per unit time (network performance metric)
  2. TPS: Transactions per second (server performance metric)
  3. CPU Utilization: Target <80% for stable operation
  4. Response Time: Time taken to complete a request

Server Performance Monitoring Focus Areas

  1. CPU Usage: Use top for real-time monitoring
  2. Memory Usage: Use free -h -t to check physicla and swap memory
  3. CPU Load: Use w/uptime to check 1/5/15 minute average loads
  4. Disk Space: Use df -h to check partition usage
  5. Disk I/O: Monitor read/write rates, I/O operations, queue length, wait time, utilization

Miscellaneous Technical Notes

CI/CD Workflow

  1. Common stack: GitLab + TeamCity
  2. CI Steps: Static code analysis, security vulnerability scanning
  3. CD Steps: Test environment validation, canary release, full production rollout

Charles Proxy Usage

  1. Breakpoints: Modify request/response data
  2. Throttling: Simulate weak network conditions
  3. Map Remote: Redirect requests to alternate endpoints

unittest vs pytest

  1. Both are Python testing frameworks for API testing
  2. unittest is built into Python standard library
  3. pytest is third-party, with simpler syntax, rich plugin ecosystem, and detailed test reports

Selenium Automation Workflow

  1. Test script acts as client
  2. Browser driver acts as server
  3. Client sends HTTP requests to browser driver
  4. Browser driver executes native browser APIs
  5. Browser returns operation results to driver
  6. Driver sends final results back to test script

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.