From 4b43cef1e11505c5aba70181499e77ab2a7430bf Mon Sep 17 00:00:00 2001 From: Date: Sun, 10 Nov 2024 18:02:12 -0500 Subject: [PATCH] Deployed a265893 with MkDocs version: 1.6.1 --- 404.html | 12 + advanced-command-line-features/index.html | 12 + advanced-fast-api/index.html | 12 + advanced-python-operations/index.html | 16 +- advanced-streamlit/index.html | 12 + bash/index.html | 12 + basics-of-git/index.html | 12 + code-of-conduct/index.html | 12 + coding-patterns-for-interviews/index.html | 354 +++++++++++ command-line-basics/index.html | 12 + command-line-cheat-sheet/index.html | 12 + command-line-text-manipulation/index.html | 12 + command-line-utilities/index.html | 12 + data-patterns/index.html | 638 ++++++++++++++++++++ fast-api-testing/index.html | 12 + fast-api/index.html | 16 +- getting-to-know-the-command-line/index.html | 12 + git-and-github-voice-overview/index.html | 12 + git-and-github/index.html | 12 + git-flow/index.html | 12 + github-cli/index.html | 12 + index.html | 14 +- intro-to-python/index.html | 12 + search.html | 12 + search/search_index.json | 2 +- software-design-patterns/index.html | 542 +++++++++++++++++ streamlit-fundamentals/index.html | 12 + system-design-patterns/index.html | 529 ++++++++++++++++ 28 files changed, 2345 insertions(+), 6 deletions(-) create mode 100644 coding-patterns-for-interviews/index.html create mode 100644 data-patterns/index.html create mode 100644 software-design-patterns/index.html create mode 100644 system-design-patterns/index.html diff --git a/404.html b/404.html index 486d947..680a13f 100644 --- a/404.html +++ b/404.html @@ -81,6 +81,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/advanced-command-line-features/index.html b/advanced-command-line-features/index.html index 564b98f..70aa62a 100644 --- a/advanced-command-line-features/index.html +++ b/advanced-command-line-features/index.html @@ -162,6 +162,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/advanced-fast-api/index.html b/advanced-fast-api/index.html index 03b80e6..0fe07c3 100644 --- a/advanced-fast-api/index.html +++ b/advanced-fast-api/index.html @@ -88,6 +88,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/advanced-python-operations/index.html b/advanced-python-operations/index.html index c3e9c6d..f4fbd77 100644 --- a/advanced-python-operations/index.html +++ b/advanced-python-operations/index.html @@ -134,6 +134,18 @@
  • + + +
  • Patterns +
  • FastAPI @@ -440,7 +452,7 @@

    Movement Orders (Next Steps)


    @@ -466,7 +478,7 @@

    Movement Orders (Next Steps)

    « Previous - Next » + Next » diff --git a/advanced-streamlit/index.html b/advanced-streamlit/index.html index 736d433..ee3d48f 100644 --- a/advanced-streamlit/index.html +++ b/advanced-streamlit/index.html @@ -88,6 +88,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/bash/index.html b/bash/index.html index 43fd82d..4ad976c 100644 --- a/bash/index.html +++ b/bash/index.html @@ -170,6 +170,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/basics-of-git/index.html b/basics-of-git/index.html index 5d4a1fa..d811dda 100644 --- a/basics-of-git/index.html +++ b/basics-of-git/index.html @@ -124,6 +124,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/code-of-conduct/index.html b/code-of-conduct/index.html index 3ab5f2b..8299ad1 100644 --- a/code-of-conduct/index.html +++ b/code-of-conduct/index.html @@ -108,6 +108,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/coding-patterns-for-interviews/index.html b/coding-patterns-for-interviews/index.html new file mode 100644 index 0000000..60454d7 --- /dev/null +++ b/coding-patterns-for-interviews/index.html @@ -0,0 +1,354 @@ + + + + + + + + Coding Interview Patterns - Vets Who Code SOPs + + + + + + + + + + + + + + +
    + + +
    + +
    +
    +
      +
    • + + + +
    • +
    • +
    +
    +
    +
    +
    + +

    VetsWhoCode: Combat-Ready Coding Patterns 🎖️

    +
    +

    "In code as in combat, patterns and preparation determine success." - VetsWhoCode

    +
    +

    Mission Overview

    +

    These battle-tested coding patterns form the foundation of technical interviews and efficient problem-solving. Like standard operating procedures (SOPs) in combat, these patterns provide proven solutions to common challenges.

    +

    Table of Contents

    + +

    Mission Briefing

    +

    These patterns are your tactical toolset for coding interviews. Like a well-maintained weapon system, each pattern serves a specific purpose and should be mastered through consistent practice and application.

    +

    Battle Rhythm

    +
      +
    1. Identify the pattern that fits your mission
    2. +
    3. Apply the appropriate tactical solution
    4. +
    5. Test and verify your implementation
    6. +
    7. Optimize for better performance
    8. +
    +
    +

    Two Pointers Pattern

    +

    Tactical Overview

    +

    Mission Type: Coordinated Movement Operations

    +

    Military Context: Like coordinating two fire teams during a patrol - each team moves with purpose and coordination to achieve the mission objective. Just as fire teams maintain relative positioning, our pointers maintain their relationship while moving through the array.

    +

    Battle Plan

    +
      +
    1. Initialize two pointers at strategic positions
    2. +
    3. Move pointers based on mission parameters
    4. +
    5. Maintain coordination between pointer movements
    6. +
    7. Achieve objective with minimal traversal
    8. +
    +

    Implementation: Equipment Load Distribution

    +
    def find_equipment_pairs(weights, target_weight):
    +    """
    +    Mission: Find pairs of equipment that add up to target weight.
    +
    +    Tactical Application: 
    +    - Organizing gear for balanced load distribution
    +    - Matching battle buddies for equipment carry
    +    - Ensuring optimal weight distribution across the unit
    +
    +    Operation Parameters:
    +    weights (list): List of equipment weights
    +    target_weight (int): Target combined weight
    +
    +    Mission Outcome:
    +    list: Pairs of weights that match target
    +    """
    +    weights.sort()  # Organize equipment by weight
    +    left = 0  # Alpha team position
    +    right = len(weights) - 1  # Bravo team position
    +    pairs = []
    +
    +    while left < right:
    +        current_weight = weights[left] + weights[right]
    +        if current_weight == target_weight:
    +            pairs.append((weights[left], weights[right]))
    +            left += 1  # Alpha team advances
    +            right -= 1  # Bravo team falls back
    +        elif current_weight < target_weight:
    +            left += 1  # Alpha team moves forward
    +        else:
    +            right -= 1  # Bravo team adjusts position
    +
    +    return pairs
    +
    +# Field Operations Test
    +equipment_weights = [10, 15, 20, 25, 30, 35]
    +target = 45
    +pairs = find_equipment_pairs(equipment_weights, target)
    +print(f"SITREP: Equipment pairs matching {target}lbs: {pairs}")
    +
    +

    Mission Applications

    +
      +
    1. Finding pairs in sorted arrays (Two Sum)
    2. +
    3. Container optimization (Water Container)
    4. +
    5. Removing duplicates from sorted arrays
    6. +
    +

    Combat Tips

    +
      +
    • Always sort when dealing with pair finding
    • +
    • Consider edge cases like empty arrays
    • +
    • Watch for pointer bounds
    • +
    +

    [Additional sections follow same enhanced format...]

    +

    After Action Review

    +

    Key Tactical Points

    +
      +
    1. Each pattern represents a battle-tested approach to solving specific types of problems
    2. +
    3. Practice these patterns until they become muscle memory
    4. +
    5. Remember: In both coding and combat, preparation and pattern recognition are key to success
    6. +
    +

    Field Notes

    +
      +
    • Document your approaches
    • +
    • Learn from failed attempts
    • +
    • Build your pattern recognition skills
    • +
    +

    Training Resources

    + +
    +

    Standard Operating Procedures

    +
      +
    1. Always identify the pattern before coding
    2. +
    3. Test with multiple scenarios
    4. +
    5. Consider edge cases
    6. +
    7. Optimize after achieving basic functionality
    8. +
    +
    +

    "Code with Honor, Debug with Discipline" - VetsWhoCode

    +

    "Mission success through tactical coding excellence"

    + +
    +
    + +
    +
    + +
    + +
    + +
    + + + + « Previous + + + Next » + + +
    + + + + + + + + + diff --git a/command-line-basics/index.html b/command-line-basics/index.html index 9e5f130..afeeb0e 100644 --- a/command-line-basics/index.html +++ b/command-line-basics/index.html @@ -142,6 +142,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/command-line-cheat-sheet/index.html b/command-line-cheat-sheet/index.html index 1beb7d9..748d786 100644 --- a/command-line-cheat-sheet/index.html +++ b/command-line-cheat-sheet/index.html @@ -112,6 +112,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/command-line-text-manipulation/index.html b/command-line-text-manipulation/index.html index f1019ce..41ca052 100644 --- a/command-line-text-manipulation/index.html +++ b/command-line-text-manipulation/index.html @@ -130,6 +130,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/command-line-utilities/index.html b/command-line-utilities/index.html index e9b6428..7df3bf0 100644 --- a/command-line-utilities/index.html +++ b/command-line-utilities/index.html @@ -176,6 +176,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/data-patterns/index.html b/data-patterns/index.html new file mode 100644 index 0000000..3bb6356 --- /dev/null +++ b/data-patterns/index.html @@ -0,0 +1,638 @@ + + + + + + + + Data Patterns - Vets Who Code SOPs + + + + + + + + + + + + + + +
    + + +
    + +
    +
    +
      +
    • + + + +
    • +
    • +
    +
    +
    +
    +
    + +

    VetsWhoCode: Intelligence & Data Operations Patterns 🎖️

    +
    +

    "Like military intelligence, data operations require precision, scale, and adaptability." - VetsWhoCode

    +
    +

    Overview

    +

    This field manual covers patterns for handling large-scale data operations and AI systems, explained through military analogies and practical implementations.

    +

    Table of Contents

    + +
    +

    Data Processing Patterns

    +

    Military Context

    +

    Like coordinating large-scale military operations, these patterns handle massive data processing operations efficiently and reliably.

    +

    1. MapReduce - Distributed Intelligence Analysis

    +
    class MapReduceFramework:
    +    """
    +    Mission: Process large datasets using distributed computing resources.
    +
    +    Tactical Application:
    +    - Like coordinating multiple intelligence teams
    +    - Each team processes specific intel (Map)
    +    - Command aggregates findings (Reduce)
    +    """
    +    def __init__(self):
    +        self.data_chunks = []
    +        self.results = []
    +
    +    def map_phase(self, data, map_function):
    +        # Distribute data to processing units
    +        mapped_data = []
    +        for chunk in self.data_chunks:
    +            result = map_function(chunk)
    +            mapped_data.append(result)
    +        return mapped_data
    +
    +    def reduce_phase(self, mapped_data, reduce_function):
    +        # Combine results from all units
    +        return reduce_function(mapped_data)
    +
    +    def execute(self, data, map_fn, reduce_fn):
    +        self.data_chunks = self._split_data(data)
    +        mapped_data = self.map_phase(self.data_chunks, map_fn)
    +        return self.reduce_phase(mapped_data, reduce_fn)
    +
    +    def _split_data(self, data, chunk_size=1000):
    +        return [data[i:i + chunk_size] 
    +                for i in range(0, len(data), chunk_size)]
    +
    +# Field Implementation
    +def word_count_map(text):
    +    return [(word, 1) for word in text.split()]
    +
    +def word_count_reduce(mapped_data):
    +    word_counts = {}
    +    for word, count in mapped_data:
    +        word_counts[word] = word_counts.get(word, 0) + count
    +    return word_counts
    +
    +mapreduce = MapReduceFramework()
    +intel_data = "Enemy movement detected in sector alpha..."
    +results = mapreduce.execute(intel_data, word_count_map, word_count_reduce)
    +
    +

    2. Stream Processing - Real-time Intelligence

    +
    from datetime import datetime
    +from queue import Queue
    +
    +class StreamProcessor:
    +    """
    +    Mission: Process continuous data streams in real-time.
    +
    +    Tactical Application:
    +    - Like real-time battlefield monitoring
    +    - Continuous intelligence gathering
    +    - Immediate threat detection
    +    """
    +    def __init__(self):
    +        self.data_stream = Queue()
    +        self.processors = []
    +        self.alert_threshold = 0.8
    +
    +    def add_processor(self, processor):
    +        self.processors.append(processor)
    +
    +    def process_event(self, event):
    +        event['timestamp'] = datetime.now()
    +
    +        for processor in self.processors:
    +            event = processor.process(event)
    +
    +            if self._detect_threat(event):
    +                self._raise_alert(event)
    +
    +        return event
    +
    +    def _detect_threat(self, event):
    +        return event.get('threat_level', 0) > self.alert_threshold
    +
    +    def _raise_alert(self, event):
    +        print(f"ALERT: High threat detected - {event}")
    +
    +# Field Implementation
    +class ThreatDetector:
    +    def process(self, event):
    +        # Analyze event for threats
    +        if 'enemy_activity' in event['data']:
    +            event['threat_level'] = 0.9
    +        return event
    +
    +stream_processor = StreamProcessor()
    +stream_processor.add_processor(ThreatDetector())
    +
    +
    +

    Machine Learning Patterns

    +

    Military Context

    +

    Like training and deploying specialized units, ML patterns focus on building and deploying intelligent systems.

    +

    1. Feature Engineering - Intelligence Preparation

    +
    import numpy as np
    +
    +class FeatureEngineer:
    +    """
    +    Mission: Transform raw intelligence into actionable features.
    +
    +    Tactical Application:
    +    - Like processing raw intel into actionable intelligence
    +    - Identify key indicators
    +    - Standardize reporting formats
    +    """
    +    def __init__(self):
    +        self.feature_transformers = {}
    +        self.feature_importance = {}
    +
    +    def add_transformer(self, feature_name, transformer):
    +        self.feature_transformers[feature_name] = transformer
    +
    +    def transform_features(self, raw_data):
    +        features = {}
    +        for name, transformer in self.feature_transformers.items():
    +            features[name] = transformer(raw_data)
    +
    +        return self._normalize_features(features)
    +
    +    def _normalize_features(self, features):
    +        # Standardize feature values
    +        for name, values in features.items():
    +            if isinstance(values, (list, np.ndarray)):
    +                features[name] = (values - np.mean(values)) / np.std(values)
    +        return features
    +
    +# Field Implementation
    +def location_transformer(data):
    +    # Convert location data to grid coordinates
    +    return [data['lat'], data['lon']]
    +
    +engineer = FeatureEngineer()
    +engineer.add_transformer('location', location_transformer)
    +
    +

    2. Model Deployment - Unit Deployment

    +
    class ModelDeployment:
    +    """
    +    Mission: Deploy and monitor ML models in production.
    +
    +    Tactical Application:
    +    - Like deploying specialized units
    +    - Continuous monitoring
    +    - Performance evaluation
    +    """
    +    def __init__(self, model, version):
    +        self.model = model
    +        self.version = version
    +        self.metrics = {
    +            'accuracy': [],
    +            'latency': [],
    +            'errors': []
    +        }
    +
    +    def predict(self, input_data):
    +        try:
    +            start_time = time.time()
    +            prediction = self.model.predict(input_data)
    +            latency = time.time() - start_time
    +
    +            self._update_metrics(prediction, latency)
    +            return prediction
    +
    +        except Exception as e:
    +            self._log_error(e)
    +            return None
    +
    +    def _update_metrics(self, prediction, latency):
    +        self.metrics['latency'].append(latency)
    +        # Update other metrics
    +
    +    def _log_error(self, error):
    +        self.metrics['errors'].append({
    +            'timestamp': datetime.now(),
    +            'error': str(error)
    +        })
    +
    +# Field Implementation
    +model_deployment = ModelDeployment(trained_model, version="1.0")
    +
    +
    +

    Data Storage Patterns

    +

    Military Context

    +

    Like managing military logistics and intelligence archives, these patterns handle data storage and retrieval efficiently.

    +

    1. Data Lake - Central Intelligence Repository

    +
    class DataLake:
    +    """
    +    Mission: Store vast amounts of raw intelligence data.
    +
    +    Tactical Application:
    +    - Like central intelligence repository
    +    - Raw data storage
    +    - Multiple access patterns
    +    """
    +    def __init__(self, storage_path):
    +        self.storage_path = storage_path
    +        self.metadata = {}
    +        self.access_logs = []
    +
    +    def store_data(self, data_id, data, metadata=None):
    +        # Store raw data with metadata
    +        file_path = f"{self.storage_path}/{data_id}"
    +        self._write_data(file_path, data)
    +
    +        if metadata:
    +            self.metadata[data_id] = metadata
    +
    +        self._log_access('write', data_id)
    +
    +    def retrieve_data(self, data_id):
    +        # Retrieve data and log access
    +        file_path = f"{self.storage_path}/{data_id}"
    +        data = self._read_data(file_path)
    +        self._log_access('read', data_id)
    +        return data
    +
    +    def _log_access(self, operation, data_id):
    +        self.access_logs.append({
    +            'timestamp': datetime.now(),
    +            'operation': operation,
    +            'data_id': data_id
    +        })
    +
    +# Field Implementation
    +data_lake = DataLake("/path/to/storage")
    +data_lake.store_data("intel_001", intel_data, {"classification": "SECRET"})
    +
    +

    2. Hot-Warm-Cold Storage - Intelligence Tiering

    +
    class TieredStorage:
    +    """
    +    Mission: Optimize data storage based on access patterns.
    +
    +    Tactical Application:
    +    - Like tiered intelligence classification
    +    - Priority-based access
    +    - Resource optimization
    +    """
    +    def __init__(self):
    +        self.hot_storage = {}  # Active intelligence
    +        self.warm_storage = {} # Recent intelligence
    +        self.cold_storage = {} # Archived intelligence
    +
    +    def store_data(self, data_id, data, tier='hot'):
    +        if tier == 'hot':
    +            self.hot_storage[data_id] = data
    +        elif tier == 'warm':
    +            self.warm_storage[data_id] = data
    +        else:
    +            self.cold_storage[data_id] = data
    +
    +    def access_data(self, data_id):
    +        # Check each tier and promote if needed
    +        if data_id in self.cold_storage:
    +            data = self.cold_storage.pop(data_id)
    +            self.warm_storage[data_id] = data
    +            return data
    +
    +        if data_id in self.warm_storage:
    +            data = self.warm_storage.pop(data_id)
    +            self.hot_storage[data_id] = data
    +            return data
    +
    +        return self.hot_storage.get(data_id)
    +
    +# Field Implementation
    +storage = TieredStorage()
    +storage.store_data("current_ops", ops_data, "hot")
    +storage.store_data("last_month", old_data, "warm")
    +
    +
    +

    Data Integration Patterns

    +

    Military Context

    +

    Like coordinating joint operations, these patterns ensure smooth data flow between different systems.

    +

    1. Data Pipeline - Intelligence Flow

    +
    class DataPipeline:
    +    """
    +    Mission: Coordinate data flow between systems.
    +
    +    Tactical Application:
    +    - Like intelligence flow in joint operations
    +    - Coordinated data movement
    +    - Quality control
    +    """
    +    def __init__(self):
    +        self.stages = []
    +        self.monitoring = PipelineMonitor()
    +
    +    def add_stage(self, stage):
    +        self.stages.append(stage)
    +
    +    def execute(self, data):
    +        current_data = data
    +        for stage in self.stages:
    +            try:
    +                current_data = stage.process(current_data)
    +                self.monitoring.log_success(stage.name)
    +            except Exception as e:
    +                self.monitoring.log_failure(stage.name, str(e))
    +                raise e
    +
    +        return current_data
    +
    +# Field Implementation
    +class DataStage:
    +    def __init__(self, name, process_fn):
    +        self.name = name
    +        self.process = process_fn
    +
    +pipeline = DataPipeline()
    +pipeline.add_stage(DataStage("extract", extract_fn))
    +pipeline.add_stage(DataStage("transform", transform_fn))
    +
    +

    2. Event-Driven ETL - Intelligence Updates

    +
    class EventDrivenETL:
    +    """
    +    Mission: Process data updates in real-time.
    +
    +    Tactical Application:
    +    - Like real-time intelligence updates
    +    - Immediate data processing
    +    - Automated responses
    +    """
    +    def __init__(self):
    +        self.event_handlers = {}
    +        self.event_queue = Queue()
    +
    +    def register_handler(self, event_type, handler):
    +        self.event_handlers[event_type] = handler
    +
    +    def process_event(self, event):
    +        event_type = event['type']
    +        if event_type in self.event_handlers:
    +            handler = self.event_handlers[event_type]
    +            return handler(event['data'])
    +        else:
    +            raise ValueError(f"No handler for event type: {event_type}")
    +
    +# Field Implementation
    +def intel_update_handler(data):
    +    # Process intelligence update
    +    return processed_data
    +
    +etl = EventDrivenETL()
    +etl.register_handler("intel_update", intel_update_handler)
    +
    +
    +

    Additional Resources

    +

    Training Materials

    + +

    Field Notes

    +
      +
    1. Data operations require strategic planning and tactical execution
    2. +
    3. Always consider:
    4. +
    5. Data quality (intelligence accuracy)
    6. +
    7. Processing efficiency (operational speed)
    8. +
    9. Storage optimization (resource management)
    10. +
    11. Remember: Good data leads to good decisions
    12. +
    +
    +

    "Processing data with military precision" - VetsWhoCode

    + +
    +
    + +
    +
    + +
    + +
    + +
    + + + + « Previous + + + Next » + + +
    + + + + + + + + + diff --git a/fast-api-testing/index.html b/fast-api-testing/index.html index dc997ae..5432188 100644 --- a/fast-api-testing/index.html +++ b/fast-api-testing/index.html @@ -88,6 +88,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/fast-api/index.html b/fast-api/index.html index e874acc..91c4087 100644 --- a/fast-api/index.html +++ b/fast-api/index.html @@ -88,6 +88,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI @@ -472,7 +484,7 @@

    Next Mission Parameters

    @@ -496,7 +508,7 @@

    Next Mission Parameters

    - « Previous + « Previous Next » diff --git a/getting-to-know-the-command-line/index.html b/getting-to-know-the-command-line/index.html index f7110c8..c4a3e18 100644 --- a/getting-to-know-the-command-line/index.html +++ b/getting-to-know-the-command-line/index.html @@ -116,6 +116,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/git-and-github-voice-overview/index.html b/git-and-github-voice-overview/index.html index 0b1578c..73f551f 100644 --- a/git-and-github-voice-overview/index.html +++ b/git-and-github-voice-overview/index.html @@ -92,6 +92,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/git-and-github/index.html b/git-and-github/index.html index 7048eac..507d047 100644 --- a/git-and-github/index.html +++ b/git-and-github/index.html @@ -114,6 +114,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/git-flow/index.html b/git-flow/index.html index 3bd1e11..763b43a 100644 --- a/git-flow/index.html +++ b/git-flow/index.html @@ -130,6 +130,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/github-cli/index.html b/github-cli/index.html index f74a862..0774280 100644 --- a/github-cli/index.html +++ b/github-cli/index.html @@ -144,6 +144,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/index.html b/index.html index 1c31c23..c73ff55 100644 --- a/index.html +++ b/index.html @@ -96,6 +96,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI @@ -274,5 +286,5 @@

    General Guidance: diff --git a/intro-to-python/index.html b/intro-to-python/index.html index 75c7d1a..b0d20cb 100644 --- a/intro-to-python/index.html +++ b/intro-to-python/index.html @@ -134,6 +134,18 @@

  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/search.html b/search.html index fa68a79..01b4a53 100644 --- a/search.html +++ b/search.html @@ -81,6 +81,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/search/search_index.json b/search/search_index.json index 6d0665e..16603e7 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Vets Who Code Engineering Standard Operating Procedures (SOPs) \ud83c\uddfa\ud83c\uddf8 A veteran transitioning into software engineering through Vets Who Code... Has responsibilities to their team \u2013 mentor, coach, and support others Knows their SOPs . Follows their SOPs. Improves their SOPs when needed. Shares knowledge and best practices with others. Leads by example. Models professional excellence both interpersonally and technically. Understands how their work contributes to the larger mission and ensures team success. These are our Standard Operating Procedures for Software Engineering as a Vets Who Code team member. All contributions are welcome! Please feel free to submit a pull request to get involved. Why Have SOPs To increase overall efficiency for the entire Vets Who Code community To reduce common obstacles in the transition to becoming software engineers To learn from shared experiences and help each other grow professionally To establish a consistent, high-quality approach to software development tasks Core Values: Our Guiding Principles \ud83c\uddfa\ud83c\uddf8 Our military service taught us the importance of Integrity, Service, and Excellence. These values continue to guide us as software engineers: Integrity First : The foundation of all we do Write clear, maintainable code that reflects its intended purpose Own your mistakes and grow from them Practice transparency in your work and give credit to others Service Before Self : Your work impacts the entire team Build solutions that benefit the whole organization Support the developer community through open-source contributions Put user needs at the forefront of development decisions Excellence In All We Do : Commit to continuous improvement Regularly evaluate and enhance your code Stay current with industry best practices Share knowledge to elevate the entire team General Guidance: Professional Development Guidelines \ud83c\uddfa\ud83c\uddf8 Maintain high standards through thorough code reviews and testing Prioritize quality over speed - careful planning prevents future issues Focus on one task at a time using GitHub Projects for organization Practice clear communication: Use wikis for documentation Engage in discussions for knowledge sharing Create detailed issues for tracking work Start with simple, effective solutions before adding complexity Respect project scope - create new issues for additional features Deploy updates incrementally and document changes clearly Keep your team informed through regular updates on issues and pull requests Report problems thoroughly with clear reproduction steps and context Take ownership of the codebase - everyone is responsible for quality Leverage automation through GitHub Actions to ensure consistency Use standardized templates to streamline processes Remember: Your military experience has given you valuable skills in leadership, attention to detail, and teamwork. These qualities, combined with technical expertise, make you a valuable asset to any development team. Together, we'll continue serving through technology. Let's show what Vets Who Code can do! \ud83c\uddfa\ud83c\uddf8","title":"Home"},{"location":"#vets-who-code-engineering-standard-operating-procedures-sops","text":"A veteran transitioning into software engineering through Vets Who Code... Has responsibilities to their team \u2013 mentor, coach, and support others Knows their SOPs . Follows their SOPs. Improves their SOPs when needed. Shares knowledge and best practices with others. Leads by example. Models professional excellence both interpersonally and technically. Understands how their work contributes to the larger mission and ensures team success. These are our Standard Operating Procedures for Software Engineering as a Vets Who Code team member. All contributions are welcome! Please feel free to submit a pull request to get involved.","title":"Vets Who Code Engineering Standard Operating Procedures (SOPs) \ud83c\uddfa\ud83c\uddf8"},{"location":"#why-have-sops","text":"To increase overall efficiency for the entire Vets Who Code community To reduce common obstacles in the transition to becoming software engineers To learn from shared experiences and help each other grow professionally To establish a consistent, high-quality approach to software development tasks","title":"Why Have SOPs"},{"location":"#core-values-our-guiding-principles","text":"Our military service taught us the importance of Integrity, Service, and Excellence. These values continue to guide us as software engineers: Integrity First : The foundation of all we do Write clear, maintainable code that reflects its intended purpose Own your mistakes and grow from them Practice transparency in your work and give credit to others Service Before Self : Your work impacts the entire team Build solutions that benefit the whole organization Support the developer community through open-source contributions Put user needs at the forefront of development decisions Excellence In All We Do : Commit to continuous improvement Regularly evaluate and enhance your code Stay current with industry best practices Share knowledge to elevate the entire team","title":"Core Values: Our Guiding Principles \ud83c\uddfa\ud83c\uddf8"},{"location":"#general-guidance-professional-development-guidelines","text":"Maintain high standards through thorough code reviews and testing Prioritize quality over speed - careful planning prevents future issues Focus on one task at a time using GitHub Projects for organization Practice clear communication: Use wikis for documentation Engage in discussions for knowledge sharing Create detailed issues for tracking work Start with simple, effective solutions before adding complexity Respect project scope - create new issues for additional features Deploy updates incrementally and document changes clearly Keep your team informed through regular updates on issues and pull requests Report problems thoroughly with clear reproduction steps and context Take ownership of the codebase - everyone is responsible for quality Leverage automation through GitHub Actions to ensure consistency Use standardized templates to streamline processes Remember: Your military experience has given you valuable skills in leadership, attention to detail, and teamwork. These qualities, combined with technical expertise, make you a valuable asset to any development team. Together, we'll continue serving through technology. Let's show what Vets Who Code can do! \ud83c\uddfa\ud83c\uddf8","title":"General Guidance: Professional Development Guidelines \ud83c\uddfa\ud83c\uddf8"},{"location":"advanced-command-line-features/","text":"Advanced Command Line Features SOP 1. Introduction This Standard Operating Procedure (SOP) outlines advanced command line features and techniques that enhance productivity and efficiency for software engineers, writers, instructors, and other tech professionals. These advanced features include shell scripting basics, environmental variables, aliases and shortcuts, command history manipulation, job control, and task scheduling. 2. Shell Scripting Basics Shell scripting allows for automation of complex tasks and repetitive operations. 2.1 Creating a Shell Script Create a new file with a .sh extension. Add the shebang line at the top: #!/bin/bash Make the script executable: chmod +x script.sh 2.2 Syntax Variables variable_name=value my_var=\"Hello, World\" Conditional Statements if [ \"$variable_one\" -gt \"$variable_two\" ]; then echo \"Variable one is greater\" elif [ \"$variable_one\" -eq \"$variable_two\" ]; then echo \"Variables are equal\" else echo \"Variable two is greater\" fi Loops For Loop: for i in {1..10}; do echo $i done While Loop: count=0 while [ $count -lt 10 ]; do echo $count ((count++)) done 2.3 Structure Shebang #!/bin/bash Functions my_function() { echo \"Hello from my_function!\" } # Call the function my_function 2.4 Best Practices Use consistent indentation (2 or 4 spaces). Comment your code for clarity. Handle errors and check return codes. 2.5 Debugging Basic debugging: bash -x script.sh Advanced debugging: set -e # Exit on first error set -u # Treat unset variables as errors set +e # Continue even if there is an error 3. Environmental Variables Environmental variables store system-wide or user-specific configuration information. 3.1 Setting Variables # Temporary (session only) VARIABLE_NAME=value # Permanent (add to ~/.bashrc or ~/.bash_profile) echo 'export PERMANENT_VAR=\"I'm here to stay!\"' >> ~/.bashrc source ~/.bashrc 3.2 Retrieving Variables echo $VARIABLE_NAME env # List all environment variables 3.3 Exporting Variables export VARIABLE_NAME # Or in one line export VARIABLE_NAME=value 3.4 Unsetting Variables unset VARIABLE_NAME 4. Aliases and Shortcuts Aliases allow you to create custom shortcuts for frequently used commands. 4.1 Creating Aliases # Temporary (session only) alias myalias='my long command here' # Permanent (add to ~/.bashrc or ~/.zshrc) echo \"alias persist='I will survive reboots!'\" >> ~/.bashrc source ~/.bashrc 4.2 Common Aliases alias ll='ls -l' alias la='ls -A' alias ..='cd ..' 4.3 Functions For more complex operations, use functions: myfunc() { echo \"Doing complex stuff!\" } 5. Command History Command history allows you to recall and reuse previously executed commands. 5.1 Navigating History Use Up and Down arrow keys to navigate through history. Ctrl+r : Search backward through history. 5.2 Repeating Commands !! # Repeat the last command !n # Repeat the nth command in history !-n # Repeat the nth last command 5.3 Modifying History history -c # Clear current session's history history -d n # Delete the nth command from history history -a # Manually save session's history 6. Job Control Job control allows management of multiple processes within a single terminal session. 6.1 Background and Foreground Jobs command & # Start a job in the background Ctrl+Z # Pause the current foreground job fg %n # Bring job n to the foreground bg %n # Continue job n in the background 6.2 Listing and Managing Jobs jobs # List all jobs kill %n # Terminate job n 6.3 Signals kill -l # List all available signals kill -SIGSTOP %n # Pause job n kill -SIGCONT %n # Resume job n kill -SIGKILL %n # Forcefully terminate job n 7. Scheduling Tasks The cron utility allows scheduling of recurring tasks. 7.1 Editing the Crontab crontab -e 7.2 Crontab Syntax * * * * * command_to_execute \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2514\u2500\u2500\u2500 day of week (0 - 7) (Sunday = 0 or 7) \u2502 \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500 month (1 - 12) \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 day of month (1 - 31) \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 hour (0 - 23) \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 minute (0 - 59) 7.3 Example Cron Job 0 2 * * * /path/to/backup_script.sh This runs the backup script every day at 2:00 AM. 8. Best Practices Use meaningful names for variables, aliases, and functions. Comment your scripts and complex commands for better readability. Be cautious when modifying system-wide environmental variables. Regularly review and clean up your command history and cron jobs. Use job control judiciously to manage system resources effectively. Test scripts and scheduled tasks thoroughly before implementation. Keep your shell configuration files (e.g., .bashrc, .zshrc) organized and well-commented. Use error handling in your scripts to make them more robust. When working with environmental variables, consider using lowercase for local variables and uppercase for exported variables to maintain clarity. Utilize shell script debugging tools like set -x for troubleshooting. 9. Summary Mastering these advanced command line features significantly enhances your ability to work efficiently in a Unix-like environment. From automating tasks with shell scripts to managing complex job workflows, these tools provide powerful capabilities for system administration, software development, and general productivity. Environmental variables offer a flexible way to configure your system and applications, while shell scripting allows you to automate complex tasks and create powerful utilities. Aliases and shortcuts streamline your workflow, and command history manipulation helps you work more efficiently. Job control gives you fine-grained management of processes, and task scheduling with cron allows for automation of recurring tasks. Regular practice and exploration of these features will continue to improve your command line proficiency. Remember to always consider security implications when working with sensitive data in scripts or environmental variables, and to document your work for future reference and collaboration.","title":"Advanced Command Line Features"},{"location":"advanced-command-line-features/#advanced-command-line-features-sop","text":"","title":"Advanced Command Line Features SOP"},{"location":"advanced-command-line-features/#1-introduction","text":"This Standard Operating Procedure (SOP) outlines advanced command line features and techniques that enhance productivity and efficiency for software engineers, writers, instructors, and other tech professionals. These advanced features include shell scripting basics, environmental variables, aliases and shortcuts, command history manipulation, job control, and task scheduling.","title":"1. Introduction"},{"location":"advanced-command-line-features/#2-shell-scripting-basics","text":"Shell scripting allows for automation of complex tasks and repetitive operations.","title":"2. Shell Scripting Basics"},{"location":"advanced-command-line-features/#21-creating-a-shell-script","text":"Create a new file with a .sh extension. Add the shebang line at the top: #!/bin/bash Make the script executable: chmod +x script.sh","title":"2.1 Creating a Shell Script"},{"location":"advanced-command-line-features/#22-syntax","text":"","title":"2.2 Syntax"},{"location":"advanced-command-line-features/#variables","text":"variable_name=value my_var=\"Hello, World\"","title":"Variables"},{"location":"advanced-command-line-features/#conditional-statements","text":"if [ \"$variable_one\" -gt \"$variable_two\" ]; then echo \"Variable one is greater\" elif [ \"$variable_one\" -eq \"$variable_two\" ]; then echo \"Variables are equal\" else echo \"Variable two is greater\" fi","title":"Conditional Statements"},{"location":"advanced-command-line-features/#loops","text":"For Loop: for i in {1..10}; do echo $i done While Loop: count=0 while [ $count -lt 10 ]; do echo $count ((count++)) done","title":"Loops"},{"location":"advanced-command-line-features/#23-structure","text":"","title":"2.3 Structure"},{"location":"advanced-command-line-features/#shebang","text":"#!/bin/bash","title":"Shebang"},{"location":"advanced-command-line-features/#functions","text":"my_function() { echo \"Hello from my_function!\" } # Call the function my_function","title":"Functions"},{"location":"advanced-command-line-features/#24-best-practices","text":"Use consistent indentation (2 or 4 spaces). Comment your code for clarity. Handle errors and check return codes.","title":"2.4 Best Practices"},{"location":"advanced-command-line-features/#25-debugging","text":"Basic debugging: bash -x script.sh Advanced debugging: set -e # Exit on first error set -u # Treat unset variables as errors set +e # Continue even if there is an error","title":"2.5 Debugging"},{"location":"advanced-command-line-features/#3-environmental-variables","text":"Environmental variables store system-wide or user-specific configuration information.","title":"3. Environmental Variables"},{"location":"advanced-command-line-features/#31-setting-variables","text":"# Temporary (session only) VARIABLE_NAME=value # Permanent (add to ~/.bashrc or ~/.bash_profile) echo 'export PERMANENT_VAR=\"I'm here to stay!\"' >> ~/.bashrc source ~/.bashrc","title":"3.1 Setting Variables"},{"location":"advanced-command-line-features/#32-retrieving-variables","text":"echo $VARIABLE_NAME env # List all environment variables","title":"3.2 Retrieving Variables"},{"location":"advanced-command-line-features/#33-exporting-variables","text":"export VARIABLE_NAME # Or in one line export VARIABLE_NAME=value","title":"3.3 Exporting Variables"},{"location":"advanced-command-line-features/#34-unsetting-variables","text":"unset VARIABLE_NAME","title":"3.4 Unsetting Variables"},{"location":"advanced-command-line-features/#4-aliases-and-shortcuts","text":"Aliases allow you to create custom shortcuts for frequently used commands.","title":"4. Aliases and Shortcuts"},{"location":"advanced-command-line-features/#41-creating-aliases","text":"# Temporary (session only) alias myalias='my long command here' # Permanent (add to ~/.bashrc or ~/.zshrc) echo \"alias persist='I will survive reboots!'\" >> ~/.bashrc source ~/.bashrc","title":"4.1 Creating Aliases"},{"location":"advanced-command-line-features/#42-common-aliases","text":"alias ll='ls -l' alias la='ls -A' alias ..='cd ..'","title":"4.2 Common Aliases"},{"location":"advanced-command-line-features/#43-functions","text":"For more complex operations, use functions: myfunc() { echo \"Doing complex stuff!\" }","title":"4.3 Functions"},{"location":"advanced-command-line-features/#5-command-history","text":"Command history allows you to recall and reuse previously executed commands.","title":"5. Command History"},{"location":"advanced-command-line-features/#51-navigating-history","text":"Use Up and Down arrow keys to navigate through history. Ctrl+r : Search backward through history.","title":"5.1 Navigating History"},{"location":"advanced-command-line-features/#52-repeating-commands","text":"!! # Repeat the last command !n # Repeat the nth command in history !-n # Repeat the nth last command","title":"5.2 Repeating Commands"},{"location":"advanced-command-line-features/#53-modifying-history","text":"history -c # Clear current session's history history -d n # Delete the nth command from history history -a # Manually save session's history","title":"5.3 Modifying History"},{"location":"advanced-command-line-features/#6-job-control","text":"Job control allows management of multiple processes within a single terminal session.","title":"6. Job Control"},{"location":"advanced-command-line-features/#61-background-and-foreground-jobs","text":"command & # Start a job in the background Ctrl+Z # Pause the current foreground job fg %n # Bring job n to the foreground bg %n # Continue job n in the background","title":"6.1 Background and Foreground Jobs"},{"location":"advanced-command-line-features/#62-listing-and-managing-jobs","text":"jobs # List all jobs kill %n # Terminate job n","title":"6.2 Listing and Managing Jobs"},{"location":"advanced-command-line-features/#63-signals","text":"kill -l # List all available signals kill -SIGSTOP %n # Pause job n kill -SIGCONT %n # Resume job n kill -SIGKILL %n # Forcefully terminate job n","title":"6.3 Signals"},{"location":"advanced-command-line-features/#7-scheduling-tasks","text":"The cron utility allows scheduling of recurring tasks.","title":"7. Scheduling Tasks"},{"location":"advanced-command-line-features/#71-editing-the-crontab","text":"crontab -e","title":"7.1 Editing the Crontab"},{"location":"advanced-command-line-features/#72-crontab-syntax","text":"* * * * * command_to_execute \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2514\u2500\u2500\u2500 day of week (0 - 7) (Sunday = 0 or 7) \u2502 \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500 month (1 - 12) \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 day of month (1 - 31) \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 hour (0 - 23) \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 minute (0 - 59)","title":"7.2 Crontab Syntax"},{"location":"advanced-command-line-features/#73-example-cron-job","text":"0 2 * * * /path/to/backup_script.sh This runs the backup script every day at 2:00 AM.","title":"7.3 Example Cron Job"},{"location":"advanced-command-line-features/#8-best-practices","text":"Use meaningful names for variables, aliases, and functions. Comment your scripts and complex commands for better readability. Be cautious when modifying system-wide environmental variables. Regularly review and clean up your command history and cron jobs. Use job control judiciously to manage system resources effectively. Test scripts and scheduled tasks thoroughly before implementation. Keep your shell configuration files (e.g., .bashrc, .zshrc) organized and well-commented. Use error handling in your scripts to make them more robust. When working with environmental variables, consider using lowercase for local variables and uppercase for exported variables to maintain clarity. Utilize shell script debugging tools like set -x for troubleshooting.","title":"8. Best Practices"},{"location":"advanced-command-line-features/#9-summary","text":"Mastering these advanced command line features significantly enhances your ability to work efficiently in a Unix-like environment. From automating tasks with shell scripts to managing complex job workflows, these tools provide powerful capabilities for system administration, software development, and general productivity. Environmental variables offer a flexible way to configure your system and applications, while shell scripting allows you to automate complex tasks and create powerful utilities. Aliases and shortcuts streamline your workflow, and command history manipulation helps you work more efficiently. Job control gives you fine-grained management of processes, and task scheduling with cron allows for automation of recurring tasks. Regular practice and exploration of these features will continue to improve your command line proficiency. Remember to always consider security implications when working with sensitive data in scripts or environmental variables, and to document your work for future reference and collaboration.","title":"9. Summary"},{"location":"advanced-fast-api/","text":"VWC FastAPI Advanced Operations Guide \ud83c\udf96\ufe0f Part 1: Advanced FastAPI Features WebSocket Implementation (Real-time Communications) from fastapi import FastAPI, WebSocket, WebSocketDisconnect from typing import List app = FastAPI() class CommandCenter: def __init__(self): self.active_connections: List[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) command_center = CommandCenter() @app.websocket(\"/ws/mission-updates/{unit_id}\") async def mission_updates(websocket: WebSocket, unit_id: str): await command_center.connect(websocket) try: while True: data = await websocket.receive_text() await command_center.broadcast(f\"Unit {unit_id}: {data}\") except WebSocketDisconnect: command_center.disconnect(websocket) await command_center.broadcast(f\"Unit {unit_id} disconnected\") File Operations with Azure Storage from fastapi import UploadFile, File from azure.storage.blob import BlobServiceClient import os class AzureStorageManager: def __init__(self): conn_str = os.getenv(\"AZURE_STORAGE_CONNECTION_STRING\") self.blob_service_client = BlobServiceClient.from_connection_string(conn_str) self.container_name = \"mission-docs\" async def upload_file(self, file: UploadFile): blob_client = self.blob_service_client.get_blob_client( container=self.container_name, blob=file.filename ) data = await file.read() await blob_client.upload_blob(data) return blob_client.url async def download_file(self, filename: str): blob_client = self.blob_service_client.get_blob_client( container=self.container_name, blob=filename ) return await blob_client.download_blob() storage_manager = AzureStorageManager() @app.post(\"/upload-document/\") async def upload_document(file: UploadFile = File(...)): try: url = await storage_manager.upload_file(file) return {\"status\": \"success\", \"url\": url} except Exception as e: return {\"status\": \"error\", \"message\": str(e)} Rate Limiting from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address limiter = Limiter(key_func=get_remote_address) app = FastAPI() app.state.limiter = limiter app.add_exception_handler(429, _rate_limit_exceeded_handler) @app.get(\"/secure-intel\") @limiter.limit(\"5/minute\") async def get_secure_intel(request: Request): return {\"intel\": \"Classified information\"} Caching with Azure Redis Cache from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache import aioredis @app.on_event(\"startup\") async def startup(): redis = aioredis.from_url( os.getenv(\"AZURE_REDIS_CONNECTION_STRING\"), encoding=\"utf8\" ) FastAPICache.init(RedisBackend(redis), prefix=\"vwc-cache\") @app.get(\"/mission-brief/{mission_id}\") @cache(expire=60) async def get_mission_brief(mission_id: str): return {\"mission_id\": mission_id, \"brief\": \"Mission details...\"} Part 2: Azure Deployment Operations Azure App Service Configuration # config.py from pydantic_settings import BaseSettings class Settings(BaseSettings): APP_NAME: str = \"VWC API\" AZURE_STORAGE_CONNECTION_STRING: str AZURE_REDIS_CONNECTION_STRING: str AZURE_SQL_CONNECTION_STRING: str APPLICATIONINSIGHTS_CONNECTION_STRING: str class Config: env_file = \".env\" Container Registry Setup # Dockerfile FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY ./app ./app CMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"] Azure DevOps Pipeline # azure-pipelines.yml trigger: - main variables: azureSubscription: 'VWC-Azure' containerRegistry: 'vwccontainers.azurecr.io' imageRepository: 'vwc-api' dockerfilePath: 'Dockerfile' tag: '$(Build.BuildId)' stages: - stage: Build jobs: - job: BuildAndTest pool: vmImage: 'ubuntu-latest' steps: - task: Docker@2 inputs: containerRegistry: '$(containerRegistry)' repository: '$(imageRepository)' command: 'buildAndPush' Dockerfile: '$(dockerfilePath)' tags: '$(tag)' - stage: Deploy jobs: - job: Deploy pool: vmImage: 'ubuntu-latest' steps: - task: AzureWebAppContainer@1 inputs: azureSubscription: '$(azureSubscription)' appName: 'vwc-api' containers: '$(containerRegistry)/$(imageRepository):$(tag)' Azure Monitor Integration # monitoring.py from opencensus.ext.azure.trace_exporter import AzureExporter from opencensus.trace.tracer import Tracer from opencensus.trace.samplers import ProbabilitySampler import logging class AzureMonitoring: def __init__(self, connection_string: str): self.tracer = Tracer( exporter=AzureExporter(connection_string=connection_string), sampler=ProbabilitySampler(1.0) ) def track_request(self, name: str): with self.tracer.span(name=name) as span: span.add_attribute(\"service\", \"vwc-api\") return span # Usage in main.py monitoring = AzureMonitoring(os.getenv(\"APPLICATIONINSIGHTS_CONNECTION_STRING\")) @app.middleware(\"http\") async def monitoring_middleware(request: Request, call_next): with monitoring.track_request(f\"{request.method} {request.url.path}\"): response = await call_next(request) return response Azure Key Vault Integration # security.py from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential class SecureConfig: def __init__(self): credential = DefaultAzureCredential() vault_url = os.getenv(\"AZURE_KEYVAULT_URL\") self.client = SecretClient(vault_url=vault_url, credential=credential) def get_secret(self, name: str) -> str: return self.client.get_secret(name).value # Usage secure_config = SecureConfig() db_password = secure_config.get_secret(\"database-password\") Production Configuration # production.py from azure.identity import DefaultAzureCredential from fastapi.middleware.cors import CORSMiddleware def configure_production(app: FastAPI): # CORS configuration app.add_middleware( CORSMiddleware, allow_origins=[\"https://*.azurewebsites.net\"], allow_credentials=True, allow_methods=[\"*\"], allow_headers=[\"*\"], ) # Azure authentication credential = DefaultAzureCredential() # Health check endpoint @app.get(\"/health\") async def health_check(): return {\"status\": \"healthy\", \"environment\": \"azure-production\"} Field Exercise: Complete Azure-Deployed API Here's a complete example combining these concepts: # main.py from fastapi import FastAPI, Depends, HTTPException, Request from azure.identity import DefaultAzureCredential from azure.storage.blob import BlobServiceClient from azure.keyvault.secrets import SecretClient import logging class AzureAPI: def __init__(self): self.app = FastAPI(title=\"VWC Mission Control\") self.credential = DefaultAzureCredential() self.setup_azure_services() self.setup_routes() self.setup_monitoring() def setup_azure_services(self): # Key Vault setup vault_url = os.getenv(\"AZURE_KEYVAULT_URL\") self.key_vault = SecretClient( vault_url=vault_url, credential=self.credential ) # Blob storage setup storage_connection = self.key_vault.get_secret(\"storage-connection\").value self.blob_service = BlobServiceClient.from_connection_string(storage_connection) def setup_monitoring(self): connection_string = self.key_vault.get_secret(\"appinsights-connection\").value self.monitoring = AzureMonitoring(connection_string) def setup_routes(self): @self.app.get(\"/\") async def root(): return {\"status\": \"operational\", \"service\": \"VWC API\"} @self.app.post(\"/documents/\") async def upload_document(file: UploadFile = File(...)): try: container_client = self.blob_service.get_container_client(\"documents\") blob_client = container_client.get_blob_client(file.filename) data = await file.read() await blob_client.upload_blob(data) return {\"status\": \"success\", \"url\": blob_client.url} except Exception as e: logging.error(f\"Upload failed: {str(e)}\") raise HTTPException(status_code=500, detail=str(e)) # Initialize application azure_api = AzureAPI() app = azure_api.app Deployment Commands # Login to Azure az login # Create resource group az group create --name vwc-resources --location eastus # Create App Service plan az appservice plan create \\ --name vwc-service-plan \\ --resource-group vwc-resources \\ --sku B1 \\ --is-linux # Create Web App az webapp create \\ --resource-group vwc-resources \\ --plan vwc-service-plan \\ --name vwc-fastapi-app \\ --runtime \"PYTHON:3.9\" # Configure deployment az webapp config appsettings set \\ --resource-group vwc-resources \\ --name vwc-fastapi-app \\ --settings \\ WEBSITES_PORT=8000 \\ SCM_DO_BUILD_DURING_DEPLOYMENT=true Next Mission Parameters Advanced Azure Features: Azure Functions integration Azure API Management Azure Front Door setup Virtual Networks configuration Security Hardening: Managed Identities Role-Based Access Control Network Security Groups Web Application Firewall Remember: Monitor your resources Set up proper logging Configure automated backups Use managed identities Follow least privilege principle \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Advanced FastAPI"},{"location":"advanced-fast-api/#vwc-fastapi-advanced-operations-guide","text":"","title":"VWC FastAPI Advanced Operations Guide \ud83c\udf96\ufe0f"},{"location":"advanced-fast-api/#part-1-advanced-fastapi-features","text":"","title":"Part 1: Advanced FastAPI Features"},{"location":"advanced-fast-api/#websocket-implementation-real-time-communications","text":"from fastapi import FastAPI, WebSocket, WebSocketDisconnect from typing import List app = FastAPI() class CommandCenter: def __init__(self): self.active_connections: List[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) command_center = CommandCenter() @app.websocket(\"/ws/mission-updates/{unit_id}\") async def mission_updates(websocket: WebSocket, unit_id: str): await command_center.connect(websocket) try: while True: data = await websocket.receive_text() await command_center.broadcast(f\"Unit {unit_id}: {data}\") except WebSocketDisconnect: command_center.disconnect(websocket) await command_center.broadcast(f\"Unit {unit_id} disconnected\")","title":"WebSocket Implementation (Real-time Communications)"},{"location":"advanced-fast-api/#file-operations-with-azure-storage","text":"from fastapi import UploadFile, File from azure.storage.blob import BlobServiceClient import os class AzureStorageManager: def __init__(self): conn_str = os.getenv(\"AZURE_STORAGE_CONNECTION_STRING\") self.blob_service_client = BlobServiceClient.from_connection_string(conn_str) self.container_name = \"mission-docs\" async def upload_file(self, file: UploadFile): blob_client = self.blob_service_client.get_blob_client( container=self.container_name, blob=file.filename ) data = await file.read() await blob_client.upload_blob(data) return blob_client.url async def download_file(self, filename: str): blob_client = self.blob_service_client.get_blob_client( container=self.container_name, blob=filename ) return await blob_client.download_blob() storage_manager = AzureStorageManager() @app.post(\"/upload-document/\") async def upload_document(file: UploadFile = File(...)): try: url = await storage_manager.upload_file(file) return {\"status\": \"success\", \"url\": url} except Exception as e: return {\"status\": \"error\", \"message\": str(e)}","title":"File Operations with Azure Storage"},{"location":"advanced-fast-api/#rate-limiting","text":"from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address limiter = Limiter(key_func=get_remote_address) app = FastAPI() app.state.limiter = limiter app.add_exception_handler(429, _rate_limit_exceeded_handler) @app.get(\"/secure-intel\") @limiter.limit(\"5/minute\") async def get_secure_intel(request: Request): return {\"intel\": \"Classified information\"}","title":"Rate Limiting"},{"location":"advanced-fast-api/#caching-with-azure-redis-cache","text":"from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache import aioredis @app.on_event(\"startup\") async def startup(): redis = aioredis.from_url( os.getenv(\"AZURE_REDIS_CONNECTION_STRING\"), encoding=\"utf8\" ) FastAPICache.init(RedisBackend(redis), prefix=\"vwc-cache\") @app.get(\"/mission-brief/{mission_id}\") @cache(expire=60) async def get_mission_brief(mission_id: str): return {\"mission_id\": mission_id, \"brief\": \"Mission details...\"}","title":"Caching with Azure Redis Cache"},{"location":"advanced-fast-api/#part-2-azure-deployment-operations","text":"","title":"Part 2: Azure Deployment Operations"},{"location":"advanced-fast-api/#azure-app-service-configuration","text":"# config.py from pydantic_settings import BaseSettings class Settings(BaseSettings): APP_NAME: str = \"VWC API\" AZURE_STORAGE_CONNECTION_STRING: str AZURE_REDIS_CONNECTION_STRING: str AZURE_SQL_CONNECTION_STRING: str APPLICATIONINSIGHTS_CONNECTION_STRING: str class Config: env_file = \".env\"","title":"Azure App Service Configuration"},{"location":"advanced-fast-api/#container-registry-setup","text":"# Dockerfile FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY ./app ./app CMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]","title":"Container Registry Setup"},{"location":"advanced-fast-api/#azure-devops-pipeline","text":"# azure-pipelines.yml trigger: - main variables: azureSubscription: 'VWC-Azure' containerRegistry: 'vwccontainers.azurecr.io' imageRepository: 'vwc-api' dockerfilePath: 'Dockerfile' tag: '$(Build.BuildId)' stages: - stage: Build jobs: - job: BuildAndTest pool: vmImage: 'ubuntu-latest' steps: - task: Docker@2 inputs: containerRegistry: '$(containerRegistry)' repository: '$(imageRepository)' command: 'buildAndPush' Dockerfile: '$(dockerfilePath)' tags: '$(tag)' - stage: Deploy jobs: - job: Deploy pool: vmImage: 'ubuntu-latest' steps: - task: AzureWebAppContainer@1 inputs: azureSubscription: '$(azureSubscription)' appName: 'vwc-api' containers: '$(containerRegistry)/$(imageRepository):$(tag)'","title":"Azure DevOps Pipeline"},{"location":"advanced-fast-api/#azure-monitor-integration","text":"# monitoring.py from opencensus.ext.azure.trace_exporter import AzureExporter from opencensus.trace.tracer import Tracer from opencensus.trace.samplers import ProbabilitySampler import logging class AzureMonitoring: def __init__(self, connection_string: str): self.tracer = Tracer( exporter=AzureExporter(connection_string=connection_string), sampler=ProbabilitySampler(1.0) ) def track_request(self, name: str): with self.tracer.span(name=name) as span: span.add_attribute(\"service\", \"vwc-api\") return span # Usage in main.py monitoring = AzureMonitoring(os.getenv(\"APPLICATIONINSIGHTS_CONNECTION_STRING\")) @app.middleware(\"http\") async def monitoring_middleware(request: Request, call_next): with monitoring.track_request(f\"{request.method} {request.url.path}\"): response = await call_next(request) return response","title":"Azure Monitor Integration"},{"location":"advanced-fast-api/#azure-key-vault-integration","text":"# security.py from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential class SecureConfig: def __init__(self): credential = DefaultAzureCredential() vault_url = os.getenv(\"AZURE_KEYVAULT_URL\") self.client = SecretClient(vault_url=vault_url, credential=credential) def get_secret(self, name: str) -> str: return self.client.get_secret(name).value # Usage secure_config = SecureConfig() db_password = secure_config.get_secret(\"database-password\")","title":"Azure Key Vault Integration"},{"location":"advanced-fast-api/#production-configuration","text":"# production.py from azure.identity import DefaultAzureCredential from fastapi.middleware.cors import CORSMiddleware def configure_production(app: FastAPI): # CORS configuration app.add_middleware( CORSMiddleware, allow_origins=[\"https://*.azurewebsites.net\"], allow_credentials=True, allow_methods=[\"*\"], allow_headers=[\"*\"], ) # Azure authentication credential = DefaultAzureCredential() # Health check endpoint @app.get(\"/health\") async def health_check(): return {\"status\": \"healthy\", \"environment\": \"azure-production\"}","title":"Production Configuration"},{"location":"advanced-fast-api/#field-exercise-complete-azure-deployed-api","text":"Here's a complete example combining these concepts: # main.py from fastapi import FastAPI, Depends, HTTPException, Request from azure.identity import DefaultAzureCredential from azure.storage.blob import BlobServiceClient from azure.keyvault.secrets import SecretClient import logging class AzureAPI: def __init__(self): self.app = FastAPI(title=\"VWC Mission Control\") self.credential = DefaultAzureCredential() self.setup_azure_services() self.setup_routes() self.setup_monitoring() def setup_azure_services(self): # Key Vault setup vault_url = os.getenv(\"AZURE_KEYVAULT_URL\") self.key_vault = SecretClient( vault_url=vault_url, credential=self.credential ) # Blob storage setup storage_connection = self.key_vault.get_secret(\"storage-connection\").value self.blob_service = BlobServiceClient.from_connection_string(storage_connection) def setup_monitoring(self): connection_string = self.key_vault.get_secret(\"appinsights-connection\").value self.monitoring = AzureMonitoring(connection_string) def setup_routes(self): @self.app.get(\"/\") async def root(): return {\"status\": \"operational\", \"service\": \"VWC API\"} @self.app.post(\"/documents/\") async def upload_document(file: UploadFile = File(...)): try: container_client = self.blob_service.get_container_client(\"documents\") blob_client = container_client.get_blob_client(file.filename) data = await file.read() await blob_client.upload_blob(data) return {\"status\": \"success\", \"url\": blob_client.url} except Exception as e: logging.error(f\"Upload failed: {str(e)}\") raise HTTPException(status_code=500, detail=str(e)) # Initialize application azure_api = AzureAPI() app = azure_api.app","title":"Field Exercise: Complete Azure-Deployed API"},{"location":"advanced-fast-api/#deployment-commands","text":"# Login to Azure az login # Create resource group az group create --name vwc-resources --location eastus # Create App Service plan az appservice plan create \\ --name vwc-service-plan \\ --resource-group vwc-resources \\ --sku B1 \\ --is-linux # Create Web App az webapp create \\ --resource-group vwc-resources \\ --plan vwc-service-plan \\ --name vwc-fastapi-app \\ --runtime \"PYTHON:3.9\" # Configure deployment az webapp config appsettings set \\ --resource-group vwc-resources \\ --name vwc-fastapi-app \\ --settings \\ WEBSITES_PORT=8000 \\ SCM_DO_BUILD_DURING_DEPLOYMENT=true","title":"Deployment Commands"},{"location":"advanced-fast-api/#next-mission-parameters","text":"Advanced Azure Features: Azure Functions integration Azure API Management Azure Front Door setup Virtual Networks configuration Security Hardening: Managed Identities Role-Based Access Control Network Security Groups Web Application Firewall Remember: Monitor your resources Set up proper logging Configure automated backups Use managed identities Follow least privilege principle \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Next Mission Parameters"},{"location":"advanced-python-operations/","text":"Vets Who Code - Advanced Python Operations \ud83c\udf96\ufe0f Phase 1: Battle Drills (Functions) Basic Function Structure def call_sign_generator(last_name, unit): \"\"\" Docstring: Like a mission brief, explains the function's purpose Args: last_name: String of operator's last name unit: String of unit designation Returns: String: Generated call sign \"\"\" return f\"VIPER_{last_name.upper()}_{unit}\" # Using the function operator_call_sign = call_sign_generator(\"Smith\", \"PYTHON\") print(operator_call_sign) # Output: VIPER_SMITH_PYTHON Function Parameters (Loading Combat Gear) # Default Parameters def create_fire_team(team_leader, size=4, designation=\"Alpha\"): return f\"Team {designation}: {size} operators led by {team_leader}\" # Multiple Parameters def mission_brief(date, time, location, *objectives, **support_units): \"\"\" *objectives: Variable args (tuple) for multiple mission objectives **support_units: Keyword args (dict) for support elements \"\"\" brief = f\"Mission Date: {date} at {time}\\nLocation: {location}\\n\" brief += \"\\nObjectives:\\n\" for obj in objectives: brief += f\"- {obj}\\n\" brief += \"\\nSupport Units:\\n\" for unit, role in support_units.items(): brief += f\"- {unit}: {role}\\n\" return brief # Using complex function brief = mission_brief(\"2024-11-10\", \"0600\", \"Grid Alpha-7\", \"Secure Perimeter\", \"Establish Comms\", \"Deploy Assets\", air_support=\"Close Air Support\", medical=\"Combat Medic Team\") Phase 2: Combat Contingencies (Error Handling) Basic Error Handling def check_ammunition(mag_count): try: if not isinstance(mag_count, int): raise TypeError(\"Magazine count must be a number\") if mag_count < 0: raise ValueError(\"Magazine count cannot be negative\") if mag_count < 3: print(\"Low ammunition warning!\") return f\"Ammunition check: {mag_count} magazines\" except TypeError as e: return f\"Error in ammunition count: {e}\" except ValueError as e: return f\"Invalid ammunition count: {e}\" except Exception as e: return f\"Unknown error in ammunition check: {e}\" finally: print(\"Ammunition check complete\") Custom Exceptions class MissionCriticalError(Exception): \"\"\"Custom exception for mission-critical failures\"\"\" pass def verify_comms(signal_strength): try: if signal_strength < 50: raise MissionCriticalError(\"Communications signal too weak\") return \"Communications operational\" except MissionCriticalError as e: return f\"MISSION CRITICAL: {e}\" Phase 3: Mission Logs (File Operations) Basic File Operations # Writing mission logs def write_mission_log(mission_id, details): try: with open(f\"mission_{mission_id}.log\", \"w\") as log_file: log_file.write(f\"Mission ID: {mission_id}\\n\") log_file.write(f\"Timestamp: {datetime.now()}\\n\") log_file.write(\"Details:\\n\") log_file.write(details) except IOError as e: print(f\"Error writing mission log: {e}\") # Reading mission logs def read_mission_log(mission_id): try: with open(f\"mission_{mission_id}.log\", \"r\") as log_file: return log_file.read() except FileNotFoundError: return \"Mission log not found\" CSV Operations (Personnel Records) import csv def log_personnel_data(filename, personnel_list): with open(filename, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['id', 'name', 'rank', 'unit']) writer.writeheader() for person in personnel_list: writer.writerow(person) def read_personnel_data(filename): with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile) return list(reader) Phase 4: Unit Organization (Classes) Basic Class Structure class MilitaryUnit: def __init__(self, designation, strength, location): self.designation = designation self.strength = strength self.location = location self.status = \"Active\" def deploy(self, new_location): self.location = new_location return f\"{self.designation} deployed to {new_location}\" def report_status(self): return f\"Unit: {self.designation}\\nStrength: {self.strength}\\nLocation: {self.location}\\nStatus: {self.status}\" # Using the class alpha_team = MilitaryUnit(\"Alpha\", 12, \"Base\") print(alpha_team.deploy(\"Grid Bravo-7\")) print(alpha_team.report_status()) Inheritance (Specialized Units) class SpecialOperationsUnit(MilitaryUnit): def __init__(self, designation, strength, location, specialty): super().__init__(designation, strength, location) self.specialty = specialty self.deployed = False def conduct_operation(self, operation_type): if operation_type == self.specialty: return f\"Conducting {operation_type} operation with {self.strength} operators\" return f\"Operation type mismatch with unit specialty\" # Using inherited class delta_force = SpecialOperationsUnit(\"Delta\", 8, \"Classified\", \"Direct Action\") print(delta_force.conduct_operation(\"Direct Action\")) Phase 5: Support Elements (Modules) Creating Custom Modules # mission_utils.py def generate_grid_reference(x, y): return f\"GRID_{x}{y}\" def calculate_bearing(start, end): # Complex bearing calculation logic here pass # Using modules from mission_utils import generate_grid_reference grid = generate_grid_reference(5, 8) Module Organization # Project structure military_ops/ __init__.py personnel/ __init__.py roster.py qualifications.py operations/ __init__.py mission_planning.py logistics.py utils/ __init__.py grid_calc.py comms.py Field Exercise: Combined Arms Operation Let's combine all these concepts in a practical exercise - a Mission Planning System: class MissionPlanningSystem: def __init__(self): self.missions = {} self.units = {} self.logs = [] def plan_mission(self, mission_id, objective): try: if mission_id in self.missions: raise ValueError(\"Mission ID already exists\") mission = { \"id\": mission_id, \"objective\": objective, \"status\": \"Planning\", \"units\": [] } self.missions[mission_id] = mission self._log_event(f\"Mission {mission_id} created\") return \"Mission created successfully\" except Exception as e: self._log_event(f\"Error creating mission: {e}\") raise def assign_unit(self, mission_id, unit): if mission_id in self.missions: self.missions[mission_id][\"units\"].append(unit) self._log_event(f\"Unit {unit.designation} assigned to mission {mission_id}\") def _log_event(self, event): timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") log_entry = f\"[{timestamp}] {event}\" self.logs.append(log_entry) # Write to file with open(\"mission_logs.txt\", \"a\") as f: f.write(log_entry + \"\\n\") # Using the system mps = MissionPlanningSystem() alpha = MilitaryUnit(\"Alpha\", 10, \"Base\") try: mps.plan_mission(\"OPS001\", \"Secure Objective Bravo\") mps.assign_unit(\"OPS001\", alpha) except Exception as e: print(f\"Mission planning failed: {e}\") Movement Orders (Next Steps) Practice implementing these concepts with your own scenarios Build a complete project combining multiple concepts Learn about: Testing (Mission Rehearsal) Debugging (Equipment Checks) Advanced OOP concepts (Unit Organization) API integration (Joint Operations) Remember: Code with discipline Document thoroughly Test rigorously Stay mission-focused \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode Need clarification on any operations or ready for specific exercises?","title":"Advanced Python Operations"},{"location":"advanced-python-operations/#vets-who-code-advanced-python-operations","text":"","title":"Vets Who Code - Advanced Python Operations \ud83c\udf96\ufe0f"},{"location":"advanced-python-operations/#phase-1-battle-drills-functions","text":"","title":"Phase 1: Battle Drills (Functions)"},{"location":"advanced-python-operations/#basic-function-structure","text":"def call_sign_generator(last_name, unit): \"\"\" Docstring: Like a mission brief, explains the function's purpose Args: last_name: String of operator's last name unit: String of unit designation Returns: String: Generated call sign \"\"\" return f\"VIPER_{last_name.upper()}_{unit}\" # Using the function operator_call_sign = call_sign_generator(\"Smith\", \"PYTHON\") print(operator_call_sign) # Output: VIPER_SMITH_PYTHON","title":"Basic Function Structure"},{"location":"advanced-python-operations/#function-parameters-loading-combat-gear","text":"# Default Parameters def create_fire_team(team_leader, size=4, designation=\"Alpha\"): return f\"Team {designation}: {size} operators led by {team_leader}\" # Multiple Parameters def mission_brief(date, time, location, *objectives, **support_units): \"\"\" *objectives: Variable args (tuple) for multiple mission objectives **support_units: Keyword args (dict) for support elements \"\"\" brief = f\"Mission Date: {date} at {time}\\nLocation: {location}\\n\" brief += \"\\nObjectives:\\n\" for obj in objectives: brief += f\"- {obj}\\n\" brief += \"\\nSupport Units:\\n\" for unit, role in support_units.items(): brief += f\"- {unit}: {role}\\n\" return brief # Using complex function brief = mission_brief(\"2024-11-10\", \"0600\", \"Grid Alpha-7\", \"Secure Perimeter\", \"Establish Comms\", \"Deploy Assets\", air_support=\"Close Air Support\", medical=\"Combat Medic Team\")","title":"Function Parameters (Loading Combat Gear)"},{"location":"advanced-python-operations/#phase-2-combat-contingencies-error-handling","text":"","title":"Phase 2: Combat Contingencies (Error Handling)"},{"location":"advanced-python-operations/#basic-error-handling","text":"def check_ammunition(mag_count): try: if not isinstance(mag_count, int): raise TypeError(\"Magazine count must be a number\") if mag_count < 0: raise ValueError(\"Magazine count cannot be negative\") if mag_count < 3: print(\"Low ammunition warning!\") return f\"Ammunition check: {mag_count} magazines\" except TypeError as e: return f\"Error in ammunition count: {e}\" except ValueError as e: return f\"Invalid ammunition count: {e}\" except Exception as e: return f\"Unknown error in ammunition check: {e}\" finally: print(\"Ammunition check complete\")","title":"Basic Error Handling"},{"location":"advanced-python-operations/#custom-exceptions","text":"class MissionCriticalError(Exception): \"\"\"Custom exception for mission-critical failures\"\"\" pass def verify_comms(signal_strength): try: if signal_strength < 50: raise MissionCriticalError(\"Communications signal too weak\") return \"Communications operational\" except MissionCriticalError as e: return f\"MISSION CRITICAL: {e}\"","title":"Custom Exceptions"},{"location":"advanced-python-operations/#phase-3-mission-logs-file-operations","text":"","title":"Phase 3: Mission Logs (File Operations)"},{"location":"advanced-python-operations/#basic-file-operations","text":"# Writing mission logs def write_mission_log(mission_id, details): try: with open(f\"mission_{mission_id}.log\", \"w\") as log_file: log_file.write(f\"Mission ID: {mission_id}\\n\") log_file.write(f\"Timestamp: {datetime.now()}\\n\") log_file.write(\"Details:\\n\") log_file.write(details) except IOError as e: print(f\"Error writing mission log: {e}\") # Reading mission logs def read_mission_log(mission_id): try: with open(f\"mission_{mission_id}.log\", \"r\") as log_file: return log_file.read() except FileNotFoundError: return \"Mission log not found\"","title":"Basic File Operations"},{"location":"advanced-python-operations/#csv-operations-personnel-records","text":"import csv def log_personnel_data(filename, personnel_list): with open(filename, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['id', 'name', 'rank', 'unit']) writer.writeheader() for person in personnel_list: writer.writerow(person) def read_personnel_data(filename): with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile) return list(reader)","title":"CSV Operations (Personnel Records)"},{"location":"advanced-python-operations/#phase-4-unit-organization-classes","text":"","title":"Phase 4: Unit Organization (Classes)"},{"location":"advanced-python-operations/#basic-class-structure","text":"class MilitaryUnit: def __init__(self, designation, strength, location): self.designation = designation self.strength = strength self.location = location self.status = \"Active\" def deploy(self, new_location): self.location = new_location return f\"{self.designation} deployed to {new_location}\" def report_status(self): return f\"Unit: {self.designation}\\nStrength: {self.strength}\\nLocation: {self.location}\\nStatus: {self.status}\" # Using the class alpha_team = MilitaryUnit(\"Alpha\", 12, \"Base\") print(alpha_team.deploy(\"Grid Bravo-7\")) print(alpha_team.report_status())","title":"Basic Class Structure"},{"location":"advanced-python-operations/#inheritance-specialized-units","text":"class SpecialOperationsUnit(MilitaryUnit): def __init__(self, designation, strength, location, specialty): super().__init__(designation, strength, location) self.specialty = specialty self.deployed = False def conduct_operation(self, operation_type): if operation_type == self.specialty: return f\"Conducting {operation_type} operation with {self.strength} operators\" return f\"Operation type mismatch with unit specialty\" # Using inherited class delta_force = SpecialOperationsUnit(\"Delta\", 8, \"Classified\", \"Direct Action\") print(delta_force.conduct_operation(\"Direct Action\"))","title":"Inheritance (Specialized Units)"},{"location":"advanced-python-operations/#phase-5-support-elements-modules","text":"","title":"Phase 5: Support Elements (Modules)"},{"location":"advanced-python-operations/#creating-custom-modules","text":"# mission_utils.py def generate_grid_reference(x, y): return f\"GRID_{x}{y}\" def calculate_bearing(start, end): # Complex bearing calculation logic here pass # Using modules from mission_utils import generate_grid_reference grid = generate_grid_reference(5, 8)","title":"Creating Custom Modules"},{"location":"advanced-python-operations/#module-organization","text":"# Project structure military_ops/ __init__.py personnel/ __init__.py roster.py qualifications.py operations/ __init__.py mission_planning.py logistics.py utils/ __init__.py grid_calc.py comms.py","title":"Module Organization"},{"location":"advanced-python-operations/#field-exercise-combined-arms-operation","text":"Let's combine all these concepts in a practical exercise - a Mission Planning System: class MissionPlanningSystem: def __init__(self): self.missions = {} self.units = {} self.logs = [] def plan_mission(self, mission_id, objective): try: if mission_id in self.missions: raise ValueError(\"Mission ID already exists\") mission = { \"id\": mission_id, \"objective\": objective, \"status\": \"Planning\", \"units\": [] } self.missions[mission_id] = mission self._log_event(f\"Mission {mission_id} created\") return \"Mission created successfully\" except Exception as e: self._log_event(f\"Error creating mission: {e}\") raise def assign_unit(self, mission_id, unit): if mission_id in self.missions: self.missions[mission_id][\"units\"].append(unit) self._log_event(f\"Unit {unit.designation} assigned to mission {mission_id}\") def _log_event(self, event): timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") log_entry = f\"[{timestamp}] {event}\" self.logs.append(log_entry) # Write to file with open(\"mission_logs.txt\", \"a\") as f: f.write(log_entry + \"\\n\") # Using the system mps = MissionPlanningSystem() alpha = MilitaryUnit(\"Alpha\", 10, \"Base\") try: mps.plan_mission(\"OPS001\", \"Secure Objective Bravo\") mps.assign_unit(\"OPS001\", alpha) except Exception as e: print(f\"Mission planning failed: {e}\")","title":"Field Exercise: Combined Arms Operation"},{"location":"advanced-python-operations/#movement-orders-next-steps","text":"Practice implementing these concepts with your own scenarios Build a complete project combining multiple concepts Learn about: Testing (Mission Rehearsal) Debugging (Equipment Checks) Advanced OOP concepts (Unit Organization) API integration (Joint Operations) Remember: Code with discipline Document thoroughly Test rigorously Stay mission-focused \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode Need clarification on any operations or ready for specific exercises?","title":"Movement Orders (Next Steps)"},{"location":"advanced-streamlit/","text":"Vets Who Code: Advanced Streamlit Development Taking Your Streamlit Apps to the Next Level \ud83c\udfaf Advanced Learning Objectives After completing this lesson, you will be able to: Deploy applications to Streamlit Cloud Create custom Streamlit components Implement secure authentication Build responsive layouts Create advanced data visualizations \ud83d\udcda Lesson 1: Streamlit Cloud Deployment Local Setup for Deployment Create requirements.txt : streamlit==1.31.0 pandas==2.0.3 numpy==1.24.3 python-dotenv==1.0.0 Create .gitignore : venv/ .env __pycache__/ *.pyc .DS_Store Create config.toml in .streamlit folder: [theme] primaryColor = \"#D6372E\" # VWC Red backgroundColor = \"#FFFFFF\" secondaryBackgroundColor = \"#F0F2F6\" textColor = \"#262730\" font = \"sans serif\" [server] maxUploadSize = 200 enableXsrfProtection = true Deployment Steps Push to GitHub: git init git add . git commit -m \"Initial commit\" git remote add origin your-repo-url git push -u origin main Streamlit Cloud Setup: Visit streamlit.io/cloud Connect your GitHub repository Select main file Add secrets in dashboard Deploy \ud83d\udcda Lesson 2: Custom Components Basic Custom Component Create custom_components.py : import streamlit as st import streamlit.components.v1 as components def custom_html_component(): components.html( \"\"\"

    Custom HTML Component

    This is a custom component using HTML and JavaScript.

    \"\"\", height=200 ) def custom_chart_component(): components.html( \"\"\"
    \"\"\", height=400 ) # Usage st.title(\"Custom Components Demo\") custom_html_component() custom_chart_component() \ud83d\udcda Lesson 3: Authentication & Security Basic Authentication Create auth.py : import streamlit as st import hmac import hashlib from datetime import datetime, timedelta class Authenticator: def __init__(self): if 'authenticated' not in st.session_state: st.session_state.authenticated = False st.session_state.auth_time = None def _hash_password(self, password: str) -> str: return hashlib.sha256(password.encode()).hexdigest() def _check_password(self, username: str, password: str) -> bool: # Replace with database lookup in production users = { \"demo\": self._hash_password(\"demo123\") } return username in users and users[username] == self._hash_password(password) def login_form(self): if not st.session_state.authenticated: st.title(\"Login\") with st.form(\"login_form\"): username = st.text_input(\"Username\") password = st.text_input(\"Password\", type=\"password\") submitted = st.form_submit_button(\"Login\") if submitted: if self._check_password(username, password): st.session_state.authenticated = True st.session_state.auth_time = datetime.now() st.experimental_rerun() else: st.error(\"Invalid credentials\") return st.session_state.authenticated # Usage example auth = Authenticator() if auth.login_form(): st.write(\"Welcome to the secure area!\") \ud83d\udcda Lesson 4: Responsive Design Responsive Layout Example Create responsive.py : import streamlit as st def get_device_type(): # Basic device detection using viewport width # Note: This is a simplified approach return st.select_slider( \"Preview as:\", options=[\"Mobile\", \"Tablet\", \"Desktop\"], value=\"Desktop\", key=\"device_type\" ) st.title(\"Responsive Design Demo\") device = get_device_type() # Responsive layout based on device if device == \"Mobile\": # Single column layout st.write(\"Mobile Layout\") st.image(\"https://via.placeholder.com/300x200\") st.write(\"Content below image\") elif device == \"Tablet\": # Two column layout col1, col2 = st.columns([1, 1]) with col1: st.write(\"Tablet Layout - Left\") st.image(\"https://via.placeholder.com/400x300\") with col2: st.write(\"Tablet Layout - Right\") st.write(\"Content next to image\") else: # Desktop # Three column layout col1, col2, col3 = st.columns([1, 2, 1]) with col1: st.write(\"Sidebar content\") with col2: st.write(\"Desktop Layout - Main\") st.image(\"https://via.placeholder.com/800x400\") with col3: st.write(\"Additional content\") # Responsive CSS st.markdown(\"\"\" \"\"\", unsafe_allow_html=True) \ud83d\udcda Lesson 5: Advanced Visualizations Interactive Dashboard Create advanced_viz.py : import streamlit as st import pandas as pd import plotly.express as px import plotly.graph_objects as go from datetime import datetime, timedelta # Generate sample data def generate_data(): dates = pd.date_range( start=datetime.now() - timedelta(days=30), end=datetime.now(), freq='D' ) df = pd.DataFrame({ 'date': dates, 'users': np.random.randint(100, 1000, size=len(dates)), 'revenue': np.random.uniform(1000, 5000, size=len(dates)), 'conversion': np.random.uniform(0.1, 0.3, size=len(dates)) }) return df # Create interactive visualizations def create_dashboard(): st.title(\"Advanced Analytics Dashboard\") # Load data df = generate_data() # Date filter date_range = st.date_input( \"Select Date Range\", value=(df['date'].min(), df['date'].max()), key=\"date_range\" ) # Filter data mask = (df['date'].dt.date >= date_range[0]) & (df['date'].dt.date <= date_range[1]) filtered_df = df[mask] # Metrics row col1, col2, col3 = st.columns(3) with col1: st.metric( \"Total Users\", f\"{filtered_df['users'].sum():,.0f}\", f\"{filtered_df['users'].diff().mean():+.1f}/day\" ) with col2: st.metric( \"Total Revenue\", f\"${filtered_df['revenue'].sum():,.2f}\", f\"{filtered_df['revenue'].pct_change().mean()*100:+.1f}%\" ) with col3: st.metric( \"Avg Conversion\", f\"{filtered_df['conversion'].mean()*100:.1f}%\", f\"{filtered_df['conversion'].diff().mean()*100:+.2f}pp\" ) # Interactive charts tab1, tab2 = st.tabs([\"Time Series\", \"Analysis\"]) with tab1: # Create time series chart fig = go.Figure() fig.add_trace(go.Scatter( x=filtered_df['date'], y=filtered_df['users'], name=\"Users\", line=dict(color=\"#D6372E\") )) fig.add_trace(go.Scatter( x=filtered_df['date'], y=filtered_df['revenue'], name=\"Revenue\", yaxis=\"y2\" )) fig.update_layout( title=\"Users and Revenue Over Time\", yaxis=dict(title=\"Users\"), yaxis2=dict(title=\"Revenue\", overlaying=\"y\", side=\"right\"), hovermode=\"x unified\" ) st.plotly_chart(fig, use_container_width=True) with tab2: # Create scatter plot fig = px.scatter( filtered_df, x='users', y='revenue', size='conversion', color='conversion', color_continuous_scale=\"Reds\", title=\"User-Revenue Correlation\" ) st.plotly_chart(fig, use_container_width=True) if __name__ == \"__main__\": create_dashboard() \ud83d\udee0\ufe0f Practice Projects Secure Dashboard Application Implement user authentication Create role-based access control Add secure data storage Deploy to Streamlit Cloud Responsive Chat Interface Build custom chat components Create mobile-friendly layout Add real-time updates Implement message persistence Advanced Analytics Dashboard Create interactive visualizations Add custom filtering Implement data export Build responsive layout \ud83d\udcdd Best Practices Security Use environment variables Implement proper authentication Validate user input Use HTTPS Keep dependencies updated Performance Cache expensive operations Optimize data loading Use efficient layouts Minimize re-runs Deployment Use requirements.txt Configure secrets Set up monitoring Enable error tracking Design Follow responsive design principles Maintain consistent branding Use appropriate color schemes Consider accessibility \ud83d\ude80 Next Steps Explore WebSocket integration Study database connectivity Learn about custom caching Master component lifecycle Practice CI/CD deployment","title":"Advanced Streamlit"},{"location":"advanced-streamlit/#vets-who-code-advanced-streamlit-development","text":"","title":"Vets Who Code: Advanced Streamlit Development"},{"location":"advanced-streamlit/#taking-your-streamlit-apps-to-the-next-level","text":"","title":"Taking Your Streamlit Apps to the Next Level"},{"location":"advanced-streamlit/#advanced-learning-objectives","text":"After completing this lesson, you will be able to: Deploy applications to Streamlit Cloud Create custom Streamlit components Implement secure authentication Build responsive layouts Create advanced data visualizations","title":"\ud83c\udfaf Advanced Learning Objectives"},{"location":"advanced-streamlit/#lesson-1-streamlit-cloud-deployment","text":"","title":"\ud83d\udcda Lesson 1: Streamlit Cloud Deployment"},{"location":"advanced-streamlit/#local-setup-for-deployment","text":"Create requirements.txt : streamlit==1.31.0 pandas==2.0.3 numpy==1.24.3 python-dotenv==1.0.0 Create .gitignore : venv/ .env __pycache__/ *.pyc .DS_Store Create config.toml in .streamlit folder: [theme] primaryColor = \"#D6372E\" # VWC Red backgroundColor = \"#FFFFFF\" secondaryBackgroundColor = \"#F0F2F6\" textColor = \"#262730\" font = \"sans serif\" [server] maxUploadSize = 200 enableXsrfProtection = true","title":"Local Setup for Deployment"},{"location":"advanced-streamlit/#deployment-steps","text":"Push to GitHub: git init git add . git commit -m \"Initial commit\" git remote add origin your-repo-url git push -u origin main Streamlit Cloud Setup: Visit streamlit.io/cloud Connect your GitHub repository Select main file Add secrets in dashboard Deploy","title":"Deployment Steps"},{"location":"advanced-streamlit/#lesson-2-custom-components","text":"","title":"\ud83d\udcda Lesson 2: Custom Components"},{"location":"advanced-streamlit/#basic-custom-component","text":"Create custom_components.py : import streamlit as st import streamlit.components.v1 as components def custom_html_component(): components.html( \"\"\"

    Custom HTML Component

    This is a custom component using HTML and JavaScript.

    \"\"\", height=200 ) def custom_chart_component(): components.html( \"\"\"
    \"\"\", height=400 ) # Usage st.title(\"Custom Components Demo\") custom_html_component() custom_chart_component()","title":"Basic Custom Component"},{"location":"advanced-streamlit/#lesson-3-authentication-security","text":"","title":"\ud83d\udcda Lesson 3: Authentication & Security"},{"location":"advanced-streamlit/#basic-authentication","text":"Create auth.py : import streamlit as st import hmac import hashlib from datetime import datetime, timedelta class Authenticator: def __init__(self): if 'authenticated' not in st.session_state: st.session_state.authenticated = False st.session_state.auth_time = None def _hash_password(self, password: str) -> str: return hashlib.sha256(password.encode()).hexdigest() def _check_password(self, username: str, password: str) -> bool: # Replace with database lookup in production users = { \"demo\": self._hash_password(\"demo123\") } return username in users and users[username] == self._hash_password(password) def login_form(self): if not st.session_state.authenticated: st.title(\"Login\") with st.form(\"login_form\"): username = st.text_input(\"Username\") password = st.text_input(\"Password\", type=\"password\") submitted = st.form_submit_button(\"Login\") if submitted: if self._check_password(username, password): st.session_state.authenticated = True st.session_state.auth_time = datetime.now() st.experimental_rerun() else: st.error(\"Invalid credentials\") return st.session_state.authenticated # Usage example auth = Authenticator() if auth.login_form(): st.write(\"Welcome to the secure area!\")","title":"Basic Authentication"},{"location":"advanced-streamlit/#lesson-4-responsive-design","text":"","title":"\ud83d\udcda Lesson 4: Responsive Design"},{"location":"advanced-streamlit/#responsive-layout-example","text":"Create responsive.py : import streamlit as st def get_device_type(): # Basic device detection using viewport width # Note: This is a simplified approach return st.select_slider( \"Preview as:\", options=[\"Mobile\", \"Tablet\", \"Desktop\"], value=\"Desktop\", key=\"device_type\" ) st.title(\"Responsive Design Demo\") device = get_device_type() # Responsive layout based on device if device == \"Mobile\": # Single column layout st.write(\"Mobile Layout\") st.image(\"https://via.placeholder.com/300x200\") st.write(\"Content below image\") elif device == \"Tablet\": # Two column layout col1, col2 = st.columns([1, 1]) with col1: st.write(\"Tablet Layout - Left\") st.image(\"https://via.placeholder.com/400x300\") with col2: st.write(\"Tablet Layout - Right\") st.write(\"Content next to image\") else: # Desktop # Three column layout col1, col2, col3 = st.columns([1, 2, 1]) with col1: st.write(\"Sidebar content\") with col2: st.write(\"Desktop Layout - Main\") st.image(\"https://via.placeholder.com/800x400\") with col3: st.write(\"Additional content\") # Responsive CSS st.markdown(\"\"\" \"\"\", unsafe_allow_html=True)","title":"Responsive Layout Example"},{"location":"advanced-streamlit/#lesson-5-advanced-visualizations","text":"","title":"\ud83d\udcda Lesson 5: Advanced Visualizations"},{"location":"advanced-streamlit/#interactive-dashboard","text":"Create advanced_viz.py : import streamlit as st import pandas as pd import plotly.express as px import plotly.graph_objects as go from datetime import datetime, timedelta # Generate sample data def generate_data(): dates = pd.date_range( start=datetime.now() - timedelta(days=30), end=datetime.now(), freq='D' ) df = pd.DataFrame({ 'date': dates, 'users': np.random.randint(100, 1000, size=len(dates)), 'revenue': np.random.uniform(1000, 5000, size=len(dates)), 'conversion': np.random.uniform(0.1, 0.3, size=len(dates)) }) return df # Create interactive visualizations def create_dashboard(): st.title(\"Advanced Analytics Dashboard\") # Load data df = generate_data() # Date filter date_range = st.date_input( \"Select Date Range\", value=(df['date'].min(), df['date'].max()), key=\"date_range\" ) # Filter data mask = (df['date'].dt.date >= date_range[0]) & (df['date'].dt.date <= date_range[1]) filtered_df = df[mask] # Metrics row col1, col2, col3 = st.columns(3) with col1: st.metric( \"Total Users\", f\"{filtered_df['users'].sum():,.0f}\", f\"{filtered_df['users'].diff().mean():+.1f}/day\" ) with col2: st.metric( \"Total Revenue\", f\"${filtered_df['revenue'].sum():,.2f}\", f\"{filtered_df['revenue'].pct_change().mean()*100:+.1f}%\" ) with col3: st.metric( \"Avg Conversion\", f\"{filtered_df['conversion'].mean()*100:.1f}%\", f\"{filtered_df['conversion'].diff().mean()*100:+.2f}pp\" ) # Interactive charts tab1, tab2 = st.tabs([\"Time Series\", \"Analysis\"]) with tab1: # Create time series chart fig = go.Figure() fig.add_trace(go.Scatter( x=filtered_df['date'], y=filtered_df['users'], name=\"Users\", line=dict(color=\"#D6372E\") )) fig.add_trace(go.Scatter( x=filtered_df['date'], y=filtered_df['revenue'], name=\"Revenue\", yaxis=\"y2\" )) fig.update_layout( title=\"Users and Revenue Over Time\", yaxis=dict(title=\"Users\"), yaxis2=dict(title=\"Revenue\", overlaying=\"y\", side=\"right\"), hovermode=\"x unified\" ) st.plotly_chart(fig, use_container_width=True) with tab2: # Create scatter plot fig = px.scatter( filtered_df, x='users', y='revenue', size='conversion', color='conversion', color_continuous_scale=\"Reds\", title=\"User-Revenue Correlation\" ) st.plotly_chart(fig, use_container_width=True) if __name__ == \"__main__\": create_dashboard()","title":"Interactive Dashboard"},{"location":"advanced-streamlit/#practice-projects","text":"Secure Dashboard Application Implement user authentication Create role-based access control Add secure data storage Deploy to Streamlit Cloud Responsive Chat Interface Build custom chat components Create mobile-friendly layout Add real-time updates Implement message persistence Advanced Analytics Dashboard Create interactive visualizations Add custom filtering Implement data export Build responsive layout","title":"\ud83d\udee0\ufe0f Practice Projects"},{"location":"advanced-streamlit/#best-practices","text":"Security Use environment variables Implement proper authentication Validate user input Use HTTPS Keep dependencies updated Performance Cache expensive operations Optimize data loading Use efficient layouts Minimize re-runs Deployment Use requirements.txt Configure secrets Set up monitoring Enable error tracking Design Follow responsive design principles Maintain consistent branding Use appropriate color schemes Consider accessibility","title":"\ud83d\udcdd Best Practices"},{"location":"advanced-streamlit/#next-steps","text":"Explore WebSocket integration Study database connectivity Learn about custom caching Master component lifecycle Practice CI/CD deployment","title":"\ud83d\ude80 Next Steps"},{"location":"bash/","text":"Comprehensive Bash Guide: From Basics to Advanced Techniques Table of Contents Comprehensive Bash Guide: From Basics to Advanced Techniques Table of Contents 1. Introduction to Bash 2. Basic Syntax Comments Commands 3. Variables Declaring and Using Variables Command Substitution 4. Control Structures If-Else Statement Loops For Loop While Loop 5. Functions 6. Input and Output Reading User Input Redirecting Output 7. Command Line Arguments 8. Basic String Operations 9. Basic Arithmetic 10. Useful Bash Commands 11. Intermediate Bash Techniques Arrays Case Statements Here Documents Subshells 12. Advanced Bash Techniques Regular Expressions Process Substitution Traps Debugging Parameter Expansion 13. Best Practices and Tips 1. Introduction to Bash Bash (Bourne Again SHell) is a command processor that typically runs in a text window where the user types commands that cause actions. Bash can also read and execute commands from a file, called a script. 2. Basic Syntax Comments # This is a comment Commands echo \"Hello, World!\" # Prints \"Hello, World!\" 3. Variables Declaring and Using Variables name=\"John\" echo \"Hello, $name\" # Prints \"Hello, John\" Command Substitution current_date=$(date) echo \"Today is $current_date\" 4. Control Structures If-Else Statement if [ \"$name\" == \"John\" ]; then echo \"Hello, John!\" else echo \"You're not John\" fi Loops For Loop for i in 1 2 3 4 5 do echo \"Number: $i\" done While Loop count=0 while [ $count -lt 5 ] do echo \"Count: $count\" ((count++)) done 5. Functions greet() { echo \"Hello, $1!\" } greet \"World\" # Calls the function, prints \"Hello, World!\" 6. Input and Output Reading User Input echo \"What's your name?\" read user_name echo \"Hello, $user_name!\" Redirecting Output echo \"This goes to a file\" > output.txt echo \"This is appended to the file\" >> output.txt 7. Command Line Arguments # Save as script.sh and run with: ./script.sh arg1 arg2 echo \"First argument: $1\" echo \"Second argument: $2\" echo \"All arguments: $@\" echo \"Number of arguments: $#\" 8. Basic String Operations string=\"Hello, World!\" echo \"${string:0:5}\" # Prints \"Hello\" echo \"${string/World/Bash}\" # Prints \"Hello, Bash!\" echo \"${#string}\" # Prints the length of the string 9. Basic Arithmetic a=5 b=3 echo $((a + b)) # Addition echo $((a - b)) # Subtraction echo $((a * b)) # Multiplication echo $((a / b)) # Division echo $((a % b)) # Modulus 10. Useful Bash Commands source script.sh : Execute commands from a file in the current shell export VAR=\"value\" : Make a variable available to child processes alias ls='ls -la' : Create a shortcut for a command set -e : Exit immediately if a command exits with a non-zero status set -x : Print commands and their arguments as they are executed 11. Intermediate Bash Techniques Arrays fruits=(\"apple\" \"banana\" \"cherry\") echo ${fruits[1]} # Prints \"banana\" echo ${fruits[@]} # Prints all elements echo ${#fruits[@]} # Prints number of elements Case Statements case $fruit in \"apple\") echo \"It's an apple\" ;; \"banana\"|\"plantain\") echo \"It's a banana or plantain\" ;; *) echo \"Unknown fruit\" ;; esac Here Documents cat << EOF > file.txt This is a multi-line text that will be written to file.txt EOF Subshells (cd /tmp && echo \"Current dir: $PWD\") echo \"We're back in $PWD\" 12. Advanced Bash Techniques Regular Expressions if [[ \"example@email.com\" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}$ ]]; then echo \"Valid email\" fi Process Substitution diff <(ls dir1) <(ls dir2) Traps trap 'echo \"Ctrl+C is trapped\"' INT Debugging set -x # Enable debugging set -e # Exit on error set -u # Treat unset variables as an error Parameter Expansion name=\"John\" echo ${name:-\"Default\"} # Use default if name is unset echo ${name:=\"NewDefault\"} # Assign default if name is unset echo ${name:+\"Alternative\"} # Use alternative if name is set echo ${name:?\"Error message\"} # Display error if name is unset 13. Best Practices and Tips Use shellcheck for script validation Use functions for repeated code Use meaningful variable names Quote variables to prevent word splitting Use set -e to exit on error Use set -u to catch unset variables Use [[ ]] for conditionals instead of [ ] Use $(command) instead of backticks for command substitution Use $() for arithmetic instead of expr Use trap to handle signals and perform cleanup Remember, this guide covers a wide range of Bash features, but Bash is incredibly rich and there's always more to learn. Always refer to the Bash manual ( man bash ) for the most up-to-date and detailed information.","title":"Bash Scripting"},{"location":"bash/#comprehensive-bash-guide-from-basics-to-advanced-techniques","text":"","title":"Comprehensive Bash Guide: From Basics to Advanced Techniques"},{"location":"bash/#table-of-contents","text":"Comprehensive Bash Guide: From Basics to Advanced Techniques Table of Contents 1. Introduction to Bash 2. Basic Syntax Comments Commands 3. Variables Declaring and Using Variables Command Substitution 4. Control Structures If-Else Statement Loops For Loop While Loop 5. Functions 6. Input and Output Reading User Input Redirecting Output 7. Command Line Arguments 8. Basic String Operations 9. Basic Arithmetic 10. Useful Bash Commands 11. Intermediate Bash Techniques Arrays Case Statements Here Documents Subshells 12. Advanced Bash Techniques Regular Expressions Process Substitution Traps Debugging Parameter Expansion 13. Best Practices and Tips","title":"Table of Contents"},{"location":"bash/#1-introduction-to-bash","text":"Bash (Bourne Again SHell) is a command processor that typically runs in a text window where the user types commands that cause actions. Bash can also read and execute commands from a file, called a script.","title":"1. Introduction to Bash"},{"location":"bash/#2-basic-syntax","text":"","title":"2. Basic Syntax"},{"location":"bash/#comments","text":"# This is a comment","title":"Comments"},{"location":"bash/#commands","text":"echo \"Hello, World!\" # Prints \"Hello, World!\"","title":"Commands"},{"location":"bash/#3-variables","text":"","title":"3. Variables"},{"location":"bash/#declaring-and-using-variables","text":"name=\"John\" echo \"Hello, $name\" # Prints \"Hello, John\"","title":"Declaring and Using Variables"},{"location":"bash/#command-substitution","text":"current_date=$(date) echo \"Today is $current_date\"","title":"Command Substitution"},{"location":"bash/#4-control-structures","text":"","title":"4. Control Structures"},{"location":"bash/#if-else-statement","text":"if [ \"$name\" == \"John\" ]; then echo \"Hello, John!\" else echo \"You're not John\" fi","title":"If-Else Statement"},{"location":"bash/#loops","text":"","title":"Loops"},{"location":"bash/#for-loop","text":"for i in 1 2 3 4 5 do echo \"Number: $i\" done","title":"For Loop"},{"location":"bash/#while-loop","text":"count=0 while [ $count -lt 5 ] do echo \"Count: $count\" ((count++)) done","title":"While Loop"},{"location":"bash/#5-functions","text":"greet() { echo \"Hello, $1!\" } greet \"World\" # Calls the function, prints \"Hello, World!\"","title":"5. Functions"},{"location":"bash/#6-input-and-output","text":"","title":"6. Input and Output"},{"location":"bash/#reading-user-input","text":"echo \"What's your name?\" read user_name echo \"Hello, $user_name!\"","title":"Reading User Input"},{"location":"bash/#redirecting-output","text":"echo \"This goes to a file\" > output.txt echo \"This is appended to the file\" >> output.txt","title":"Redirecting Output"},{"location":"bash/#7-command-line-arguments","text":"# Save as script.sh and run with: ./script.sh arg1 arg2 echo \"First argument: $1\" echo \"Second argument: $2\" echo \"All arguments: $@\" echo \"Number of arguments: $#\"","title":"7. Command Line Arguments"},{"location":"bash/#8-basic-string-operations","text":"string=\"Hello, World!\" echo \"${string:0:5}\" # Prints \"Hello\" echo \"${string/World/Bash}\" # Prints \"Hello, Bash!\" echo \"${#string}\" # Prints the length of the string","title":"8. Basic String Operations"},{"location":"bash/#9-basic-arithmetic","text":"a=5 b=3 echo $((a + b)) # Addition echo $((a - b)) # Subtraction echo $((a * b)) # Multiplication echo $((a / b)) # Division echo $((a % b)) # Modulus","title":"9. Basic Arithmetic"},{"location":"bash/#10-useful-bash-commands","text":"source script.sh : Execute commands from a file in the current shell export VAR=\"value\" : Make a variable available to child processes alias ls='ls -la' : Create a shortcut for a command set -e : Exit immediately if a command exits with a non-zero status set -x : Print commands and their arguments as they are executed","title":"10. Useful Bash Commands"},{"location":"bash/#11-intermediate-bash-techniques","text":"","title":"11. Intermediate Bash Techniques"},{"location":"bash/#arrays","text":"fruits=(\"apple\" \"banana\" \"cherry\") echo ${fruits[1]} # Prints \"banana\" echo ${fruits[@]} # Prints all elements echo ${#fruits[@]} # Prints number of elements","title":"Arrays"},{"location":"bash/#case-statements","text":"case $fruit in \"apple\") echo \"It's an apple\" ;; \"banana\"|\"plantain\") echo \"It's a banana or plantain\" ;; *) echo \"Unknown fruit\" ;; esac","title":"Case Statements"},{"location":"bash/#here-documents","text":"cat << EOF > file.txt This is a multi-line text that will be written to file.txt EOF","title":"Here Documents"},{"location":"bash/#subshells","text":"(cd /tmp && echo \"Current dir: $PWD\") echo \"We're back in $PWD\"","title":"Subshells"},{"location":"bash/#12-advanced-bash-techniques","text":"","title":"12. Advanced Bash Techniques"},{"location":"bash/#regular-expressions","text":"if [[ \"example@email.com\" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}$ ]]; then echo \"Valid email\" fi","title":"Regular Expressions"},{"location":"bash/#process-substitution","text":"diff <(ls dir1) <(ls dir2)","title":"Process Substitution"},{"location":"bash/#traps","text":"trap 'echo \"Ctrl+C is trapped\"' INT","title":"Traps"},{"location":"bash/#debugging","text":"set -x # Enable debugging set -e # Exit on error set -u # Treat unset variables as an error","title":"Debugging"},{"location":"bash/#parameter-expansion","text":"name=\"John\" echo ${name:-\"Default\"} # Use default if name is unset echo ${name:=\"NewDefault\"} # Assign default if name is unset echo ${name:+\"Alternative\"} # Use alternative if name is set echo ${name:?\"Error message\"} # Display error if name is unset","title":"Parameter Expansion"},{"location":"bash/#13-best-practices-and-tips","text":"Use shellcheck for script validation Use functions for repeated code Use meaningful variable names Quote variables to prevent word splitting Use set -e to exit on error Use set -u to catch unset variables Use [[ ]] for conditionals instead of [ ] Use $(command) instead of backticks for command substitution Use $() for arithmetic instead of expr Use trap to handle signals and perform cleanup Remember, this guide covers a wide range of Bash features, but Bash is incredibly rich and there's always more to learn. Always refer to the Bash manual ( man bash ) for the most up-to-date and detailed information.","title":"13. Best Practices and Tips"},{"location":"basics-of-git/","text":"Setting up Git Introduction This guide will walk you through the steps to properly set up Git on your machine. You will configure Git, generate SSH keys for secure authentication, set up your user identity, and, if necessary, configure a proxy for Git operations. Objectives By the end of this guide, you will be able to: Configure Git using the terminal. Generate SSH keys for secure communication. Set and manage your Git user identity. Configure a proxy for Git operations (if required). Configuring Git Setting Up User Information To personalize your Git environment, configure your username and email. This information will be attached to every commit you make. Use the following commands: git config --global user.name \"Your Name\" git config --global user.email \"your.email@example.com\" Verifying Configuration To check your current settings, use: git config --list !!! task Set your username and email, then verify the configuration using the above command. Generating SSH Keys SSH keys provide secure access to Git services (like GitHub or GitLab), allowing you to interact with remote repositories without entering your password every time. Generating an SSH Key Run the following command in your terminal: ssh-keygen -t rsa -b 4096 Follow the prompts and press Enter to accept the default file location. Adding SSH Key to GitHub/GitLab Once the key is generated: Copy the public key to your clipboard: bash cat ~/.ssh/id_rsa.pub Go to your GitHub or GitLab account settings. Navigate to SSH and GPG keys and paste the key. !!! task Generate an SSH key and add it to your GitHub or GitLab account. Proxy Configuration (Optional) If you're working behind a corporate firewall or restricted network, you may need to configure Git to use a proxy. Setting Up a Proxy To set up a proxy, run: git config --global http.proxy http://proxy.example.com:8080 Replace proxy.example.com:8080 with your actual proxy details. Verifying Proxy Configuration To confirm the proxy is set up correctly: git config --global http.proxy !!! task If needed, configure your proxy settings and verify them using the above commands. Practical Exercise Follow these steps to complete your setup: Configure Git with your username and email. Generate an SSH key and add it to your GitHub or GitLab account. If necessary, set up a proxy. Verify your configuration with: git config --list Additional Resources Official Git Documentation GitHub SSH Key Setup Guide Git Configuration Best Practices With these steps completed, Git is now properly configured on your machine, and you're ready to start working with version control. Happy coding!","title":"Git Basics"},{"location":"basics-of-git/#setting-up-git","text":"","title":"Setting up Git"},{"location":"basics-of-git/#introduction","text":"This guide will walk you through the steps to properly set up Git on your machine. You will configure Git, generate SSH keys for secure authentication, set up your user identity, and, if necessary, configure a proxy for Git operations.","title":"Introduction"},{"location":"basics-of-git/#objectives","text":"By the end of this guide, you will be able to: Configure Git using the terminal. Generate SSH keys for secure communication. Set and manage your Git user identity. Configure a proxy for Git operations (if required).","title":"Objectives"},{"location":"basics-of-git/#configuring-git","text":"","title":"Configuring Git"},{"location":"basics-of-git/#setting-up-user-information","text":"To personalize your Git environment, configure your username and email. This information will be attached to every commit you make. Use the following commands: git config --global user.name \"Your Name\" git config --global user.email \"your.email@example.com\"","title":"Setting Up User Information"},{"location":"basics-of-git/#verifying-configuration","text":"To check your current settings, use: git config --list !!! task Set your username and email, then verify the configuration using the above command.","title":"Verifying Configuration"},{"location":"basics-of-git/#generating-ssh-keys","text":"SSH keys provide secure access to Git services (like GitHub or GitLab), allowing you to interact with remote repositories without entering your password every time.","title":"Generating SSH Keys"},{"location":"basics-of-git/#generating-an-ssh-key","text":"Run the following command in your terminal: ssh-keygen -t rsa -b 4096 Follow the prompts and press Enter to accept the default file location.","title":"Generating an SSH Key"},{"location":"basics-of-git/#adding-ssh-key-to-githubgitlab","text":"Once the key is generated: Copy the public key to your clipboard: bash cat ~/.ssh/id_rsa.pub Go to your GitHub or GitLab account settings. Navigate to SSH and GPG keys and paste the key. !!! task Generate an SSH key and add it to your GitHub or GitLab account.","title":"Adding SSH Key to GitHub/GitLab"},{"location":"basics-of-git/#proxy-configuration-optional","text":"If you're working behind a corporate firewall or restricted network, you may need to configure Git to use a proxy.","title":"Proxy Configuration (Optional)"},{"location":"basics-of-git/#setting-up-a-proxy","text":"To set up a proxy, run: git config --global http.proxy http://proxy.example.com:8080 Replace proxy.example.com:8080 with your actual proxy details.","title":"Setting Up a Proxy"},{"location":"basics-of-git/#verifying-proxy-configuration","text":"To confirm the proxy is set up correctly: git config --global http.proxy !!! task If needed, configure your proxy settings and verify them using the above commands.","title":"Verifying Proxy Configuration"},{"location":"basics-of-git/#practical-exercise","text":"Follow these steps to complete your setup: Configure Git with your username and email. Generate an SSH key and add it to your GitHub or GitLab account. If necessary, set up a proxy. Verify your configuration with: git config --list","title":"Practical Exercise"},{"location":"basics-of-git/#additional-resources","text":"Official Git Documentation GitHub SSH Key Setup Guide Git Configuration Best Practices With these steps completed, Git is now properly configured on your machine, and you're ready to start working with version control. Happy coding!","title":"Additional Resources"},{"location":"code-of-conduct/","text":"Code of Conduct Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards Examples of behavior that contributes to creating a positive environment include: Using welcoming and inclusive language. Being respectful of differing viewpoints and experiences. Gracefully accepting constructive criticism. Focusing on what is best for the community. Showing empathy towards other community members. Examples of unacceptable behavior by participants include: The use of sexualized language or imagery and unwelcome sexual attention or advances. Trolling, insulting/derogatory comments, and personal or political attacks. Public or private harassment. Deliberate intimidation, stalking, or following. Harassing photography or recording. Sustained disruption of talks or other events. Inappropriate physical contact. Advocating for, or encouraging, any of the above behaviors. Publishing others' private information, such as a physical or electronic address, without explicit permission. Other conduct that is inappropriate for a professional or shared professional environment. Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting Jerome Hardaway directly via slack. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Attribution This Code of Conduct is adapted from the Contributor Covenant, version 1.4, code of conduct.","title":"Code Of Conduct"},{"location":"code-of-conduct/#code-of-conduct","text":"","title":"Code of Conduct"},{"location":"code-of-conduct/#our-pledge","text":"In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.","title":"Our Pledge"},{"location":"code-of-conduct/#our-standards","text":"","title":"Our Standards"},{"location":"code-of-conduct/#examples-of-behavior-that-contributes-to-creating-a-positive-environment-include","text":"Using welcoming and inclusive language. Being respectful of differing viewpoints and experiences. Gracefully accepting constructive criticism. Focusing on what is best for the community. Showing empathy towards other community members.","title":"Examples of behavior that contributes to creating a positive environment include:"},{"location":"code-of-conduct/#examples-of-unacceptable-behavior-by-participants-include","text":"The use of sexualized language or imagery and unwelcome sexual attention or advances. Trolling, insulting/derogatory comments, and personal or political attacks. Public or private harassment. Deliberate intimidation, stalking, or following. Harassing photography or recording. Sustained disruption of talks or other events. Inappropriate physical contact. Advocating for, or encouraging, any of the above behaviors. Publishing others' private information, such as a physical or electronic address, without explicit permission. Other conduct that is inappropriate for a professional or shared professional environment.","title":"Examples of unacceptable behavior by participants include:"},{"location":"code-of-conduct/#our-responsibilities","text":"Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.","title":"Our Responsibilities"},{"location":"code-of-conduct/#scope","text":"This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.","title":"Scope"},{"location":"code-of-conduct/#enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting Jerome Hardaway directly via slack. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.","title":"Enforcement"},{"location":"code-of-conduct/#attribution","text":"This Code of Conduct is adapted from the Contributor Covenant, version 1.4, code of conduct.","title":"Attribution"},{"location":"command-line-basics/","text":"Command Line Basics SOP 1. Introduction This Standard Operating Procedure (SOP) outlines the fundamental commands and techniques for effective command line usage. Mastering these basics is crucial for efficient system navigation, file management, and maintaining operational security in a digital environment. 2. Navigating Directories 2.1 Essential Navigation Commands 2.1.1 pwd (Print Working Directory) Confirms your current location in the file system. pwd 2.1.2 cd (Change Directory) Primary command for moving between directories. - Move to home directory: cd or cd ~ - Move to previous directory: cd - - Move up one level: cd .. - Move to specific directory: cd /path/to/directory 2.1.3 ls (List) Provides reconnaissance on directory contents. - Basic listing: ls - Detailed listing: ls -l - Show hidden files: ls -a - Detailed listing with hidden files: ls -la - Sort by size: ls -S 2.1.4 tree Offers a hierarchical view of the directory structure. - Limited depth view: tree -L 2 - Directory-only view: tree -d 2.2 Advanced Navigation Techniques Use tab completion to auto-complete file and directory names. Utilize the up and down arrow keys to navigate command history. Create aliases for frequently used commands to enhance efficiency. 3. File Operations 3.1 Basic File Management 3.1.1 cp (Copy) Copies files or directories. cp source_file target_file cp -R source_directory target_directory 3.1.2 mv (Move) Moves or renames files and directories. mv old_filename new_filename mv file_to_move target_directory/ 3.1.3 rm (Remove) Deletes files or directories. rm filename rm -r directory_name rm -i filename # Interactive mode, asks for confirmation 3.1.4 touch Creates new empty files or updates file timestamps. touch new_file 3.1.5 mkdir (Make Directory) Creates new directories. mkdir new_directory mkdir -p parent_directory/new_directory 3.2 Advanced File Operations 3.2.1 find Searches for files and directories based on various criteria. find /path/to/search -name \"filename\" find ~ -name \"*.txt\" # Find all .txt files in home directory 3.2.2 locate Quickly searches for files using a pre-built database. locate filename sudo updatedb # Update the database 4. Working with Wildcards Wildcards enhance precision and efficiency in file operations. 4.1 Asterisk (*) Matches zero or more characters. ls *.jpg # Lists all JPEG files 4.2 Question Mark (?) Matches exactly one character. ls report_?.txt # Matches report_1.txt, report_2.txt, but not report_10.txt 4.3 Square Brackets ([]) Matches any single character within the brackets. ls [a-c]*.txt # Lists files starting with a, b, or c and ending with .txt 4.4 Curly Braces ({}) Specifies multiple discrete patterns. ls {*.txt,*.pdf} # Lists all text and PDF files 5. Managing Permissions Proper permission management is crucial for system security. 5.1 chmod (Change Mode) Adjusts file and directory permissions. chmod u+x file.txt # Adds execute permission for the owner chmod 755 script.sh # Sets rwxr-xr-x permissions 5.2 chown (Change Owner) Transfers file or directory ownership. chown user:group file.txt 5.3 chgrp (Change Group) Modifies the group ownership of files or directories. chgrp team project/ 5.4 umask Sets default creation permissions for new files and directories. umask 022 # Sets default permissions to 644 for files and 755 for directories 6. Disk and Directory Usage 6.1 df (Disk Free) Displays disk space usage. df -h # Human-readable format 6.2 du (Disk Usage) Estimates space used by directories and files. du -sh /path/to/directory 7. Summary Mastering these command line basics provides a solid foundation for efficient system management and navigation. Regular practice and application of these commands will enhance your operational capabilities in a digital environment. Remember, the command line is your primary interface for precise control and management of your system resources.","title":"Command Line Basics"},{"location":"command-line-basics/#command-line-basics-sop","text":"","title":"Command Line Basics SOP"},{"location":"command-line-basics/#1-introduction","text":"This Standard Operating Procedure (SOP) outlines the fundamental commands and techniques for effective command line usage. Mastering these basics is crucial for efficient system navigation, file management, and maintaining operational security in a digital environment.","title":"1. Introduction"},{"location":"command-line-basics/#2-navigating-directories","text":"","title":"2. Navigating Directories"},{"location":"command-line-basics/#21-essential-navigation-commands","text":"","title":"2.1 Essential Navigation Commands"},{"location":"command-line-basics/#211-pwd-print-working-directory","text":"Confirms your current location in the file system. pwd","title":"2.1.1 pwd (Print Working Directory)"},{"location":"command-line-basics/#212-cd-change-directory","text":"Primary command for moving between directories. - Move to home directory: cd or cd ~ - Move to previous directory: cd - - Move up one level: cd .. - Move to specific directory: cd /path/to/directory","title":"2.1.2 cd (Change Directory)"},{"location":"command-line-basics/#213-ls-list","text":"Provides reconnaissance on directory contents. - Basic listing: ls - Detailed listing: ls -l - Show hidden files: ls -a - Detailed listing with hidden files: ls -la - Sort by size: ls -S","title":"2.1.3 ls (List)"},{"location":"command-line-basics/#214-tree","text":"Offers a hierarchical view of the directory structure. - Limited depth view: tree -L 2 - Directory-only view: tree -d","title":"2.1.4 tree"},{"location":"command-line-basics/#22-advanced-navigation-techniques","text":"Use tab completion to auto-complete file and directory names. Utilize the up and down arrow keys to navigate command history. Create aliases for frequently used commands to enhance efficiency.","title":"2.2 Advanced Navigation Techniques"},{"location":"command-line-basics/#3-file-operations","text":"","title":"3. File Operations"},{"location":"command-line-basics/#31-basic-file-management","text":"","title":"3.1 Basic File Management"},{"location":"command-line-basics/#311-cp-copy","text":"Copies files or directories. cp source_file target_file cp -R source_directory target_directory","title":"3.1.1 cp (Copy)"},{"location":"command-line-basics/#312-mv-move","text":"Moves or renames files and directories. mv old_filename new_filename mv file_to_move target_directory/","title":"3.1.2 mv (Move)"},{"location":"command-line-basics/#313-rm-remove","text":"Deletes files or directories. rm filename rm -r directory_name rm -i filename # Interactive mode, asks for confirmation","title":"3.1.3 rm (Remove)"},{"location":"command-line-basics/#314-touch","text":"Creates new empty files or updates file timestamps. touch new_file","title":"3.1.4 touch"},{"location":"command-line-basics/#315-mkdir-make-directory","text":"Creates new directories. mkdir new_directory mkdir -p parent_directory/new_directory","title":"3.1.5 mkdir (Make Directory)"},{"location":"command-line-basics/#32-advanced-file-operations","text":"","title":"3.2 Advanced File Operations"},{"location":"command-line-basics/#321-find","text":"Searches for files and directories based on various criteria. find /path/to/search -name \"filename\" find ~ -name \"*.txt\" # Find all .txt files in home directory","title":"3.2.1 find"},{"location":"command-line-basics/#322-locate","text":"Quickly searches for files using a pre-built database. locate filename sudo updatedb # Update the database","title":"3.2.2 locate"},{"location":"command-line-basics/#4-working-with-wildcards","text":"Wildcards enhance precision and efficiency in file operations.","title":"4. Working with Wildcards"},{"location":"command-line-basics/#41-asterisk","text":"Matches zero or more characters. ls *.jpg # Lists all JPEG files","title":"4.1 Asterisk (*)"},{"location":"command-line-basics/#42-question-mark","text":"Matches exactly one character. ls report_?.txt # Matches report_1.txt, report_2.txt, but not report_10.txt","title":"4.2 Question Mark (?)"},{"location":"command-line-basics/#43-square-brackets","text":"Matches any single character within the brackets. ls [a-c]*.txt # Lists files starting with a, b, or c and ending with .txt","title":"4.3 Square Brackets ([])"},{"location":"command-line-basics/#44-curly-braces","text":"Specifies multiple discrete patterns. ls {*.txt,*.pdf} # Lists all text and PDF files","title":"4.4 Curly Braces ({})"},{"location":"command-line-basics/#5-managing-permissions","text":"Proper permission management is crucial for system security.","title":"5. Managing Permissions"},{"location":"command-line-basics/#51-chmod-change-mode","text":"Adjusts file and directory permissions. chmod u+x file.txt # Adds execute permission for the owner chmod 755 script.sh # Sets rwxr-xr-x permissions","title":"5.1 chmod (Change Mode)"},{"location":"command-line-basics/#52-chown-change-owner","text":"Transfers file or directory ownership. chown user:group file.txt","title":"5.2 chown (Change Owner)"},{"location":"command-line-basics/#53-chgrp-change-group","text":"Modifies the group ownership of files or directories. chgrp team project/","title":"5.3 chgrp (Change Group)"},{"location":"command-line-basics/#54-umask","text":"Sets default creation permissions for new files and directories. umask 022 # Sets default permissions to 644 for files and 755 for directories","title":"5.4 umask"},{"location":"command-line-basics/#6-disk-and-directory-usage","text":"","title":"6. Disk and Directory Usage"},{"location":"command-line-basics/#61-df-disk-free","text":"Displays disk space usage. df -h # Human-readable format","title":"6.1 df (Disk Free)"},{"location":"command-line-basics/#62-du-disk-usage","text":"Estimates space used by directories and files. du -sh /path/to/directory","title":"6.2 du (Disk Usage)"},{"location":"command-line-basics/#7-summary","text":"Mastering these command line basics provides a solid foundation for efficient system management and navigation. Regular practice and application of these commands will enhance your operational capabilities in a digital environment. Remember, the command line is your primary interface for precise control and management of your system resources.","title":"7. Summary"},{"location":"command-line-cheat-sheet/","text":"Command Line Cheat Sheet Navigation pwd # Print working directory ls # List directory contents ls -la # List detailed contents, including hidden files cd # Change directory cd .. # Move up one directory cd ~ # Go to home directory File Operations touch # Create a new file mkdir # Create a new directory cp # Copy file or directory mv # Move or rename file or directory rm # Remove a file rm -r # Remove a directory and its contents File Viewing and Editing cat # Display file contents less # View file contents with pagination head # Show first 10 lines of file tail # Show last 10 lines of file nano # Open file in nano text editor vim # Open file in vim text editor File Permissions chmod +x # Make file executable chmod 755 # Set read, write, execute permissions chown # Change file owner System Information uname -a # Display system information df -h # Show disk usage free -h # Display free and used memory top # Show running processes (interactive) ps aux # List all running processes Network ping # Ping a host ssh @ # SSH into a remote machine scp @: # Secure copy file to remote host wget # Download file from web curl # Send HTTP request Package Management (Debian/Ubuntu) apt update # Update package list apt upgrade # Upgrade installed packages apt install # Install a package apt remove # Remove a package Text Processing grep # Search for pattern in file sed 's/old/new/g' # Replace text in file awk '{print $1}' # Print first column of file Process Management & # Run command in background jobs # List background jobs fg # Bring most recent job to foreground kill # Terminate process by ID Shortcuts Ctrl + C # Interrupt current process Ctrl + Z # Suspend current process Ctrl + D # Exit current shell Ctrl + L # Clear screen Ctrl + R # Search command history Miscellaneous man # Display manual for command history # Show command history echo $PATH # Display PATH environment variable which # Show full path of command Remember, these commands may vary slightly depending on your specific operating system and shell. Always refer to the man pages ( man ) for detailed information about each command.","title":"Command Line Cheat Sheet"},{"location":"command-line-cheat-sheet/#command-line-cheat-sheet","text":"","title":"Command Line Cheat Sheet"},{"location":"command-line-cheat-sheet/#navigation","text":"pwd # Print working directory ls # List directory contents ls -la # List detailed contents, including hidden files cd # Change directory cd .. # Move up one directory cd ~ # Go to home directory","title":"Navigation"},{"location":"command-line-cheat-sheet/#file-operations","text":"touch # Create a new file mkdir # Create a new directory cp # Copy file or directory mv # Move or rename file or directory rm # Remove a file rm -r # Remove a directory and its contents","title":"File Operations"},{"location":"command-line-cheat-sheet/#file-viewing-and-editing","text":"cat # Display file contents less # View file contents with pagination head # Show first 10 lines of file tail # Show last 10 lines of file nano # Open file in nano text editor vim # Open file in vim text editor","title":"File Viewing and Editing"},{"location":"command-line-cheat-sheet/#file-permissions","text":"chmod +x # Make file executable chmod 755 # Set read, write, execute permissions chown # Change file owner","title":"File Permissions"},{"location":"command-line-cheat-sheet/#system-information","text":"uname -a # Display system information df -h # Show disk usage free -h # Display free and used memory top # Show running processes (interactive) ps aux # List all running processes","title":"System Information"},{"location":"command-line-cheat-sheet/#network","text":"ping # Ping a host ssh @ # SSH into a remote machine scp @: # Secure copy file to remote host wget # Download file from web curl # Send HTTP request","title":"Network"},{"location":"command-line-cheat-sheet/#package-management-debianubuntu","text":"apt update # Update package list apt upgrade # Upgrade installed packages apt install # Install a package apt remove # Remove a package","title":"Package Management (Debian/Ubuntu)"},{"location":"command-line-cheat-sheet/#text-processing","text":"grep # Search for pattern in file sed 's/old/new/g' # Replace text in file awk '{print $1}' # Print first column of file","title":"Text Processing"},{"location":"command-line-cheat-sheet/#process-management","text":" & # Run command in background jobs # List background jobs fg # Bring most recent job to foreground kill # Terminate process by ID","title":"Process Management"},{"location":"command-line-cheat-sheet/#shortcuts","text":"Ctrl + C # Interrupt current process Ctrl + Z # Suspend current process Ctrl + D # Exit current shell Ctrl + L # Clear screen Ctrl + R # Search command history","title":"Shortcuts"},{"location":"command-line-cheat-sheet/#miscellaneous","text":"man # Display manual for command history # Show command history echo $PATH # Display PATH environment variable which # Show full path of command Remember, these commands may vary slightly depending on your specific operating system and shell. Always refer to the man pages ( man ) for detailed information about each command.","title":"Miscellaneous"},{"location":"command-line-text-manipulation/","text":"Command Line Text Manipulation SOP 1. Introduction This Standard Operating Procedure (SOP) outlines essential techniques and tools for text manipulation using the command line. Mastering these skills is crucial for efficient data processing, log analysis, file management, and text editing in various operational contexts. Whether you're a software engineer, writer, or instructor based in Atlanta, these skills will significantly enhance your command line proficiency. 2. Viewing Files 2.1 cat Displays entire file content at once. cat file.txt cat -n file.txt # Add line numbers cat -s file.txt # Squeeze multiple blank lines 2.2 less Views files one screen at a time with advanced navigation. less file.txt # Inside less: # /pattern - search forward # ?pattern - search backward # g - go to beginning # G - go to end 2.3 more Similar to less, but with fewer features. more file.txt # Inside more: # Space - next screen # b - previous screen # /pattern - search forward 2.4 tac Displays file content in reverse order. tac file.txt tac -s 'separator' file.txt # Use custom separator 3. Redirects and Pipes [Content remains the same as in the previous version] 4. Regular Expressions [Content remains the same as in the previous version] 5. Searching and Editing [Content remains the same as in the previous version] 6. Sorting and Uniqueness [Content remains the same as in the previous version] 7. Text Comparison [Content remains the same as in the previous version] 8. Text Editing 8.1 nano Simple and user-friendly text editor. nano file.txt # Ctrl+G - Help # Ctrl+O - Save # Ctrl+X - Exit 8.2 vi/vim Powerful and efficient text editor with different modes. vi file.txt # :w - Save # :q - Quit # :wq - Save and quit # /pattern - Search for pattern 8.3 emacs Extensible and customizable text editor. emacs file.txt # Ctrl+x Ctrl+s - Save # Ctrl+x Ctrl+c - Exit # Ctrl+s - Search forward # Ctrl+r - Search backward 8.4 gedit Graphical text editor that can be run from terminal. gedit file.txt gedit --new-window file.txt 9. Best Practices Always make backups before performing large-scale text manipulations. Use version control systems when working with source code. Test complex commands on a small subset of data before applying to large datasets. Combine multiple tools using pipes for more powerful operations. Use man pages or --help flags to explore advanced options of each command. Choose the appropriate text editor based on the task complexity and your familiarity. Practice regularly with different text manipulation tools to improve proficiency. 10. Summary Mastering command line text manipulation tools enhances operational efficiency in various tech-related tasks. From basic file viewing and searching to complex pattern matching, file comparisons, and text editing, these utilities form a powerful toolkit for data processing and file management. The ability to efficiently view, search, manipulate, and edit text files directly from the command line is invaluable in roles such as software development, system administration, and data analysis. By mastering tools like cat, less, grep, sed, awk, and various text editors, you'll be well-equipped to handle a wide range of text-related tasks quickly and effectively. Regular practice with these tools will significantly improve your command line proficiency, data handling capabilities, and overall productivity in tech-related fields. Remember, the key to mastery is consistent application of these skills in real-world scenarios.","title":"Command Line Text Manipulation"},{"location":"command-line-text-manipulation/#command-line-text-manipulation-sop","text":"","title":"Command Line Text Manipulation SOP"},{"location":"command-line-text-manipulation/#1-introduction","text":"This Standard Operating Procedure (SOP) outlines essential techniques and tools for text manipulation using the command line. Mastering these skills is crucial for efficient data processing, log analysis, file management, and text editing in various operational contexts. Whether you're a software engineer, writer, or instructor based in Atlanta, these skills will significantly enhance your command line proficiency.","title":"1. Introduction"},{"location":"command-line-text-manipulation/#2-viewing-files","text":"","title":"2. Viewing Files"},{"location":"command-line-text-manipulation/#21-cat","text":"Displays entire file content at once. cat file.txt cat -n file.txt # Add line numbers cat -s file.txt # Squeeze multiple blank lines","title":"2.1 cat"},{"location":"command-line-text-manipulation/#22-less","text":"Views files one screen at a time with advanced navigation. less file.txt # Inside less: # /pattern - search forward # ?pattern - search backward # g - go to beginning # G - go to end","title":"2.2 less"},{"location":"command-line-text-manipulation/#23-more","text":"Similar to less, but with fewer features. more file.txt # Inside more: # Space - next screen # b - previous screen # /pattern - search forward","title":"2.3 more"},{"location":"command-line-text-manipulation/#24-tac","text":"Displays file content in reverse order. tac file.txt tac -s 'separator' file.txt # Use custom separator","title":"2.4 tac"},{"location":"command-line-text-manipulation/#3-redirects-and-pipes","text":"[Content remains the same as in the previous version]","title":"3. Redirects and Pipes"},{"location":"command-line-text-manipulation/#4-regular-expressions","text":"[Content remains the same as in the previous version]","title":"4. Regular Expressions"},{"location":"command-line-text-manipulation/#5-searching-and-editing","text":"[Content remains the same as in the previous version]","title":"5. Searching and Editing"},{"location":"command-line-text-manipulation/#6-sorting-and-uniqueness","text":"[Content remains the same as in the previous version]","title":"6. Sorting and Uniqueness"},{"location":"command-line-text-manipulation/#7-text-comparison","text":"[Content remains the same as in the previous version]","title":"7. Text Comparison"},{"location":"command-line-text-manipulation/#8-text-editing","text":"","title":"8. Text Editing"},{"location":"command-line-text-manipulation/#81-nano","text":"Simple and user-friendly text editor. nano file.txt # Ctrl+G - Help # Ctrl+O - Save # Ctrl+X - Exit","title":"8.1 nano"},{"location":"command-line-text-manipulation/#82-vivim","text":"Powerful and efficient text editor with different modes. vi file.txt # :w - Save # :q - Quit # :wq - Save and quit # /pattern - Search for pattern","title":"8.2 vi/vim"},{"location":"command-line-text-manipulation/#83-emacs","text":"Extensible and customizable text editor. emacs file.txt # Ctrl+x Ctrl+s - Save # Ctrl+x Ctrl+c - Exit # Ctrl+s - Search forward # Ctrl+r - Search backward","title":"8.3 emacs"},{"location":"command-line-text-manipulation/#84-gedit","text":"Graphical text editor that can be run from terminal. gedit file.txt gedit --new-window file.txt","title":"8.4 gedit"},{"location":"command-line-text-manipulation/#9-best-practices","text":"Always make backups before performing large-scale text manipulations. Use version control systems when working with source code. Test complex commands on a small subset of data before applying to large datasets. Combine multiple tools using pipes for more powerful operations. Use man pages or --help flags to explore advanced options of each command. Choose the appropriate text editor based on the task complexity and your familiarity. Practice regularly with different text manipulation tools to improve proficiency.","title":"9. Best Practices"},{"location":"command-line-text-manipulation/#10-summary","text":"Mastering command line text manipulation tools enhances operational efficiency in various tech-related tasks. From basic file viewing and searching to complex pattern matching, file comparisons, and text editing, these utilities form a powerful toolkit for data processing and file management. The ability to efficiently view, search, manipulate, and edit text files directly from the command line is invaluable in roles such as software development, system administration, and data analysis. By mastering tools like cat, less, grep, sed, awk, and various text editors, you'll be well-equipped to handle a wide range of text-related tasks quickly and effectively. Regular practice with these tools will significantly improve your command line proficiency, data handling capabilities, and overall productivity in tech-related fields. Remember, the key to mastery is consistent application of these skills in real-world scenarios.","title":"10. Summary"},{"location":"command-line-utilities/","text":"Command Line Utilities SOP 1. Introduction This Standard Operating Procedure (SOP) outlines essential command line utilities that enhance productivity and efficiency in various tech-related tasks. These tools are crucial for data transfer, file compression, network management, package management, system monitoring, and user administration. Mastering these utilities will significantly improve your command line proficiency and overall system management capabilities. 2. Data Transfer 2.1 scp (Secure Copy Protocol) Securely transfer files between systems using SSH. scp -P 2222 user@remote:/path/to/file /local/directory scp -r user@remote:/directory/ /local/directory 2.2 rsync (Remote Sync) Efficiently synchronize files and directories between systems. rsync -avz user@remote:/source /local/destination rsync -av --exclude 'path/to/exclude' /source /destination rsync --bwlimit=1000 /source /destination 2.3 wget (Web Get) Retrieve files from web servers. wget -b url wget --retry-connrefused --waitretry=10 --timeout=60 url 2.4 ftp (File Transfer Protocol) Basic file transfer for non-secure data movements. ftp -p host ftp -s:script.txt host 3. File Compression 3.1 zip Package and compress files for easy sharing and storage. zip archive.zip -r target_folder/ -x \\*exclude_pattern\\* zip -u archive.zip updated_file.txt 3.2 tar Bundle files and directories efficiently. tar --listed-incremental=snapshot.file -cvzf backup.tar.gz target_directory/ tar czf - target_directory/ | ssh user@remote \"cat > remote_backup.tar.gz\" 3.3 gzip Maximize compression ratios for faster transfers. gzip -S .custom_suffix large_file cat archive_part1.gz archive_part2.gz > combined_archive.gz 3.4 bzip2 Provide superior compression efficiency for large-scale archival. bzip2 -dc archive.bz2 > output_file pbzip2 -p4 massive_file 4. Network Tools 4.1 ping Test connectivity and measure round-trip time to a host. ping -c 4 google.com 4.2 ssh (Secure Shell) Securely access and execute commands on remote machines. ssh -p port user@hostname ssh -i ~/.ssh/mykey user@192.168.1.100 5. Package Management 5.1 apt (Advanced Package Tool) Manage software on Debian-based systems. sudo apt update && sudo apt upgrade -y echo \"package_name hold\" | sudo dpkg --set-selections 5.2 brew (Homebrew) Package management for macOS. brew tap custom/repo brew services start service_name 5.3 yum (Yellowdog Updater, Modified) Manage RPM packages on Red Hat-based systems. yum history yum --enablerepo=repo_name install package_name 5.4 dpkg (Debian Package) Low-level package management for Debian-based systems. dpkg-query -l dpkg-reconfigure package_name 6. System Information Tools 6.1 uname Display system information. uname -a # Display all information uname -s # Display kernel name uname -r # Display kernel release 6.2 lscpu Display CPU architecture information. lscpu lscpu | grep Virtualization # Check virtualization support 6.3 lshw Display detailed hardware information. sudo lshw -short # Display brief hardware summary sudo lshw -C network # Display network hardware details 6.4 dmesg Display kernel messages. dmesg -Tw # Display kernel messages in real-time with timestamps 7. System Monitoring 7.1 top Monitor system processes and resource usage in real-time. top -b -n 1 > top_output.txt # Capture a snapshot of system state top -p PID1,PID2 # Monitor specific processes 7.2 htop Interactive process viewer and system monitor. htop -u username # Monitor processes for a specific user htop --output-setup-json > setup.json # Export htop configuration 7.3 iostat Report CPU statistics and I/O statistics for devices and partitions. iostat -d /dev/sda # Display I/O statistics for a specific device iostat -e # Display extended statistics 7.4 vmstat Report virtual memory statistics. vmstat -d # Display disk statistics vmstat -e # Display event counter information 8. User and Group Management 8.1 useradd Create a new user account. useradd -m -d /home/jdoe -e 2023-12-31 jdoe # Create user with home directory and expiration date 8.2 groupadd Create a new group. groupadd -r -g 101 developers # Create a system group with specific GID 8.3 sudo Execute a command as another user, typically with administrative privileges. sudo -u jdoe ls /home/jdoe # Execute command as another user 8.4 passwd Change user password and manage account locks. passwd -l jdoe # Lock user account passwd -u jdoe # Unlock user account 9. Best Practices Always verify the integrity of transferred data. Use compression to reduce bandwidth usage and storage requirements. Regularly update package lists and installed software to ensure security. Exercise caution when removing packages to avoid unintended consequences. Use SSH keys for secure, passwordless authentication when accessing remote systems. Implement rate limiting and throttling for large data transfers to avoid network congestion. Choose the appropriate compression algorithm based on the specific requirements of speed, size, and computational resources. Regularly review and update SSH keys to maintain security. Regularly monitor system performance and resource usage to identify and address issues proactively. Use system information tools to gather detailed hardware and software information for troubleshooting and inventory management. Implement proper user and group management practices to enhance system security and organization. Utilize sudo instead of switching to the root user for better security and accountability. Regularly review and update user accounts, removing or disabling unnecessary accounts to maintain system security. 10. Summary Mastering these command line utilities provides a comprehensive toolkit for efficient system management, data handling, network operations, system monitoring, and user management. From secure file transfers and compression to network diagnostics, package management, and system performance analysis, these tools form the backbone of effective command line operations. The ability to gather detailed system information, monitor performance in real-time, and manage users and groups effectively are crucial skills for system administrators and power users. By incorporating these utilities into your workflow, you can significantly enhance your ability to manage, troubleshoot, and optimize Linux systems. Regular practice and application of these utilities will significantly enhance your proficiency in various tech-related roles, from system administration to software development and cybersecurity.","title":"Command Line Utilities"},{"location":"command-line-utilities/#command-line-utilities-sop","text":"","title":"Command Line Utilities SOP"},{"location":"command-line-utilities/#1-introduction","text":"This Standard Operating Procedure (SOP) outlines essential command line utilities that enhance productivity and efficiency in various tech-related tasks. These tools are crucial for data transfer, file compression, network management, package management, system monitoring, and user administration. Mastering these utilities will significantly improve your command line proficiency and overall system management capabilities.","title":"1. Introduction"},{"location":"command-line-utilities/#2-data-transfer","text":"","title":"2. Data Transfer"},{"location":"command-line-utilities/#21-scp-secure-copy-protocol","text":"Securely transfer files between systems using SSH. scp -P 2222 user@remote:/path/to/file /local/directory scp -r user@remote:/directory/ /local/directory","title":"2.1 scp (Secure Copy Protocol)"},{"location":"command-line-utilities/#22-rsync-remote-sync","text":"Efficiently synchronize files and directories between systems. rsync -avz user@remote:/source /local/destination rsync -av --exclude 'path/to/exclude' /source /destination rsync --bwlimit=1000 /source /destination","title":"2.2 rsync (Remote Sync)"},{"location":"command-line-utilities/#23-wget-web-get","text":"Retrieve files from web servers. wget -b url wget --retry-connrefused --waitretry=10 --timeout=60 url","title":"2.3 wget (Web Get)"},{"location":"command-line-utilities/#24-ftp-file-transfer-protocol","text":"Basic file transfer for non-secure data movements. ftp -p host ftp -s:script.txt host","title":"2.4 ftp (File Transfer Protocol)"},{"location":"command-line-utilities/#3-file-compression","text":"","title":"3. File Compression"},{"location":"command-line-utilities/#31-zip","text":"Package and compress files for easy sharing and storage. zip archive.zip -r target_folder/ -x \\*exclude_pattern\\* zip -u archive.zip updated_file.txt","title":"3.1 zip"},{"location":"command-line-utilities/#32-tar","text":"Bundle files and directories efficiently. tar --listed-incremental=snapshot.file -cvzf backup.tar.gz target_directory/ tar czf - target_directory/ | ssh user@remote \"cat > remote_backup.tar.gz\"","title":"3.2 tar"},{"location":"command-line-utilities/#33-gzip","text":"Maximize compression ratios for faster transfers. gzip -S .custom_suffix large_file cat archive_part1.gz archive_part2.gz > combined_archive.gz","title":"3.3 gzip"},{"location":"command-line-utilities/#34-bzip2","text":"Provide superior compression efficiency for large-scale archival. bzip2 -dc archive.bz2 > output_file pbzip2 -p4 massive_file","title":"3.4 bzip2"},{"location":"command-line-utilities/#4-network-tools","text":"","title":"4. Network Tools"},{"location":"command-line-utilities/#41-ping","text":"Test connectivity and measure round-trip time to a host. ping -c 4 google.com","title":"4.1 ping"},{"location":"command-line-utilities/#42-ssh-secure-shell","text":"Securely access and execute commands on remote machines. ssh -p port user@hostname ssh -i ~/.ssh/mykey user@192.168.1.100","title":"4.2 ssh (Secure Shell)"},{"location":"command-line-utilities/#5-package-management","text":"","title":"5. Package Management"},{"location":"command-line-utilities/#51-apt-advanced-package-tool","text":"Manage software on Debian-based systems. sudo apt update && sudo apt upgrade -y echo \"package_name hold\" | sudo dpkg --set-selections","title":"5.1 apt (Advanced Package Tool)"},{"location":"command-line-utilities/#52-brew-homebrew","text":"Package management for macOS. brew tap custom/repo brew services start service_name","title":"5.2 brew (Homebrew)"},{"location":"command-line-utilities/#53-yum-yellowdog-updater-modified","text":"Manage RPM packages on Red Hat-based systems. yum history yum --enablerepo=repo_name install package_name","title":"5.3 yum (Yellowdog Updater, Modified)"},{"location":"command-line-utilities/#54-dpkg-debian-package","text":"Low-level package management for Debian-based systems. dpkg-query -l dpkg-reconfigure package_name","title":"5.4 dpkg (Debian Package)"},{"location":"command-line-utilities/#6-system-information-tools","text":"","title":"6. System Information Tools"},{"location":"command-line-utilities/#61-uname","text":"Display system information. uname -a # Display all information uname -s # Display kernel name uname -r # Display kernel release","title":"6.1 uname"},{"location":"command-line-utilities/#62-lscpu","text":"Display CPU architecture information. lscpu lscpu | grep Virtualization # Check virtualization support","title":"6.2 lscpu"},{"location":"command-line-utilities/#63-lshw","text":"Display detailed hardware information. sudo lshw -short # Display brief hardware summary sudo lshw -C network # Display network hardware details","title":"6.3 lshw"},{"location":"command-line-utilities/#64-dmesg","text":"Display kernel messages. dmesg -Tw # Display kernel messages in real-time with timestamps","title":"6.4 dmesg"},{"location":"command-line-utilities/#7-system-monitoring","text":"","title":"7. System Monitoring"},{"location":"command-line-utilities/#71-top","text":"Monitor system processes and resource usage in real-time. top -b -n 1 > top_output.txt # Capture a snapshot of system state top -p PID1,PID2 # Monitor specific processes","title":"7.1 top"},{"location":"command-line-utilities/#72-htop","text":"Interactive process viewer and system monitor. htop -u username # Monitor processes for a specific user htop --output-setup-json > setup.json # Export htop configuration","title":"7.2 htop"},{"location":"command-line-utilities/#73-iostat","text":"Report CPU statistics and I/O statistics for devices and partitions. iostat -d /dev/sda # Display I/O statistics for a specific device iostat -e # Display extended statistics","title":"7.3 iostat"},{"location":"command-line-utilities/#74-vmstat","text":"Report virtual memory statistics. vmstat -d # Display disk statistics vmstat -e # Display event counter information","title":"7.4 vmstat"},{"location":"command-line-utilities/#8-user-and-group-management","text":"","title":"8. User and Group Management"},{"location":"command-line-utilities/#81-useradd","text":"Create a new user account. useradd -m -d /home/jdoe -e 2023-12-31 jdoe # Create user with home directory and expiration date","title":"8.1 useradd"},{"location":"command-line-utilities/#82-groupadd","text":"Create a new group. groupadd -r -g 101 developers # Create a system group with specific GID","title":"8.2 groupadd"},{"location":"command-line-utilities/#83-sudo","text":"Execute a command as another user, typically with administrative privileges. sudo -u jdoe ls /home/jdoe # Execute command as another user","title":"8.3 sudo"},{"location":"command-line-utilities/#84-passwd","text":"Change user password and manage account locks. passwd -l jdoe # Lock user account passwd -u jdoe # Unlock user account","title":"8.4 passwd"},{"location":"command-line-utilities/#9-best-practices","text":"Always verify the integrity of transferred data. Use compression to reduce bandwidth usage and storage requirements. Regularly update package lists and installed software to ensure security. Exercise caution when removing packages to avoid unintended consequences. Use SSH keys for secure, passwordless authentication when accessing remote systems. Implement rate limiting and throttling for large data transfers to avoid network congestion. Choose the appropriate compression algorithm based on the specific requirements of speed, size, and computational resources. Regularly review and update SSH keys to maintain security. Regularly monitor system performance and resource usage to identify and address issues proactively. Use system information tools to gather detailed hardware and software information for troubleshooting and inventory management. Implement proper user and group management practices to enhance system security and organization. Utilize sudo instead of switching to the root user for better security and accountability. Regularly review and update user accounts, removing or disabling unnecessary accounts to maintain system security.","title":"9. Best Practices"},{"location":"command-line-utilities/#10-summary","text":"Mastering these command line utilities provides a comprehensive toolkit for efficient system management, data handling, network operations, system monitoring, and user management. From secure file transfers and compression to network diagnostics, package management, and system performance analysis, these tools form the backbone of effective command line operations. The ability to gather detailed system information, monitor performance in real-time, and manage users and groups effectively are crucial skills for system administrators and power users. By incorporating these utilities into your workflow, you can significantly enhance your ability to manage, troubleshoot, and optimize Linux systems. Regular practice and application of these utilities will significantly enhance your proficiency in various tech-related roles, from system administration to software development and cybersecurity.","title":"10. Summary"},{"location":"fast-api-testing/","text":"","title":"Testing In FastAPI"},{"location":"fast-api/","text":"Vets Who Code - FastAPI Operations Guide \ud83c\udf96\ufe0f Mission Brief: FastAPI Introduction FastAPI is like a highly efficient FOB (Forward Operating Base) for your web operations. It's: Fast (high-performance) Easy to deploy Built for modern Python operations Automatically documented Production-ready Phase 1: Base Setup Required Equipment # Create virtual environment python -m venv venv # Activate virtual environment # Windows: venv\\Scripts\\activate # Mac/Linux: source venv/bin/activate # Install dependencies pip install fastapi uvicorn First Deployment # main.py from fastapi import FastAPI # Initialize FOB (Create FastAPI instance) app = FastAPI( title=\"VWC API Operations\", description=\"Veteran-focused API operations\", version=\"1.0.0\" ) # First Checkpoint (Root endpoint) @app.get(\"/\") async def base_check(): return { \"status\": \"operational\", \"message\": \"VWC API Standing By\" } Launch Operations # Start the server uvicorn main:app --reload Phase 2: Basic Operations (Routes) Personnel Management System from typing import List, Optional from pydantic import BaseModel from datetime import date # Data Models (Intel Structure) class ServiceMember(BaseModel): id: int first_name: str last_name: str rank: str branch: str service_start: date status: str = \"Active\" # Database Simulation db_personnel = [] # Routes @app.post(\"/personnel/\", response_model=ServiceMember) async def create_personnel(member: ServiceMember): db_personnel.append(member) return member @app.get(\"/personnel/\", response_model=List[ServiceMember]) async def get_all_personnel(): return db_personnel @app.get(\"/personnel/{member_id}\", response_model=ServiceMember) async def get_personnel(member_id: int): for member in db_personnel: if member.id == member_id: return member raise HTTPException(status_code=404, detail=\"Service member not found\") Phase 3: Advanced Operations Authentication & Security from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from datetime import datetime, timedelta # Security Configuration SECRET_KEY = \"your-secret-key\" ALGORITHM = \"HS256\" ACCESS_TOKEN_EXPIRE_MINUTES = 30 pwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\") oauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\") # User Model class User(BaseModel): username: str full_name: Optional[str] = None disabled: Optional[bool] = None # Token Generation def create_access_token(data: dict): to_encode = data.copy() expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({\"exp\": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt # Authentication Route @app.post(\"/token\") async def login(form_data: OAuth2PasswordRequestForm = Depends()): # Authentication logic here access_token = create_access_token(data={\"sub\": form_data.username}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} Award System API from enum import Enum class AwardType(str, Enum): PURPLE_HEART = \"Purple Heart\" BRONZE_STAR = \"Bronze Star\" COMBAT_ACTION = \"Combat Action Ribbon\" class Award(BaseModel): type: AwardType recipient_id: int award_date: date citation: Optional[str] = None @app.post(\"/awards/\") async def issue_award(award: Award, token: str = Depends(oauth2_scheme)): # Award issuing logic return {\"status\": \"Award issued\", \"award\": award} @app.get(\"/personnel/{member_id}/awards\") async def get_member_awards(member_id: int, token: str = Depends(oauth2_scheme)): # Award retrieval logic return {\"member_id\": member_id, \"awards\": []} Phase 4: Database Integration Using SQLAlchemy from sqlalchemy import create_engine, Column, Integer, String, Date from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = \"sqlite:///./vwc_operations.db\" engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() # Database Models class DBServiceMember(Base): __tablename__ = \"service_members\" id = Column(Integer, primary_key=True, index=True) first_name = Column(String) last_name = Column(String) rank = Column(String) branch = Column(String) service_start = Column(Date) status = Column(String) # Database Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() # Updated Routes with Database @app.post(\"/personnel/\", response_model=ServiceMember) async def create_personnel( member: ServiceMember, db: Session = Depends(get_db) ): db_member = DBServiceMember(**member.dict()) db.add(db_member) db.commit() db.refresh(db_member) return db_member Phase 5: Background Tasks Mission Status Updates from fastapi import BackgroundTasks def update_mission_status(mission_id: str): # Simulate long-running task time.sleep(5) # Update mission status logic here print(f\"Mission {mission_id} status updated\") @app.post(\"/missions/{mission_id}/status\") async def update_status( mission_id: str, background_tasks: BackgroundTasks ): background_tasks.add_task(update_mission_status, mission_id) return {\"message\": \"Status update initiated\"} Field Exercise: Complete API Implementation Here's a practical exercise combining these concepts - a Veteran Service Record System: # Complete implementation example from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks from typing import List, Optional from pydantic import BaseModel from datetime import date import asyncio app = FastAPI(title=\"Veteran Service Record System\") # Models class ServiceRecord(BaseModel): id: int name: str service_number: str branch: str rank: str start_date: date end_date: Optional[date] = None status: str awards: List[str] = [] # Simulated Database records_db = {} # Routes @app.post(\"/records/\", response_model=ServiceRecord) async def create_record(record: ServiceRecord): if record.id in records_db: raise HTTPException(status_code=400, detail=\"Record already exists\") records_db[record.id] = record return record @app.get(\"/records/{record_id}\", response_model=ServiceRecord) async def get_record(record_id: int): if record_id not in records_db: raise HTTPException(status_code=404, detail=\"Record not found\") return records_db[record_id] @app.put(\"/records/{record_id}/awards\") async def add_award( record_id: int, award: str, background_tasks: BackgroundTasks ): if record_id not in records_db: raise HTTPException(status_code=404, detail=\"Record not found\") background_tasks.add_task(update_award_database, record_id, award) records_db[record_id].awards.append(award) return {\"message\": \"Award added successfully\"} # Background task async def update_award_database(record_id: int, award: str): await asyncio.sleep(2) # Simulate database update print(f\"Award {award} recorded for service member {record_id}\") Next Mission Parameters Advanced Topics: WebSocket implementations File uploads/downloads Rate limiting Caching Testing FastAPI applications Deployment Operations: Docker containerization Cloud deployment (AWS, Azure, GCP) CI/CD pipelines Production configurations Remember: Document your APIs thoroughly Implement proper security measures Test all endpoints Handle errors gracefully Monitor performance \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Introduction To FastAPI"},{"location":"fast-api/#vets-who-code-fastapi-operations-guide","text":"","title":"Vets Who Code - FastAPI Operations Guide \ud83c\udf96\ufe0f"},{"location":"fast-api/#mission-brief-fastapi-introduction","text":"FastAPI is like a highly efficient FOB (Forward Operating Base) for your web operations. It's: Fast (high-performance) Easy to deploy Built for modern Python operations Automatically documented Production-ready","title":"Mission Brief: FastAPI Introduction"},{"location":"fast-api/#phase-1-base-setup","text":"","title":"Phase 1: Base Setup"},{"location":"fast-api/#required-equipment","text":"# Create virtual environment python -m venv venv # Activate virtual environment # Windows: venv\\Scripts\\activate # Mac/Linux: source venv/bin/activate # Install dependencies pip install fastapi uvicorn","title":"Required Equipment"},{"location":"fast-api/#first-deployment","text":"# main.py from fastapi import FastAPI # Initialize FOB (Create FastAPI instance) app = FastAPI( title=\"VWC API Operations\", description=\"Veteran-focused API operations\", version=\"1.0.0\" ) # First Checkpoint (Root endpoint) @app.get(\"/\") async def base_check(): return { \"status\": \"operational\", \"message\": \"VWC API Standing By\" }","title":"First Deployment"},{"location":"fast-api/#launch-operations","text":"# Start the server uvicorn main:app --reload","title":"Launch Operations"},{"location":"fast-api/#phase-2-basic-operations-routes","text":"","title":"Phase 2: Basic Operations (Routes)"},{"location":"fast-api/#personnel-management-system","text":"from typing import List, Optional from pydantic import BaseModel from datetime import date # Data Models (Intel Structure) class ServiceMember(BaseModel): id: int first_name: str last_name: str rank: str branch: str service_start: date status: str = \"Active\" # Database Simulation db_personnel = [] # Routes @app.post(\"/personnel/\", response_model=ServiceMember) async def create_personnel(member: ServiceMember): db_personnel.append(member) return member @app.get(\"/personnel/\", response_model=List[ServiceMember]) async def get_all_personnel(): return db_personnel @app.get(\"/personnel/{member_id}\", response_model=ServiceMember) async def get_personnel(member_id: int): for member in db_personnel: if member.id == member_id: return member raise HTTPException(status_code=404, detail=\"Service member not found\")","title":"Personnel Management System"},{"location":"fast-api/#phase-3-advanced-operations","text":"","title":"Phase 3: Advanced Operations"},{"location":"fast-api/#authentication-security","text":"from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from datetime import datetime, timedelta # Security Configuration SECRET_KEY = \"your-secret-key\" ALGORITHM = \"HS256\" ACCESS_TOKEN_EXPIRE_MINUTES = 30 pwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\") oauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\") # User Model class User(BaseModel): username: str full_name: Optional[str] = None disabled: Optional[bool] = None # Token Generation def create_access_token(data: dict): to_encode = data.copy() expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({\"exp\": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt # Authentication Route @app.post(\"/token\") async def login(form_data: OAuth2PasswordRequestForm = Depends()): # Authentication logic here access_token = create_access_token(data={\"sub\": form_data.username}) return {\"access_token\": access_token, \"token_type\": \"bearer\"}","title":"Authentication & Security"},{"location":"fast-api/#award-system-api","text":"from enum import Enum class AwardType(str, Enum): PURPLE_HEART = \"Purple Heart\" BRONZE_STAR = \"Bronze Star\" COMBAT_ACTION = \"Combat Action Ribbon\" class Award(BaseModel): type: AwardType recipient_id: int award_date: date citation: Optional[str] = None @app.post(\"/awards/\") async def issue_award(award: Award, token: str = Depends(oauth2_scheme)): # Award issuing logic return {\"status\": \"Award issued\", \"award\": award} @app.get(\"/personnel/{member_id}/awards\") async def get_member_awards(member_id: int, token: str = Depends(oauth2_scheme)): # Award retrieval logic return {\"member_id\": member_id, \"awards\": []}","title":"Award System API"},{"location":"fast-api/#phase-4-database-integration","text":"","title":"Phase 4: Database Integration"},{"location":"fast-api/#using-sqlalchemy","text":"from sqlalchemy import create_engine, Column, Integer, String, Date from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = \"sqlite:///./vwc_operations.db\" engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() # Database Models class DBServiceMember(Base): __tablename__ = \"service_members\" id = Column(Integer, primary_key=True, index=True) first_name = Column(String) last_name = Column(String) rank = Column(String) branch = Column(String) service_start = Column(Date) status = Column(String) # Database Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() # Updated Routes with Database @app.post(\"/personnel/\", response_model=ServiceMember) async def create_personnel( member: ServiceMember, db: Session = Depends(get_db) ): db_member = DBServiceMember(**member.dict()) db.add(db_member) db.commit() db.refresh(db_member) return db_member","title":"Using SQLAlchemy"},{"location":"fast-api/#phase-5-background-tasks","text":"","title":"Phase 5: Background Tasks"},{"location":"fast-api/#mission-status-updates","text":"from fastapi import BackgroundTasks def update_mission_status(mission_id: str): # Simulate long-running task time.sleep(5) # Update mission status logic here print(f\"Mission {mission_id} status updated\") @app.post(\"/missions/{mission_id}/status\") async def update_status( mission_id: str, background_tasks: BackgroundTasks ): background_tasks.add_task(update_mission_status, mission_id) return {\"message\": \"Status update initiated\"}","title":"Mission Status Updates"},{"location":"fast-api/#field-exercise-complete-api-implementation","text":"Here's a practical exercise combining these concepts - a Veteran Service Record System: # Complete implementation example from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks from typing import List, Optional from pydantic import BaseModel from datetime import date import asyncio app = FastAPI(title=\"Veteran Service Record System\") # Models class ServiceRecord(BaseModel): id: int name: str service_number: str branch: str rank: str start_date: date end_date: Optional[date] = None status: str awards: List[str] = [] # Simulated Database records_db = {} # Routes @app.post(\"/records/\", response_model=ServiceRecord) async def create_record(record: ServiceRecord): if record.id in records_db: raise HTTPException(status_code=400, detail=\"Record already exists\") records_db[record.id] = record return record @app.get(\"/records/{record_id}\", response_model=ServiceRecord) async def get_record(record_id: int): if record_id not in records_db: raise HTTPException(status_code=404, detail=\"Record not found\") return records_db[record_id] @app.put(\"/records/{record_id}/awards\") async def add_award( record_id: int, award: str, background_tasks: BackgroundTasks ): if record_id not in records_db: raise HTTPException(status_code=404, detail=\"Record not found\") background_tasks.add_task(update_award_database, record_id, award) records_db[record_id].awards.append(award) return {\"message\": \"Award added successfully\"} # Background task async def update_award_database(record_id: int, award: str): await asyncio.sleep(2) # Simulate database update print(f\"Award {award} recorded for service member {record_id}\")","title":"Field Exercise: Complete API Implementation"},{"location":"fast-api/#next-mission-parameters","text":"Advanced Topics: WebSocket implementations File uploads/downloads Rate limiting Caching Testing FastAPI applications Deployment Operations: Docker containerization Cloud deployment (AWS, Azure, GCP) CI/CD pipelines Production configurations Remember: Document your APIs thoroughly Implement proper security measures Test all endpoints Handle errors gracefully Monitor performance \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Next Mission Parameters"},{"location":"getting-to-know-the-command-line/","text":"Getting to Know the Command Line Introduction The command line interface (CLI) is a powerful tool that allows users to interact directly with their computer's operating system through text-based commands. Despite the prevalence of graphical user interfaces (GUIs), the command line remains an essential skill for developers, system administrators, and power users. This guide will introduce you to the world of command-line interfaces, explain their importance, and help you understand the key components involved. What is the Command Line? The command line, or CLI, is an environment where users can input text commands to perform specific tasks on a computer. Unlike GUIs, which use visual elements for interaction, the CLI relies entirely on textual input and output. Historical Context Originating in the 1960s, the command line predates graphical interfaces, offering an advanced method of computer interaction. This era of computing required users to engage directly with the system through typed commands, a significant evolution from punch cards and manual input methods. Why Use the Command Line? Despite the user-friendliness of modern GUIs, the command line offers several compelling advantages: Speed : Execute commands and manage system resources quickly, bypassing graphical overhead. Versatility : Perform complex operations that might be cumbersome or impossible through a GUI. Automation : Write scripts to automate tasks, saving time and reducing human error. Remote Management : Access and control remote systems without needing a graphical interface. These benefits make the CLI an invaluable tool for various tech-related fields, including software development, system administration, and data science. Understanding Terminals and Shells To effectively use the command line, it's crucial to understand two key components: terminals and shells. Terminal Emulators A terminal emulator is a software application that provides a graphical interface for interacting with the shell. It simulates the functionality of traditional hardware terminals within modern desktop environments. Popular terminal emulators include: Hyper : Cross-platform, built with web technologies, and highly extensible. iTerm2 : Feature-rich terminal for macOS with advanced customization options. PuTTY : Commonly used in Windows environments, supporting various network protocols. Shells The shell acts as an interpreter, executing user commands and managing communication between the user and the kernel. It provides a scripting language and executes system commands and scripts. Common shell types include: Bash (Bourne-Again SHell) : The default shell in many Linux distributions and older macOS versions. Zsh (Z Shell) : The default shell in newer macOS versions, known for its customizability. Fish (Friendly Interactive SHell) : Focused on user-friendliness with features like autosuggestions. Dash (Debian Almquist Shell) : Prioritizes efficiency and speed, often used for system-level scripting. Key Differences: Terminal vs. Shell While often mentioned together, terminals and shells serve distinct roles: Terminal : Provides the user interface for command input and system feedback. Shell : Interprets and executes the commands entered in the terminal. Understanding this distinction helps clarify the layers of interaction in command-line usage. Getting Started with the Command Line To begin using the command line: Open your system's terminal emulator (e.g., Terminal on macOS, Command Prompt on Windows). Familiarize yourself with basic commands like ls (list files), cd (change directory), and pwd (print working directory). Experiment with command options and arguments to modify their behavior. Learn about your system's default shell and consider exploring alternatives that might better suit your needs. Customization and Productivity Tips Enhance your command-line experience with these tips: Customize your terminal's appearance with themes and color schemes. Learn keyboard shortcuts to navigate and edit commands more efficiently. Explore shell plugins and extensions to add functionality. Practice scripting to automate repetitive tasks. Conclusion The command line is a powerful tool that offers speed, versatility, and control over your computing environment. By understanding the roles of terminals and shells and learning to navigate the CLI effectively, you can significantly enhance your productivity and capabilities in various tech-related fields. Whether you're a beginner or looking to deepen your skills, mastering the command line is a valuable investment in your technical toolkit.","title":"Getting To Know The Command Line"},{"location":"getting-to-know-the-command-line/#getting-to-know-the-command-line","text":"","title":"Getting to Know the Command Line"},{"location":"getting-to-know-the-command-line/#introduction","text":"The command line interface (CLI) is a powerful tool that allows users to interact directly with their computer's operating system through text-based commands. Despite the prevalence of graphical user interfaces (GUIs), the command line remains an essential skill for developers, system administrators, and power users. This guide will introduce you to the world of command-line interfaces, explain their importance, and help you understand the key components involved.","title":"Introduction"},{"location":"getting-to-know-the-command-line/#what-is-the-command-line","text":"The command line, or CLI, is an environment where users can input text commands to perform specific tasks on a computer. Unlike GUIs, which use visual elements for interaction, the CLI relies entirely on textual input and output.","title":"What is the Command Line?"},{"location":"getting-to-know-the-command-line/#historical-context","text":"Originating in the 1960s, the command line predates graphical interfaces, offering an advanced method of computer interaction. This era of computing required users to engage directly with the system through typed commands, a significant evolution from punch cards and manual input methods.","title":"Historical Context"},{"location":"getting-to-know-the-command-line/#why-use-the-command-line","text":"Despite the user-friendliness of modern GUIs, the command line offers several compelling advantages: Speed : Execute commands and manage system resources quickly, bypassing graphical overhead. Versatility : Perform complex operations that might be cumbersome or impossible through a GUI. Automation : Write scripts to automate tasks, saving time and reducing human error. Remote Management : Access and control remote systems without needing a graphical interface. These benefits make the CLI an invaluable tool for various tech-related fields, including software development, system administration, and data science.","title":"Why Use the Command Line?"},{"location":"getting-to-know-the-command-line/#understanding-terminals-and-shells","text":"To effectively use the command line, it's crucial to understand two key components: terminals and shells.","title":"Understanding Terminals and Shells"},{"location":"getting-to-know-the-command-line/#terminal-emulators","text":"A terminal emulator is a software application that provides a graphical interface for interacting with the shell. It simulates the functionality of traditional hardware terminals within modern desktop environments. Popular terminal emulators include: Hyper : Cross-platform, built with web technologies, and highly extensible. iTerm2 : Feature-rich terminal for macOS with advanced customization options. PuTTY : Commonly used in Windows environments, supporting various network protocols.","title":"Terminal Emulators"},{"location":"getting-to-know-the-command-line/#shells","text":"The shell acts as an interpreter, executing user commands and managing communication between the user and the kernel. It provides a scripting language and executes system commands and scripts. Common shell types include: Bash (Bourne-Again SHell) : The default shell in many Linux distributions and older macOS versions. Zsh (Z Shell) : The default shell in newer macOS versions, known for its customizability. Fish (Friendly Interactive SHell) : Focused on user-friendliness with features like autosuggestions. Dash (Debian Almquist Shell) : Prioritizes efficiency and speed, often used for system-level scripting.","title":"Shells"},{"location":"getting-to-know-the-command-line/#key-differences-terminal-vs-shell","text":"While often mentioned together, terminals and shells serve distinct roles: Terminal : Provides the user interface for command input and system feedback. Shell : Interprets and executes the commands entered in the terminal. Understanding this distinction helps clarify the layers of interaction in command-line usage.","title":"Key Differences: Terminal vs. Shell"},{"location":"getting-to-know-the-command-line/#getting-started-with-the-command-line","text":"To begin using the command line: Open your system's terminal emulator (e.g., Terminal on macOS, Command Prompt on Windows). Familiarize yourself with basic commands like ls (list files), cd (change directory), and pwd (print working directory). Experiment with command options and arguments to modify their behavior. Learn about your system's default shell and consider exploring alternatives that might better suit your needs.","title":"Getting Started with the Command Line"},{"location":"getting-to-know-the-command-line/#customization-and-productivity-tips","text":"Enhance your command-line experience with these tips: Customize your terminal's appearance with themes and color schemes. Learn keyboard shortcuts to navigate and edit commands more efficiently. Explore shell plugins and extensions to add functionality. Practice scripting to automate repetitive tasks.","title":"Customization and Productivity Tips"},{"location":"getting-to-know-the-command-line/#conclusion","text":"The command line is a powerful tool that offers speed, versatility, and control over your computing environment. By understanding the roles of terminals and shells and learning to navigate the CLI effectively, you can significantly enhance your productivity and capabilities in various tech-related fields. Whether you're a beginner or looking to deepen your skills, mastering the command line is a valuable investment in your technical toolkit.","title":"Conclusion"},{"location":"git-and-github-voice-overview/","text":"Lessons Voice Overview Welcome to the voice overview of all the lessons. In this audio guide, we will cover the key topics and concepts that you'll be learning throughout the course. Listen to the Overview Your browser does not support the audio element.","title":"AI Voice Overview"},{"location":"git-and-github-voice-overview/#lessons-voice-overview","text":"Welcome to the voice overview of all the lessons. In this audio guide, we will cover the key topics and concepts that you'll be learning throughout the course.","title":"Lessons Voice Overview"},{"location":"git-and-github-voice-overview/#listen-to-the-overview","text":"Your browser does not support the audio element.","title":"Listen to the Overview"},{"location":"git-and-github/","text":"Git and GitHub (Terminal & UI) Overview Welcome to the \u201cGit and GitHub (Terminal & UI)\u201d guide! Whether you\u2019re a beginner or an experienced developer, this resource provides everything you need to master Git, GitHub, and AI-powered tools like GitHub Copilot. From essential workflows to advanced concepts, this guide will help you optimize your development process. What You Will Learn Getting Started with Git Install and configure Git on your system. Set up your user identity for version control. Create a local Git repository and commit code changes. Sync your local repository with GitHub for collaboration and secure cloud storage. GitHub Account Setup and Profile Optimization Create and set up your GitHub account. Optimize your GitHub profile with README files, pinned repositories, and SSH keys. Explore GitHub\u2019s collaborative features like Issues, Pull Requests, and Discussions to manage projects and engage with the developer community. Basic Git Operations Master fundamental Git commands: git init , git clone , git add , git commit , git push , and git pull . Learn to manage branches effectively for feature-based development. Use GitHub\u2019s web interface to visualize changes, open pull requests, and collaborate with developers. Intermediate and Advanced Git Concepts Learn branching and merging strategies for managing complex projects. Dive into rebasing, stashing, and conflict resolution. Use reflog and cherry-pick to recover lost commits or move changes between branches. Implement strategies for meaningful commit messages and maintaining a clean Git history. Collaboration on GitHub Fork repositories, open pull requests, and manage Issues and Projects for collaborative development. Set up Continuous Integration (CI) pipelines in GitHub to automatically run tests and maintain code quality. Use GitHub\u2019s security features like vulnerability alerts, branch protection, and Code Scanning to secure your projects. GitHub Copilot and AI-Driven Coding Learn about GitHub Copilot, an AI-powered tool for code completion. Integrate Copilot to generate code snippets and boost productivity. Explore GitHub Copilot CLI for automating tasks like project scaffolding and file generation. Practical Applications and Hands-On Practice Follow real-world examples to set up repositories, manage branches, and contribute to open-source projects. Hands-on labs reinforce concepts, allowing you to apply Git workflows in your own projects. Practice resolving merge conflicts, writing effective pull requests, and setting up GitHub Actions. Best Practices for Git and GitHub Maintain clean repositories using .gitignore , squashing commits, and writing clear commit messages. Explore workflows like Gitflow, feature branching, and trunk-based development, and choose the best approach for your projects. Learn guidelines for contributing to open-source projects, including issue tracking, code reviews, and community contribution. Why Learn Git and GitHub? Git and GitHub are indispensable tools in modern software development. Git allows you to track code changes, collaborate with others, and experiment without affecting the main project. GitHub builds on this by offering a platform for hosting repositories, remote collaboration, and integrating with tools for seamless version control. Mastering Git and GitHub will enhance your ability to manage code, collaborate effectively, and contribute to open-source projects. Leveraging AI-powered tools like GitHub Copilot will also streamline your workflow, keeping you ahead in the fast-paced tech industry. Who Is This Guide For? New developers looking to build a solid foundation in version control and collaborative development. Intermediate developers aiming to refine their skills with advanced Git techniques like conflict resolution, branching strategies, and GitHub Actions. Experienced developers seeking to optimize their workflow with AI-powered tools like GitHub Copilot and Copilot CLI. By the end of this guide, you\u2019ll confidently use Git for version control, collaborate on GitHub, and integrate AI-driven tools into your development process. Whether working on solo projects or large-scale collaborations, this guide will help you get the most out of Git, GitHub, and Copilot.","title":"Git And Github"},{"location":"git-and-github/#git-and-github-terminal-ui-overview","text":"Welcome to the \u201cGit and GitHub (Terminal & UI)\u201d guide! Whether you\u2019re a beginner or an experienced developer, this resource provides everything you need to master Git, GitHub, and AI-powered tools like GitHub Copilot. From essential workflows to advanced concepts, this guide will help you optimize your development process.","title":"Git and GitHub (Terminal & UI) Overview"},{"location":"git-and-github/#what-you-will-learn","text":"","title":"What You Will Learn"},{"location":"git-and-github/#getting-started-with-git","text":"Install and configure Git on your system. Set up your user identity for version control. Create a local Git repository and commit code changes. Sync your local repository with GitHub for collaboration and secure cloud storage.","title":"Getting Started with Git"},{"location":"git-and-github/#github-account-setup-and-profile-optimization","text":"Create and set up your GitHub account. Optimize your GitHub profile with README files, pinned repositories, and SSH keys. Explore GitHub\u2019s collaborative features like Issues, Pull Requests, and Discussions to manage projects and engage with the developer community.","title":"GitHub Account Setup and Profile Optimization"},{"location":"git-and-github/#basic-git-operations","text":"Master fundamental Git commands: git init , git clone , git add , git commit , git push , and git pull . Learn to manage branches effectively for feature-based development. Use GitHub\u2019s web interface to visualize changes, open pull requests, and collaborate with developers.","title":"Basic Git Operations"},{"location":"git-and-github/#intermediate-and-advanced-git-concepts","text":"Learn branching and merging strategies for managing complex projects. Dive into rebasing, stashing, and conflict resolution. Use reflog and cherry-pick to recover lost commits or move changes between branches. Implement strategies for meaningful commit messages and maintaining a clean Git history.","title":"Intermediate and Advanced Git Concepts"},{"location":"git-and-github/#collaboration-on-github","text":"Fork repositories, open pull requests, and manage Issues and Projects for collaborative development. Set up Continuous Integration (CI) pipelines in GitHub to automatically run tests and maintain code quality. Use GitHub\u2019s security features like vulnerability alerts, branch protection, and Code Scanning to secure your projects.","title":"Collaboration on GitHub"},{"location":"git-and-github/#github-copilot-and-ai-driven-coding","text":"Learn about GitHub Copilot, an AI-powered tool for code completion. Integrate Copilot to generate code snippets and boost productivity. Explore GitHub Copilot CLI for automating tasks like project scaffolding and file generation.","title":"GitHub Copilot and AI-Driven Coding"},{"location":"git-and-github/#practical-applications-and-hands-on-practice","text":"Follow real-world examples to set up repositories, manage branches, and contribute to open-source projects. Hands-on labs reinforce concepts, allowing you to apply Git workflows in your own projects. Practice resolving merge conflicts, writing effective pull requests, and setting up GitHub Actions.","title":"Practical Applications and Hands-On Practice"},{"location":"git-and-github/#best-practices-for-git-and-github","text":"Maintain clean repositories using .gitignore , squashing commits, and writing clear commit messages. Explore workflows like Gitflow, feature branching, and trunk-based development, and choose the best approach for your projects. Learn guidelines for contributing to open-source projects, including issue tracking, code reviews, and community contribution.","title":"Best Practices for Git and GitHub"},{"location":"git-and-github/#why-learn-git-and-github","text":"Git and GitHub are indispensable tools in modern software development. Git allows you to track code changes, collaborate with others, and experiment without affecting the main project. GitHub builds on this by offering a platform for hosting repositories, remote collaboration, and integrating with tools for seamless version control. Mastering Git and GitHub will enhance your ability to manage code, collaborate effectively, and contribute to open-source projects. Leveraging AI-powered tools like GitHub Copilot will also streamline your workflow, keeping you ahead in the fast-paced tech industry.","title":"Why Learn Git and GitHub?"},{"location":"git-and-github/#who-is-this-guide-for","text":"New developers looking to build a solid foundation in version control and collaborative development. Intermediate developers aiming to refine their skills with advanced Git techniques like conflict resolution, branching strategies, and GitHub Actions. Experienced developers seeking to optimize their workflow with AI-powered tools like GitHub Copilot and Copilot CLI. By the end of this guide, you\u2019ll confidently use Git for version control, collaborate on GitHub, and integrate AI-driven tools into your development process. Whether working on solo projects or large-scale collaborations, this guide will help you get the most out of Git, GitHub, and Copilot.","title":"Who Is This Guide For?"},{"location":"git-flow/","text":"Git Flow Overview Understanding Git Flow Introduction This guide will help you understand Git Flow, an advanced workflow that simplifies the management of complex projects. Git Flow introduces a branching model designed to keep your development process organized, from feature development to handling hotfixes and releases. Learning Outcomes By the end of this guide, you will: Understand what Git Flow is and how it improves project workflow. Implement a feature using Git Flow. Manage hotfixes and releases effectively. Use Git tags for version control and learn versioning best practices. What is Git Flow? (UI & Terminal) Definition Git Flow is a branching model that helps teams manage project development in a structured way. It ensures that work on new features, bug fixes, and releases is done in isolation and merged back into the main codebase when ready. Key Components Main Branch : The production-ready branch, always reflecting the latest release. Develop Branch : The integration branch where features are merged and tested before release. Feature Branches : Temporary branches for developing new features or functionalities. Release Branches : Used to prepare new releases, allowing final fixes and tests. Hotfix Branches : Created for critical patches in the production branch. Implementing a Feature using Git Flow (Terminal) Workflow for Features Git Flow makes it easy to develop new features in isolation before integrating them into the main codebase. Checkout the develop branch: bash git checkout develop Create a new feature branch: bash git checkout -b feature/new-feature Develop the feature: Add your code and commit regularly: bash git add . git commit -m \"Start implementing new feature\" Merge the feature back into develop: Once the feature is complete: bash git checkout develop git merge feature/new-feature Delete the feature branch (optional): Clean up by deleting the feature branch: bash git branch -d feature/new-feature Hotfixes and Releases (Terminal) Hotfix Workflow Hotfixes are quick patches applied directly to the production code. Git Flow makes it easy to apply fixes and keep both the main and develop branches updated. Create a hotfix branch from main: bash git checkout -b hotfix/urgent-fix main Apply the fix and commit it: bash git add . git commit -m \"Apply urgent fix for production\" Merge the fix back into main and develop: bash git checkout main git merge hotfix/urgent-fix git checkout develop git merge hotfix/urgent-fix Release Workflow Releases prepare the develop branch for production. Final bug fixes, versioning, and testing occur on the release branch before merging into main. Create a release branch from develop: bash git checkout -b release/v1.0 develop Perform final changes and commit: bash git add . git commit -m \"Prepare for release v1.0\" Merge the release into main and tag the release: bash git checkout main git merge release/v1.0 git tag -a v1.0 -m \"Release version 1.0\" Merge the release back into develop (to ensure any last-minute fixes are included): bash git checkout develop git merge main Git Tags and Versioning (Terminal) Using Git Tags Tags allow you to mark important points in your project's history, such as a new release. Tags can be lightweight (simple references) or annotated (contain metadata). Create an annotated tag for a release: bash git tag -a v1.0 -m \"Release version 1.0\" Push the tags to your remote repository: bash git push origin --tags Versioning Practices When tagging releases, many developers follow semantic versioning, which uses the format MAJOR.MINOR.PATCH. For example: MAJOR: Increment for incompatible changes (e.g., v2.0.0). MINOR: Increment for new backward-compatible functionality (e.g., v1.1.0). PATCH: Increment for backward-compatible bug fixes (e.g., v1.0.1). Summary With Git Flow, you've learned how to manage features, releases, and hotfixes in a structured, organized way. You also gained an understanding of tagging releases and versioning best practices to keep your projects clean and maintainable. Keep practicing these workflows, and you'll streamline your project management processes significantly!","title":"Git Flow"},{"location":"git-flow/#git-flow-overview","text":"","title":"Git Flow Overview"},{"location":"git-flow/#understanding-git-flow","text":"","title":"Understanding Git Flow"},{"location":"git-flow/#introduction","text":"This guide will help you understand Git Flow, an advanced workflow that simplifies the management of complex projects. Git Flow introduces a branching model designed to keep your development process organized, from feature development to handling hotfixes and releases.","title":"Introduction"},{"location":"git-flow/#learning-outcomes","text":"By the end of this guide, you will: Understand what Git Flow is and how it improves project workflow. Implement a feature using Git Flow. Manage hotfixes and releases effectively. Use Git tags for version control and learn versioning best practices.","title":"Learning Outcomes"},{"location":"git-flow/#what-is-git-flow-ui-terminal","text":"","title":"What is Git Flow? (UI & Terminal)"},{"location":"git-flow/#definition","text":"Git Flow is a branching model that helps teams manage project development in a structured way. It ensures that work on new features, bug fixes, and releases is done in isolation and merged back into the main codebase when ready.","title":"Definition"},{"location":"git-flow/#key-components","text":"Main Branch : The production-ready branch, always reflecting the latest release. Develop Branch : The integration branch where features are merged and tested before release. Feature Branches : Temporary branches for developing new features or functionalities. Release Branches : Used to prepare new releases, allowing final fixes and tests. Hotfix Branches : Created for critical patches in the production branch.","title":"Key Components"},{"location":"git-flow/#implementing-a-feature-using-git-flow-terminal","text":"","title":"Implementing a Feature using Git Flow (Terminal)"},{"location":"git-flow/#workflow-for-features","text":"Git Flow makes it easy to develop new features in isolation before integrating them into the main codebase. Checkout the develop branch: bash git checkout develop Create a new feature branch: bash git checkout -b feature/new-feature Develop the feature: Add your code and commit regularly: bash git add . git commit -m \"Start implementing new feature\" Merge the feature back into develop: Once the feature is complete: bash git checkout develop git merge feature/new-feature Delete the feature branch (optional): Clean up by deleting the feature branch: bash git branch -d feature/new-feature","title":"Workflow for Features"},{"location":"git-flow/#hotfixes-and-releases-terminal","text":"","title":"Hotfixes and Releases (Terminal)"},{"location":"git-flow/#hotfix-workflow","text":"Hotfixes are quick patches applied directly to the production code. Git Flow makes it easy to apply fixes and keep both the main and develop branches updated. Create a hotfix branch from main: bash git checkout -b hotfix/urgent-fix main Apply the fix and commit it: bash git add . git commit -m \"Apply urgent fix for production\" Merge the fix back into main and develop: bash git checkout main git merge hotfix/urgent-fix git checkout develop git merge hotfix/urgent-fix","title":"Hotfix Workflow"},{"location":"git-flow/#release-workflow","text":"Releases prepare the develop branch for production. Final bug fixes, versioning, and testing occur on the release branch before merging into main. Create a release branch from develop: bash git checkout -b release/v1.0 develop Perform final changes and commit: bash git add . git commit -m \"Prepare for release v1.0\" Merge the release into main and tag the release: bash git checkout main git merge release/v1.0 git tag -a v1.0 -m \"Release version 1.0\" Merge the release back into develop (to ensure any last-minute fixes are included): bash git checkout develop git merge main","title":"Release Workflow"},{"location":"git-flow/#git-tags-and-versioning-terminal","text":"","title":"Git Tags and Versioning (Terminal)"},{"location":"git-flow/#using-git-tags","text":"Tags allow you to mark important points in your project's history, such as a new release. Tags can be lightweight (simple references) or annotated (contain metadata). Create an annotated tag for a release: bash git tag -a v1.0 -m \"Release version 1.0\" Push the tags to your remote repository: bash git push origin --tags","title":"Using Git Tags"},{"location":"git-flow/#versioning-practices","text":"When tagging releases, many developers follow semantic versioning, which uses the format MAJOR.MINOR.PATCH. For example: MAJOR: Increment for incompatible changes (e.g., v2.0.0). MINOR: Increment for new backward-compatible functionality (e.g., v1.1.0). PATCH: Increment for backward-compatible bug fixes (e.g., v1.0.1).","title":"Versioning Practices"},{"location":"git-flow/#summary","text":"With Git Flow, you've learned how to manage features, releases, and hotfixes in a structured, organized way. You also gained an understanding of tagging releases and versioning best practices to keep your projects clean and maintainable. Keep practicing these workflows, and you'll streamline your project management processes significantly!","title":"Summary"},{"location":"github-cli/","text":"GitHub CLI Overview Introduction to GitHub CLI Introduction This guide covers the essential aspects of GitHub CLI (Command Line Interface), a powerful tool that allows you to interact with GitHub repositories directly from your terminal. Whether you're creating pull requests, managing issues, or navigating repositories, GitHub CLI helps streamline your workflow. Learning Outcomes By the end of this guide, you will: Install GitHub CLI Execute basic GitHub CLI commands Create and manage aliases for frequently used operations Authenticate your GitHub account via the CLI Installing GitHub CLI (Terminal) Installation Steps For macOS users: brew install gh For Ubuntu users: sudo apt install gh Verification To ensure the installation was successful, check the installed version: gh --version Basic GitHub CLI Commands (Terminal) Key Commands View repository details: gh repo view Check pull request status: gh pr status List repository issues: gh issue list Creating Aliases in GitHub CLI (Terminal) Aliases let you create shortcuts for frequently used commands to save time. For example, to create an alias for viewing pull requests: gh alias set pr-list 'pr list' Now, instead of typing gh pr list , you can simply type gh pr-list . Authentication with GitHub CLI (Terminal) To authenticate GitHub CLI with your GitHub account, use the following command: gh auth login Follow the on-screen prompts to complete the authentication process. Managing Repositories with GitHub CLI Learning Outcomes Create and clone repositories using GitHub CLI Fork repositories and create pull requests Manage issues within a repository Clean up repositories efficiently Creating and Cloning Repositories (Terminal) To create a new repository: gh repo create To clone an existing repository: gh repo clone Forking and Making Pull Requests (Terminal) Fork a repository to your account: gh repo fork Create a pull request from your branch: gh pr create Follow the interactive prompts to provide a title, description, and reviewers for your pull request. Issue Management (Terminal) To create a new issue: gh issue create List all open issues: gh issue list Close an issue by its number: gh issue close Cleaning Up Repositories (Terminal) To delete a repository from GitHub: gh repo delete Navigating GitHub with GitHub CLI Learning Outcomes Manage issues and pull requests efficiently Work with GitHub Gists and Actions Navigate between repositories Use search filters to find specific repositories or issues Managing Issues and Pull Requests (Terminal) To view the status of all open issues: gh issue status To check the status of pull requests: gh pr status Working with Gists and Actions (Terminal) To create a GitHub Gist from a file: gh gist create To view the list of GitHub Actions workflows: gh run list Navigating Repositories (Terminal) To open the main page of a repository in your browser: gh repo view --web This command opens the repository's webpage, making it easier to review and interact with the project. Searching and Filtering (Terminal) To search for repositories owned by a specific user or organization: gh repo list --limit To filter issues based on specific labels: gh issue list --label \"bug\" By mastering GitHub CLI, you can significantly boost your productivity by performing GitHub operations directly from the terminal. Keep practicing these commands and use GitHub CLI as part of your development workflow for faster and more efficient project management!","title":"Github CLI"},{"location":"github-cli/#github-cli-overview","text":"","title":"GitHub CLI Overview"},{"location":"github-cli/#introduction-to-github-cli","text":"","title":"Introduction to GitHub CLI"},{"location":"github-cli/#introduction","text":"This guide covers the essential aspects of GitHub CLI (Command Line Interface), a powerful tool that allows you to interact with GitHub repositories directly from your terminal. Whether you're creating pull requests, managing issues, or navigating repositories, GitHub CLI helps streamline your workflow.","title":"Introduction"},{"location":"github-cli/#learning-outcomes","text":"By the end of this guide, you will: Install GitHub CLI Execute basic GitHub CLI commands Create and manage aliases for frequently used operations Authenticate your GitHub account via the CLI","title":"Learning Outcomes"},{"location":"github-cli/#installing-github-cli-terminal","text":"","title":"Installing GitHub CLI (Terminal)"},{"location":"github-cli/#installation-steps","text":"For macOS users: brew install gh For Ubuntu users: sudo apt install gh","title":"Installation Steps"},{"location":"github-cli/#verification","text":"To ensure the installation was successful, check the installed version: gh --version","title":"Verification"},{"location":"github-cli/#basic-github-cli-commands-terminal","text":"","title":"Basic GitHub CLI Commands (Terminal)"},{"location":"github-cli/#key-commands","text":"View repository details: gh repo view Check pull request status: gh pr status List repository issues: gh issue list","title":"Key Commands"},{"location":"github-cli/#creating-aliases-in-github-cli-terminal","text":"Aliases let you create shortcuts for frequently used commands to save time. For example, to create an alias for viewing pull requests: gh alias set pr-list 'pr list' Now, instead of typing gh pr list , you can simply type gh pr-list .","title":"Creating Aliases in GitHub CLI (Terminal)"},{"location":"github-cli/#authentication-with-github-cli-terminal","text":"To authenticate GitHub CLI with your GitHub account, use the following command: gh auth login Follow the on-screen prompts to complete the authentication process.","title":"Authentication with GitHub CLI (Terminal)"},{"location":"github-cli/#managing-repositories-with-github-cli","text":"","title":"Managing Repositories with GitHub CLI"},{"location":"github-cli/#learning-outcomes_1","text":"Create and clone repositories using GitHub CLI Fork repositories and create pull requests Manage issues within a repository Clean up repositories efficiently","title":"Learning Outcomes"},{"location":"github-cli/#creating-and-cloning-repositories-terminal","text":"To create a new repository: gh repo create To clone an existing repository: gh repo clone ","title":"Creating and Cloning Repositories (Terminal)"},{"location":"github-cli/#forking-and-making-pull-requests-terminal","text":"Fork a repository to your account: gh repo fork Create a pull request from your branch: gh pr create Follow the interactive prompts to provide a title, description, and reviewers for your pull request.","title":"Forking and Making Pull Requests (Terminal)"},{"location":"github-cli/#issue-management-terminal","text":"To create a new issue: gh issue create List all open issues: gh issue list Close an issue by its number: gh issue close ","title":"Issue Management (Terminal)"},{"location":"github-cli/#cleaning-up-repositories-terminal","text":"To delete a repository from GitHub: gh repo delete ","title":"Cleaning Up Repositories (Terminal)"},{"location":"github-cli/#navigating-github-with-github-cli","text":"","title":"Navigating GitHub with GitHub CLI"},{"location":"github-cli/#learning-outcomes_2","text":"Manage issues and pull requests efficiently Work with GitHub Gists and Actions Navigate between repositories Use search filters to find specific repositories or issues","title":"Learning Outcomes"},{"location":"github-cli/#managing-issues-and-pull-requests-terminal","text":"To view the status of all open issues: gh issue status To check the status of pull requests: gh pr status","title":"Managing Issues and Pull Requests (Terminal)"},{"location":"github-cli/#working-with-gists-and-actions-terminal","text":"To create a GitHub Gist from a file: gh gist create To view the list of GitHub Actions workflows: gh run list","title":"Working with Gists and Actions (Terminal)"},{"location":"github-cli/#navigating-repositories-terminal","text":"To open the main page of a repository in your browser: gh repo view --web This command opens the repository's webpage, making it easier to review and interact with the project.","title":"Navigating Repositories (Terminal)"},{"location":"github-cli/#searching-and-filtering-terminal","text":"To search for repositories owned by a specific user or organization: gh repo list --limit To filter issues based on specific labels: gh issue list --label \"bug\" By mastering GitHub CLI, you can significantly boost your productivity by performing GitHub operations directly from the terminal. Keep practicing these commands and use GitHub CLI as part of your development workflow for faster and more efficient project management!","title":"Searching and Filtering (Terminal)"},{"location":"intro-to-python/","text":"Vets Who Code - Python Fundamentals \ud83c\udf96\ufe0f Mission Briefing Welcome to the Python track of Vets Who Code! Like any good military operation, we'll break this down into clear, manageable objectives. Your military experience has already equipped you with the discipline and problem-solving skills needed to excel in programming. Phase 1: Establishing Base (Setup) Setting Up Your FOB (Forward Operating Base) Download Python from python.org (like requisitioning new equipment) Install with \"Add Python to PATH\" checked (establishing your supply lines) Verify installation in terminal: python --version First Boots on the Ground # Your first line of code is like your first patrol print(\"Vets Who Code: Reporting for Duty!\") Phase 2: Basic Training Intelligence Types (Data Types) # Personnel Count (Integer) squad_size = 12 # Supply Levels (Float) fuel_level = 85.5 # Call Signs (String) unit_name = \"Alpha\" status = 'Oscar Mike' # 'On Mission' # Mission Status (Boolean) is_deployed = True mission_complete = False # Intel Not Available (None) pending_orders = None Field Communications (Basic Operations) # Tactical Math available_transport = 5 required_transport = 3 total_transport = available_transport + required_transport remaining_transport = available_transport - required_transport # Unit Designations battalion = \"2nd\" division = \"Infantry\" unit = battalion + \" \" + division # 2nd Infantry # Field Reports print(f\"Unit Strength: {squad_size}\") print(f\"Unit Status: {status}\") Phase 3: Combat Operations (Control Flow) Mission Planning (If Statements) def check_readiness(troops, vehicles): if troops >= 10 and vehicles >= 2: return \"Unit is Combat Ready\" elif troops >= 5: return \"Unit is Patrol Ready\" else: return \"Unit Needs Reinforcement\" # Example Usage unit_status = check_readiness(8, 1) print(unit_status) Patrol Patterns (Loops) # Perimeter Check (For Loop) sectors = [\"North\", \"East\", \"South\", \"West\"] for sector in sectors: print(f\"Sector {sector} is secure\") # Watch Rotation (While Loop) watch_hours = 4 current_hour = 0 while current_hour < watch_hours: print(f\"Hour {current_hour + 1} of watch\") current_hour += 1 Phase 4: Equipment and Logistics (Data Structures) Equipment Roster (Lists) # Basic gear list gear = [\"rifle\", \"nods\", \"radio\", \"ruck\"] # Adding gear gear.append(\"ifak\") # Adds to end gear.insert(0, \"weapon\") # Adds at position # Checking gear print(f\"First item: {gear[0]}\") print(f\"Last item: {gear[-1]}\") # Removing gear gear.remove(\"radio\") # Removes specific item last_item = gear.pop() # Removes and returns last item Mission Intel (Dictionaries) # Mission details mission = { \"type\": \"Training\", \"location\": \"Virtual FOB\", \"duration\": 14, \"unit\": \"VWC Python Platoon\" } # Accessing intel print(f\"Mission Type: {mission['type']}\") print(f\"Location: {mission.get('location')}\") # Updating intel mission[\"status\"] = \"In Progress\" mission[\"duration\"] = 21 Phase 5: Field Exercise Here's a practical exercise combining the concepts - a Military Awards Database: def awards_database(): \"\"\" Military Awards Reference System \"\"\" awards = { \"1\": { \"name\": \"Purple Heart\", \"criteria\": \"Wounded in combat\", \"precedence\": \"High\", \"branch\": \"All services\" }, \"2\": { \"name\": \"Combat Action Ribbon\", \"criteria\": \"Engaged in combat\", \"precedence\": \"Medium\", \"branch\": \"Navy/Marines\" } } while True: print(\"\\nVWC Awards Database\") print(\"------------------\") for key, award in awards.items(): print(f\"{key}: {award['name']}\") print(\"3: Exit System\") selection = input(\"\\nEnter award number: \") if selection == \"3\": print(\"Database Secured!\") break elif selection in awards: award = awards[selection] print(f\"\\nName: {award['name']}\") print(f\"Criteria: {award['criteria']}\") print(f\"Precedence: {award['precedence']}\") print(f\"Branch: {award['branch']}\") else: print(\"Invalid selection, try again\") if __name__ == \"__main__\": awards_database() Next Mission Parameters Coming Up Next: Functions (Battle Drills) Error Handling (Combat Contingencies) File Operations (Mission Logs) Classes (Unit Organization) Modules (Support Elements) Core Values to Remember: Attention to Detail (Clean Code) Adapt and Overcome (Problem Solving) Leave No One Behind (Help Others Learn) Mission First (Working Code) Ready to move to advanced operations? Remember: Stay motivated Keep practicing Debug with discipline Learn from each mission \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Introduction To Python"},{"location":"intro-to-python/#vets-who-code-python-fundamentals","text":"","title":"Vets Who Code - Python Fundamentals \ud83c\udf96\ufe0f"},{"location":"intro-to-python/#mission-briefing","text":"Welcome to the Python track of Vets Who Code! Like any good military operation, we'll break this down into clear, manageable objectives. Your military experience has already equipped you with the discipline and problem-solving skills needed to excel in programming.","title":"Mission Briefing"},{"location":"intro-to-python/#phase-1-establishing-base-setup","text":"","title":"Phase 1: Establishing Base (Setup)"},{"location":"intro-to-python/#setting-up-your-fob-forward-operating-base","text":"Download Python from python.org (like requisitioning new equipment) Install with \"Add Python to PATH\" checked (establishing your supply lines) Verify installation in terminal: python --version","title":"Setting Up Your FOB (Forward Operating Base)"},{"location":"intro-to-python/#first-boots-on-the-ground","text":"# Your first line of code is like your first patrol print(\"Vets Who Code: Reporting for Duty!\")","title":"First Boots on the Ground"},{"location":"intro-to-python/#phase-2-basic-training","text":"","title":"Phase 2: Basic Training"},{"location":"intro-to-python/#intelligence-types-data-types","text":"# Personnel Count (Integer) squad_size = 12 # Supply Levels (Float) fuel_level = 85.5 # Call Signs (String) unit_name = \"Alpha\" status = 'Oscar Mike' # 'On Mission' # Mission Status (Boolean) is_deployed = True mission_complete = False # Intel Not Available (None) pending_orders = None","title":"Intelligence Types (Data Types)"},{"location":"intro-to-python/#field-communications-basic-operations","text":"# Tactical Math available_transport = 5 required_transport = 3 total_transport = available_transport + required_transport remaining_transport = available_transport - required_transport # Unit Designations battalion = \"2nd\" division = \"Infantry\" unit = battalion + \" \" + division # 2nd Infantry # Field Reports print(f\"Unit Strength: {squad_size}\") print(f\"Unit Status: {status}\")","title":"Field Communications (Basic Operations)"},{"location":"intro-to-python/#phase-3-combat-operations-control-flow","text":"","title":"Phase 3: Combat Operations (Control Flow)"},{"location":"intro-to-python/#mission-planning-if-statements","text":"def check_readiness(troops, vehicles): if troops >= 10 and vehicles >= 2: return \"Unit is Combat Ready\" elif troops >= 5: return \"Unit is Patrol Ready\" else: return \"Unit Needs Reinforcement\" # Example Usage unit_status = check_readiness(8, 1) print(unit_status)","title":"Mission Planning (If Statements)"},{"location":"intro-to-python/#patrol-patterns-loops","text":"# Perimeter Check (For Loop) sectors = [\"North\", \"East\", \"South\", \"West\"] for sector in sectors: print(f\"Sector {sector} is secure\") # Watch Rotation (While Loop) watch_hours = 4 current_hour = 0 while current_hour < watch_hours: print(f\"Hour {current_hour + 1} of watch\") current_hour += 1","title":"Patrol Patterns (Loops)"},{"location":"intro-to-python/#phase-4-equipment-and-logistics-data-structures","text":"","title":"Phase 4: Equipment and Logistics (Data Structures)"},{"location":"intro-to-python/#equipment-roster-lists","text":"# Basic gear list gear = [\"rifle\", \"nods\", \"radio\", \"ruck\"] # Adding gear gear.append(\"ifak\") # Adds to end gear.insert(0, \"weapon\") # Adds at position # Checking gear print(f\"First item: {gear[0]}\") print(f\"Last item: {gear[-1]}\") # Removing gear gear.remove(\"radio\") # Removes specific item last_item = gear.pop() # Removes and returns last item","title":"Equipment Roster (Lists)"},{"location":"intro-to-python/#mission-intel-dictionaries","text":"# Mission details mission = { \"type\": \"Training\", \"location\": \"Virtual FOB\", \"duration\": 14, \"unit\": \"VWC Python Platoon\" } # Accessing intel print(f\"Mission Type: {mission['type']}\") print(f\"Location: {mission.get('location')}\") # Updating intel mission[\"status\"] = \"In Progress\" mission[\"duration\"] = 21","title":"Mission Intel (Dictionaries)"},{"location":"intro-to-python/#phase-5-field-exercise","text":"Here's a practical exercise combining the concepts - a Military Awards Database: def awards_database(): \"\"\" Military Awards Reference System \"\"\" awards = { \"1\": { \"name\": \"Purple Heart\", \"criteria\": \"Wounded in combat\", \"precedence\": \"High\", \"branch\": \"All services\" }, \"2\": { \"name\": \"Combat Action Ribbon\", \"criteria\": \"Engaged in combat\", \"precedence\": \"Medium\", \"branch\": \"Navy/Marines\" } } while True: print(\"\\nVWC Awards Database\") print(\"------------------\") for key, award in awards.items(): print(f\"{key}: {award['name']}\") print(\"3: Exit System\") selection = input(\"\\nEnter award number: \") if selection == \"3\": print(\"Database Secured!\") break elif selection in awards: award = awards[selection] print(f\"\\nName: {award['name']}\") print(f\"Criteria: {award['criteria']}\") print(f\"Precedence: {award['precedence']}\") print(f\"Branch: {award['branch']}\") else: print(\"Invalid selection, try again\") if __name__ == \"__main__\": awards_database()","title":"Phase 5: Field Exercise"},{"location":"intro-to-python/#next-mission-parameters","text":"","title":"Next Mission Parameters"},{"location":"intro-to-python/#coming-up-next","text":"Functions (Battle Drills) Error Handling (Combat Contingencies) File Operations (Mission Logs) Classes (Unit Organization) Modules (Support Elements)","title":"Coming Up Next:"},{"location":"intro-to-python/#core-values-to-remember","text":"Attention to Detail (Clean Code) Adapt and Overcome (Problem Solving) Leave No One Behind (Help Others Learn) Mission First (Working Code) Ready to move to advanced operations? Remember: Stay motivated Keep practicing Debug with discipline Learn from each mission \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Core Values to Remember:"},{"location":"streamlit-fundamentals/","text":"Vets Who Code: Streamlit Fundamentals Building Interactive Web Applications with Python \ud83c\udfaf Lesson Objectives After completing this lesson, you will be able to: Set up a Streamlit development environment Understand core Streamlit components and layouts Create interactive user interfaces Handle user input and state management Build data visualizations Deploy Streamlit applications \ud83d\udee0\ufe0f Setup Instructions Ensure Python 3.10 is installed: python --version # Should show Python 3.10.x Create and activate a virtual environment: python -m venv vwc-streamlit source vwc-streamlit/bin/activate # Windows: vwc-streamlit\\Scripts\\activate Install required packages: pip install streamlit==1.31.0 pandas numpy \ud83d\udcda Lesson 1: Streamlit Basics Create a file named lesson1.py : import streamlit as st # Page configuration st.set_page_config( page_title=\"VWC Streamlit Lesson 1\", page_icon=\"\ud83c\udf96\ufe0f\", layout=\"wide\" ) # Basic text elements st.title(\"Welcome to Streamlit! \ud83d\ude80\") st.header(\"Let's learn the basics\") st.subheader(\"Text elements and markdown\") # Markdown support st.markdown(\"\"\" Here's what we can do with markdown: - **Bold text** - *Italic text* - `Code snippets` - [Links](https://vetswhocode.io) \"\"\") # Interactive elements if st.button(\"Click me!\"): st.write(\"Button was clicked!\") user_input = st.text_input(\"Enter your name\") if user_input: st.write(f\"Hello, {user_input}!\") # Run with: streamlit run lesson1.py \ud83d\udcda Lesson 2: Layouts and Containers Create lesson2.py : import streamlit as st st.title(\"Layout in Streamlit\") # Columns col1, col2 = st.columns(2) with col1: st.header(\"Column 1\") st.write(\"This is the left column\") st.button(\"Left Button\") with col2: st.header(\"Column 2\") st.write(\"This is the right column\") st.button(\"Right Button\") # Sidebar with st.sidebar: st.header(\"Sidebar\") option = st.selectbox( \"Choose an option\", [\"Option 1\", \"Option 2\", \"Option 3\"] ) # Tabs tab1, tab2 = st.tabs([\"Tab 1\", \"Tab 2\"]) with tab1: st.write(\"This is tab 1\") with tab2: st.write(\"This is tab 2\") # Containers with st.container(): st.write(\"This is a container\") st.write(\"It helps organize content\") \ud83d\udcda Lesson 3: State Management Create lesson3.py : import streamlit as st # Initialize session state if \"counter\" not in st.session_state: st.session_state.counter = 0 st.title(\"State Management in Streamlit\") # Display counter st.write(f\"Counter value: {st.session_state.counter}\") # Buttons to modify state if st.button(\"Increment\"): st.session_state.counter += 1 st.experimental_rerun() if st.button(\"Decrement\"): st.session_state.counter -= 1 st.experimental_rerun() # Form example with st.form(\"my_form\"): name = st.text_input(\"Name\") age = st.number_input(\"Age\", min_value=0, max_value=120) submitted = st.form_submit_button(\"Submit\") if submitted: st.write(f\"Name: {name}, Age: {age}\") \ud83d\udcda Lesson 4: Chat Interface Components Create lesson4.py : import streamlit as st from datetime import datetime # Initialize chat history if \"messages\" not in st.session_state: st.session_state.messages = [] st.title(\"Chat Interface Components\") # Chat display for message in st.session_state.messages: with st.container(): st.write(f\"{message['role']}: {message['content']}\") st.caption(f\"Sent at {message['timestamp']}\") # Message input message = st.text_input(\"Type a message\") if st.button(\"Send\") and message: # Add message to history st.session_state.messages.append({ \"role\": \"user\", \"content\": message, \"timestamp\": datetime.now().strftime(\"%I:%M %p\") }) # Simulate response st.session_state.messages.append({ \"role\": \"assistant\", \"content\": f\"You said: {message}\", \"timestamp\": datetime.now().strftime(\"%I:%M %p\") }) st.experimental_rerun() # Clear chat button if st.button(\"Clear Chat\"): st.session_state.messages = [] st.experimental_rerun() \ud83d\udcda Lesson 5: Data Visualization Create lesson5.py : import streamlit as st import pandas as pd import numpy as np st.title(\"Data Visualization in Streamlit\") # Create sample data data = pd.DataFrame({ 'date': pd.date_range('2024-01-01', '2024-01-10'), 'values': np.random.randn(10).cumsum() }) # Line chart st.subheader(\"Line Chart\") st.line_chart(data.set_index('date')) # Bar chart st.subheader(\"Bar Chart\") st.bar_chart(data.set_index('date')) # Metrics col1, col2, col3 = st.columns(3) with col1: st.metric(\"Total\", f\"{data['values'].sum():.2f}\") with col2: st.metric(\"Average\", f\"{data['values'].mean():.2f}\") with col3: st.metric(\"Max\", f\"{data['values'].max():.2f}\") \ud83d\udd04 Practice Exercises Create a todo list application using session state Build a simple calculator with a form Create a data dashboard with multiple visualizations Implement a file uploader with preview Build a multi-page application using st.sidebar \ud83d\ude80 Mini-Projects AI Chat Interface Implement message history Add user input handling Create styled message bubbles Add typing indicators Data Dashboard Load and display data Add interactive filters Create multiple visualizations Implement data download \ud83d\udcdd Best Practices Performance # Cache data loading @st.cache_data def load_data(): return pd.read_csv(\"data.csv\") # Cache resource-intensive computations @st.cache_resource def load_model(): return Model() Error Handling try: result = process_data() except Exception as e: st.error(f\"An error occurred: {str(e)}\") User Experience with st.spinner(\"Processing...\"): # Long running operation process_data() st.success(\"Done!\") \ud83c\udfaf Next Steps Explore Streamlit Cloud deployment Learn about custom components Study authentication and security Practice responsive design Master advanced visualizations \ud83d\udcda Resources Streamlit Documentation Streamlit Gallery VWC GitHub Python 3.10 Documentation \ud83d\udca1 Tips Use st.experimental_rerun() sparingly Keep state management simple Test locally before deployment Use caching for performance Follow Python best practices","title":"Streamlit Fundamentals"},{"location":"streamlit-fundamentals/#vets-who-code-streamlit-fundamentals","text":"","title":"Vets Who Code: Streamlit Fundamentals"},{"location":"streamlit-fundamentals/#building-interactive-web-applications-with-python","text":"","title":"Building Interactive Web Applications with Python"},{"location":"streamlit-fundamentals/#lesson-objectives","text":"After completing this lesson, you will be able to: Set up a Streamlit development environment Understand core Streamlit components and layouts Create interactive user interfaces Handle user input and state management Build data visualizations Deploy Streamlit applications","title":"\ud83c\udfaf Lesson Objectives"},{"location":"streamlit-fundamentals/#setup-instructions","text":"Ensure Python 3.10 is installed: python --version # Should show Python 3.10.x Create and activate a virtual environment: python -m venv vwc-streamlit source vwc-streamlit/bin/activate # Windows: vwc-streamlit\\Scripts\\activate Install required packages: pip install streamlit==1.31.0 pandas numpy","title":"\ud83d\udee0\ufe0f Setup Instructions"},{"location":"streamlit-fundamentals/#lesson-1-streamlit-basics","text":"Create a file named lesson1.py : import streamlit as st # Page configuration st.set_page_config( page_title=\"VWC Streamlit Lesson 1\", page_icon=\"\ud83c\udf96\ufe0f\", layout=\"wide\" ) # Basic text elements st.title(\"Welcome to Streamlit! \ud83d\ude80\") st.header(\"Let's learn the basics\") st.subheader(\"Text elements and markdown\") # Markdown support st.markdown(\"\"\" Here's what we can do with markdown: - **Bold text** - *Italic text* - `Code snippets` - [Links](https://vetswhocode.io) \"\"\") # Interactive elements if st.button(\"Click me!\"): st.write(\"Button was clicked!\") user_input = st.text_input(\"Enter your name\") if user_input: st.write(f\"Hello, {user_input}!\") # Run with: streamlit run lesson1.py","title":"\ud83d\udcda Lesson 1: Streamlit Basics"},{"location":"streamlit-fundamentals/#lesson-2-layouts-and-containers","text":"Create lesson2.py : import streamlit as st st.title(\"Layout in Streamlit\") # Columns col1, col2 = st.columns(2) with col1: st.header(\"Column 1\") st.write(\"This is the left column\") st.button(\"Left Button\") with col2: st.header(\"Column 2\") st.write(\"This is the right column\") st.button(\"Right Button\") # Sidebar with st.sidebar: st.header(\"Sidebar\") option = st.selectbox( \"Choose an option\", [\"Option 1\", \"Option 2\", \"Option 3\"] ) # Tabs tab1, tab2 = st.tabs([\"Tab 1\", \"Tab 2\"]) with tab1: st.write(\"This is tab 1\") with tab2: st.write(\"This is tab 2\") # Containers with st.container(): st.write(\"This is a container\") st.write(\"It helps organize content\")","title":"\ud83d\udcda Lesson 2: Layouts and Containers"},{"location":"streamlit-fundamentals/#lesson-3-state-management","text":"Create lesson3.py : import streamlit as st # Initialize session state if \"counter\" not in st.session_state: st.session_state.counter = 0 st.title(\"State Management in Streamlit\") # Display counter st.write(f\"Counter value: {st.session_state.counter}\") # Buttons to modify state if st.button(\"Increment\"): st.session_state.counter += 1 st.experimental_rerun() if st.button(\"Decrement\"): st.session_state.counter -= 1 st.experimental_rerun() # Form example with st.form(\"my_form\"): name = st.text_input(\"Name\") age = st.number_input(\"Age\", min_value=0, max_value=120) submitted = st.form_submit_button(\"Submit\") if submitted: st.write(f\"Name: {name}, Age: {age}\")","title":"\ud83d\udcda Lesson 3: State Management"},{"location":"streamlit-fundamentals/#lesson-4-chat-interface-components","text":"Create lesson4.py : import streamlit as st from datetime import datetime # Initialize chat history if \"messages\" not in st.session_state: st.session_state.messages = [] st.title(\"Chat Interface Components\") # Chat display for message in st.session_state.messages: with st.container(): st.write(f\"{message['role']}: {message['content']}\") st.caption(f\"Sent at {message['timestamp']}\") # Message input message = st.text_input(\"Type a message\") if st.button(\"Send\") and message: # Add message to history st.session_state.messages.append({ \"role\": \"user\", \"content\": message, \"timestamp\": datetime.now().strftime(\"%I:%M %p\") }) # Simulate response st.session_state.messages.append({ \"role\": \"assistant\", \"content\": f\"You said: {message}\", \"timestamp\": datetime.now().strftime(\"%I:%M %p\") }) st.experimental_rerun() # Clear chat button if st.button(\"Clear Chat\"): st.session_state.messages = [] st.experimental_rerun()","title":"\ud83d\udcda Lesson 4: Chat Interface Components"},{"location":"streamlit-fundamentals/#lesson-5-data-visualization","text":"Create lesson5.py : import streamlit as st import pandas as pd import numpy as np st.title(\"Data Visualization in Streamlit\") # Create sample data data = pd.DataFrame({ 'date': pd.date_range('2024-01-01', '2024-01-10'), 'values': np.random.randn(10).cumsum() }) # Line chart st.subheader(\"Line Chart\") st.line_chart(data.set_index('date')) # Bar chart st.subheader(\"Bar Chart\") st.bar_chart(data.set_index('date')) # Metrics col1, col2, col3 = st.columns(3) with col1: st.metric(\"Total\", f\"{data['values'].sum():.2f}\") with col2: st.metric(\"Average\", f\"{data['values'].mean():.2f}\") with col3: st.metric(\"Max\", f\"{data['values'].max():.2f}\")","title":"\ud83d\udcda Lesson 5: Data Visualization"},{"location":"streamlit-fundamentals/#practice-exercises","text":"Create a todo list application using session state Build a simple calculator with a form Create a data dashboard with multiple visualizations Implement a file uploader with preview Build a multi-page application using st.sidebar","title":"\ud83d\udd04 Practice Exercises"},{"location":"streamlit-fundamentals/#mini-projects","text":"AI Chat Interface Implement message history Add user input handling Create styled message bubbles Add typing indicators Data Dashboard Load and display data Add interactive filters Create multiple visualizations Implement data download","title":"\ud83d\ude80 Mini-Projects"},{"location":"streamlit-fundamentals/#best-practices","text":"Performance # Cache data loading @st.cache_data def load_data(): return pd.read_csv(\"data.csv\") # Cache resource-intensive computations @st.cache_resource def load_model(): return Model() Error Handling try: result = process_data() except Exception as e: st.error(f\"An error occurred: {str(e)}\") User Experience with st.spinner(\"Processing...\"): # Long running operation process_data() st.success(\"Done!\")","title":"\ud83d\udcdd Best Practices"},{"location":"streamlit-fundamentals/#next-steps","text":"Explore Streamlit Cloud deployment Learn about custom components Study authentication and security Practice responsive design Master advanced visualizations","title":"\ud83c\udfaf Next Steps"},{"location":"streamlit-fundamentals/#resources","text":"Streamlit Documentation Streamlit Gallery VWC GitHub Python 3.10 Documentation","title":"\ud83d\udcda Resources"},{"location":"streamlit-fundamentals/#tips","text":"Use st.experimental_rerun() sparingly Keep state management simple Test locally before deployment Use caching for performance Follow Python best practices","title":"\ud83d\udca1 Tips"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Vets Who Code Engineering Standard Operating Procedures (SOPs) \ud83c\uddfa\ud83c\uddf8 A veteran transitioning into software engineering through Vets Who Code... Has responsibilities to their team \u2013 mentor, coach, and support others Knows their SOPs . Follows their SOPs. Improves their SOPs when needed. Shares knowledge and best practices with others. Leads by example. Models professional excellence both interpersonally and technically. Understands how their work contributes to the larger mission and ensures team success. These are our Standard Operating Procedures for Software Engineering as a Vets Who Code team member. All contributions are welcome! Please feel free to submit a pull request to get involved. Why Have SOPs To increase overall efficiency for the entire Vets Who Code community To reduce common obstacles in the transition to becoming software engineers To learn from shared experiences and help each other grow professionally To establish a consistent, high-quality approach to software development tasks Core Values: Our Guiding Principles \ud83c\uddfa\ud83c\uddf8 Our military service taught us the importance of Integrity, Service, and Excellence. These values continue to guide us as software engineers: Integrity First : The foundation of all we do Write clear, maintainable code that reflects its intended purpose Own your mistakes and grow from them Practice transparency in your work and give credit to others Service Before Self : Your work impacts the entire team Build solutions that benefit the whole organization Support the developer community through open-source contributions Put user needs at the forefront of development decisions Excellence In All We Do : Commit to continuous improvement Regularly evaluate and enhance your code Stay current with industry best practices Share knowledge to elevate the entire team General Guidance: Professional Development Guidelines \ud83c\uddfa\ud83c\uddf8 Maintain high standards through thorough code reviews and testing Prioritize quality over speed - careful planning prevents future issues Focus on one task at a time using GitHub Projects for organization Practice clear communication: Use wikis for documentation Engage in discussions for knowledge sharing Create detailed issues for tracking work Start with simple, effective solutions before adding complexity Respect project scope - create new issues for additional features Deploy updates incrementally and document changes clearly Keep your team informed through regular updates on issues and pull requests Report problems thoroughly with clear reproduction steps and context Take ownership of the codebase - everyone is responsible for quality Leverage automation through GitHub Actions to ensure consistency Use standardized templates to streamline processes Remember: Your military experience has given you valuable skills in leadership, attention to detail, and teamwork. These qualities, combined with technical expertise, make you a valuable asset to any development team. Together, we'll continue serving through technology. Let's show what Vets Who Code can do! \ud83c\uddfa\ud83c\uddf8","title":"Home"},{"location":"#vets-who-code-engineering-standard-operating-procedures-sops","text":"A veteran transitioning into software engineering through Vets Who Code... Has responsibilities to their team \u2013 mentor, coach, and support others Knows their SOPs . Follows their SOPs. Improves their SOPs when needed. Shares knowledge and best practices with others. Leads by example. Models professional excellence both interpersonally and technically. Understands how their work contributes to the larger mission and ensures team success. These are our Standard Operating Procedures for Software Engineering as a Vets Who Code team member. All contributions are welcome! Please feel free to submit a pull request to get involved.","title":"Vets Who Code Engineering Standard Operating Procedures (SOPs) \ud83c\uddfa\ud83c\uddf8"},{"location":"#why-have-sops","text":"To increase overall efficiency for the entire Vets Who Code community To reduce common obstacles in the transition to becoming software engineers To learn from shared experiences and help each other grow professionally To establish a consistent, high-quality approach to software development tasks","title":"Why Have SOPs"},{"location":"#core-values-our-guiding-principles","text":"Our military service taught us the importance of Integrity, Service, and Excellence. These values continue to guide us as software engineers: Integrity First : The foundation of all we do Write clear, maintainable code that reflects its intended purpose Own your mistakes and grow from them Practice transparency in your work and give credit to others Service Before Self : Your work impacts the entire team Build solutions that benefit the whole organization Support the developer community through open-source contributions Put user needs at the forefront of development decisions Excellence In All We Do : Commit to continuous improvement Regularly evaluate and enhance your code Stay current with industry best practices Share knowledge to elevate the entire team","title":"Core Values: Our Guiding Principles \ud83c\uddfa\ud83c\uddf8"},{"location":"#general-guidance-professional-development-guidelines","text":"Maintain high standards through thorough code reviews and testing Prioritize quality over speed - careful planning prevents future issues Focus on one task at a time using GitHub Projects for organization Practice clear communication: Use wikis for documentation Engage in discussions for knowledge sharing Create detailed issues for tracking work Start with simple, effective solutions before adding complexity Respect project scope - create new issues for additional features Deploy updates incrementally and document changes clearly Keep your team informed through regular updates on issues and pull requests Report problems thoroughly with clear reproduction steps and context Take ownership of the codebase - everyone is responsible for quality Leverage automation through GitHub Actions to ensure consistency Use standardized templates to streamline processes Remember: Your military experience has given you valuable skills in leadership, attention to detail, and teamwork. These qualities, combined with technical expertise, make you a valuable asset to any development team. Together, we'll continue serving through technology. Let's show what Vets Who Code can do! \ud83c\uddfa\ud83c\uddf8","title":"General Guidance: Professional Development Guidelines \ud83c\uddfa\ud83c\uddf8"},{"location":"advanced-command-line-features/","text":"Advanced Command Line Features SOP 1. Introduction This Standard Operating Procedure (SOP) outlines advanced command line features and techniques that enhance productivity and efficiency for software engineers, writers, instructors, and other tech professionals. These advanced features include shell scripting basics, environmental variables, aliases and shortcuts, command history manipulation, job control, and task scheduling. 2. Shell Scripting Basics Shell scripting allows for automation of complex tasks and repetitive operations. 2.1 Creating a Shell Script Create a new file with a .sh extension. Add the shebang line at the top: #!/bin/bash Make the script executable: chmod +x script.sh 2.2 Syntax Variables variable_name=value my_var=\"Hello, World\" Conditional Statements if [ \"$variable_one\" -gt \"$variable_two\" ]; then echo \"Variable one is greater\" elif [ \"$variable_one\" -eq \"$variable_two\" ]; then echo \"Variables are equal\" else echo \"Variable two is greater\" fi Loops For Loop: for i in {1..10}; do echo $i done While Loop: count=0 while [ $count -lt 10 ]; do echo $count ((count++)) done 2.3 Structure Shebang #!/bin/bash Functions my_function() { echo \"Hello from my_function!\" } # Call the function my_function 2.4 Best Practices Use consistent indentation (2 or 4 spaces). Comment your code for clarity. Handle errors and check return codes. 2.5 Debugging Basic debugging: bash -x script.sh Advanced debugging: set -e # Exit on first error set -u # Treat unset variables as errors set +e # Continue even if there is an error 3. Environmental Variables Environmental variables store system-wide or user-specific configuration information. 3.1 Setting Variables # Temporary (session only) VARIABLE_NAME=value # Permanent (add to ~/.bashrc or ~/.bash_profile) echo 'export PERMANENT_VAR=\"I'm here to stay!\"' >> ~/.bashrc source ~/.bashrc 3.2 Retrieving Variables echo $VARIABLE_NAME env # List all environment variables 3.3 Exporting Variables export VARIABLE_NAME # Or in one line export VARIABLE_NAME=value 3.4 Unsetting Variables unset VARIABLE_NAME 4. Aliases and Shortcuts Aliases allow you to create custom shortcuts for frequently used commands. 4.1 Creating Aliases # Temporary (session only) alias myalias='my long command here' # Permanent (add to ~/.bashrc or ~/.zshrc) echo \"alias persist='I will survive reboots!'\" >> ~/.bashrc source ~/.bashrc 4.2 Common Aliases alias ll='ls -l' alias la='ls -A' alias ..='cd ..' 4.3 Functions For more complex operations, use functions: myfunc() { echo \"Doing complex stuff!\" } 5. Command History Command history allows you to recall and reuse previously executed commands. 5.1 Navigating History Use Up and Down arrow keys to navigate through history. Ctrl+r : Search backward through history. 5.2 Repeating Commands !! # Repeat the last command !n # Repeat the nth command in history !-n # Repeat the nth last command 5.3 Modifying History history -c # Clear current session's history history -d n # Delete the nth command from history history -a # Manually save session's history 6. Job Control Job control allows management of multiple processes within a single terminal session. 6.1 Background and Foreground Jobs command & # Start a job in the background Ctrl+Z # Pause the current foreground job fg %n # Bring job n to the foreground bg %n # Continue job n in the background 6.2 Listing and Managing Jobs jobs # List all jobs kill %n # Terminate job n 6.3 Signals kill -l # List all available signals kill -SIGSTOP %n # Pause job n kill -SIGCONT %n # Resume job n kill -SIGKILL %n # Forcefully terminate job n 7. Scheduling Tasks The cron utility allows scheduling of recurring tasks. 7.1 Editing the Crontab crontab -e 7.2 Crontab Syntax * * * * * command_to_execute \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2514\u2500\u2500\u2500 day of week (0 - 7) (Sunday = 0 or 7) \u2502 \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500 month (1 - 12) \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 day of month (1 - 31) \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 hour (0 - 23) \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 minute (0 - 59) 7.3 Example Cron Job 0 2 * * * /path/to/backup_script.sh This runs the backup script every day at 2:00 AM. 8. Best Practices Use meaningful names for variables, aliases, and functions. Comment your scripts and complex commands for better readability. Be cautious when modifying system-wide environmental variables. Regularly review and clean up your command history and cron jobs. Use job control judiciously to manage system resources effectively. Test scripts and scheduled tasks thoroughly before implementation. Keep your shell configuration files (e.g., .bashrc, .zshrc) organized and well-commented. Use error handling in your scripts to make them more robust. When working with environmental variables, consider using lowercase for local variables and uppercase for exported variables to maintain clarity. Utilize shell script debugging tools like set -x for troubleshooting. 9. Summary Mastering these advanced command line features significantly enhances your ability to work efficiently in a Unix-like environment. From automating tasks with shell scripts to managing complex job workflows, these tools provide powerful capabilities for system administration, software development, and general productivity. Environmental variables offer a flexible way to configure your system and applications, while shell scripting allows you to automate complex tasks and create powerful utilities. Aliases and shortcuts streamline your workflow, and command history manipulation helps you work more efficiently. Job control gives you fine-grained management of processes, and task scheduling with cron allows for automation of recurring tasks. Regular practice and exploration of these features will continue to improve your command line proficiency. Remember to always consider security implications when working with sensitive data in scripts or environmental variables, and to document your work for future reference and collaboration.","title":"Advanced Command Line Features"},{"location":"advanced-command-line-features/#advanced-command-line-features-sop","text":"","title":"Advanced Command Line Features SOP"},{"location":"advanced-command-line-features/#1-introduction","text":"This Standard Operating Procedure (SOP) outlines advanced command line features and techniques that enhance productivity and efficiency for software engineers, writers, instructors, and other tech professionals. These advanced features include shell scripting basics, environmental variables, aliases and shortcuts, command history manipulation, job control, and task scheduling.","title":"1. Introduction"},{"location":"advanced-command-line-features/#2-shell-scripting-basics","text":"Shell scripting allows for automation of complex tasks and repetitive operations.","title":"2. Shell Scripting Basics"},{"location":"advanced-command-line-features/#21-creating-a-shell-script","text":"Create a new file with a .sh extension. Add the shebang line at the top: #!/bin/bash Make the script executable: chmod +x script.sh","title":"2.1 Creating a Shell Script"},{"location":"advanced-command-line-features/#22-syntax","text":"","title":"2.2 Syntax"},{"location":"advanced-command-line-features/#variables","text":"variable_name=value my_var=\"Hello, World\"","title":"Variables"},{"location":"advanced-command-line-features/#conditional-statements","text":"if [ \"$variable_one\" -gt \"$variable_two\" ]; then echo \"Variable one is greater\" elif [ \"$variable_one\" -eq \"$variable_two\" ]; then echo \"Variables are equal\" else echo \"Variable two is greater\" fi","title":"Conditional Statements"},{"location":"advanced-command-line-features/#loops","text":"For Loop: for i in {1..10}; do echo $i done While Loop: count=0 while [ $count -lt 10 ]; do echo $count ((count++)) done","title":"Loops"},{"location":"advanced-command-line-features/#23-structure","text":"","title":"2.3 Structure"},{"location":"advanced-command-line-features/#shebang","text":"#!/bin/bash","title":"Shebang"},{"location":"advanced-command-line-features/#functions","text":"my_function() { echo \"Hello from my_function!\" } # Call the function my_function","title":"Functions"},{"location":"advanced-command-line-features/#24-best-practices","text":"Use consistent indentation (2 or 4 spaces). Comment your code for clarity. Handle errors and check return codes.","title":"2.4 Best Practices"},{"location":"advanced-command-line-features/#25-debugging","text":"Basic debugging: bash -x script.sh Advanced debugging: set -e # Exit on first error set -u # Treat unset variables as errors set +e # Continue even if there is an error","title":"2.5 Debugging"},{"location":"advanced-command-line-features/#3-environmental-variables","text":"Environmental variables store system-wide or user-specific configuration information.","title":"3. Environmental Variables"},{"location":"advanced-command-line-features/#31-setting-variables","text":"# Temporary (session only) VARIABLE_NAME=value # Permanent (add to ~/.bashrc or ~/.bash_profile) echo 'export PERMANENT_VAR=\"I'm here to stay!\"' >> ~/.bashrc source ~/.bashrc","title":"3.1 Setting Variables"},{"location":"advanced-command-line-features/#32-retrieving-variables","text":"echo $VARIABLE_NAME env # List all environment variables","title":"3.2 Retrieving Variables"},{"location":"advanced-command-line-features/#33-exporting-variables","text":"export VARIABLE_NAME # Or in one line export VARIABLE_NAME=value","title":"3.3 Exporting Variables"},{"location":"advanced-command-line-features/#34-unsetting-variables","text":"unset VARIABLE_NAME","title":"3.4 Unsetting Variables"},{"location":"advanced-command-line-features/#4-aliases-and-shortcuts","text":"Aliases allow you to create custom shortcuts for frequently used commands.","title":"4. Aliases and Shortcuts"},{"location":"advanced-command-line-features/#41-creating-aliases","text":"# Temporary (session only) alias myalias='my long command here' # Permanent (add to ~/.bashrc or ~/.zshrc) echo \"alias persist='I will survive reboots!'\" >> ~/.bashrc source ~/.bashrc","title":"4.1 Creating Aliases"},{"location":"advanced-command-line-features/#42-common-aliases","text":"alias ll='ls -l' alias la='ls -A' alias ..='cd ..'","title":"4.2 Common Aliases"},{"location":"advanced-command-line-features/#43-functions","text":"For more complex operations, use functions: myfunc() { echo \"Doing complex stuff!\" }","title":"4.3 Functions"},{"location":"advanced-command-line-features/#5-command-history","text":"Command history allows you to recall and reuse previously executed commands.","title":"5. Command History"},{"location":"advanced-command-line-features/#51-navigating-history","text":"Use Up and Down arrow keys to navigate through history. Ctrl+r : Search backward through history.","title":"5.1 Navigating History"},{"location":"advanced-command-line-features/#52-repeating-commands","text":"!! # Repeat the last command !n # Repeat the nth command in history !-n # Repeat the nth last command","title":"5.2 Repeating Commands"},{"location":"advanced-command-line-features/#53-modifying-history","text":"history -c # Clear current session's history history -d n # Delete the nth command from history history -a # Manually save session's history","title":"5.3 Modifying History"},{"location":"advanced-command-line-features/#6-job-control","text":"Job control allows management of multiple processes within a single terminal session.","title":"6. Job Control"},{"location":"advanced-command-line-features/#61-background-and-foreground-jobs","text":"command & # Start a job in the background Ctrl+Z # Pause the current foreground job fg %n # Bring job n to the foreground bg %n # Continue job n in the background","title":"6.1 Background and Foreground Jobs"},{"location":"advanced-command-line-features/#62-listing-and-managing-jobs","text":"jobs # List all jobs kill %n # Terminate job n","title":"6.2 Listing and Managing Jobs"},{"location":"advanced-command-line-features/#63-signals","text":"kill -l # List all available signals kill -SIGSTOP %n # Pause job n kill -SIGCONT %n # Resume job n kill -SIGKILL %n # Forcefully terminate job n","title":"6.3 Signals"},{"location":"advanced-command-line-features/#7-scheduling-tasks","text":"The cron utility allows scheduling of recurring tasks.","title":"7. Scheduling Tasks"},{"location":"advanced-command-line-features/#71-editing-the-crontab","text":"crontab -e","title":"7.1 Editing the Crontab"},{"location":"advanced-command-line-features/#72-crontab-syntax","text":"* * * * * command_to_execute \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2514\u2500\u2500\u2500 day of week (0 - 7) (Sunday = 0 or 7) \u2502 \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500 month (1 - 12) \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 day of month (1 - 31) \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 hour (0 - 23) \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 minute (0 - 59)","title":"7.2 Crontab Syntax"},{"location":"advanced-command-line-features/#73-example-cron-job","text":"0 2 * * * /path/to/backup_script.sh This runs the backup script every day at 2:00 AM.","title":"7.3 Example Cron Job"},{"location":"advanced-command-line-features/#8-best-practices","text":"Use meaningful names for variables, aliases, and functions. Comment your scripts and complex commands for better readability. Be cautious when modifying system-wide environmental variables. Regularly review and clean up your command history and cron jobs. Use job control judiciously to manage system resources effectively. Test scripts and scheduled tasks thoroughly before implementation. Keep your shell configuration files (e.g., .bashrc, .zshrc) organized and well-commented. Use error handling in your scripts to make them more robust. When working with environmental variables, consider using lowercase for local variables and uppercase for exported variables to maintain clarity. Utilize shell script debugging tools like set -x for troubleshooting.","title":"8. Best Practices"},{"location":"advanced-command-line-features/#9-summary","text":"Mastering these advanced command line features significantly enhances your ability to work efficiently in a Unix-like environment. From automating tasks with shell scripts to managing complex job workflows, these tools provide powerful capabilities for system administration, software development, and general productivity. Environmental variables offer a flexible way to configure your system and applications, while shell scripting allows you to automate complex tasks and create powerful utilities. Aliases and shortcuts streamline your workflow, and command history manipulation helps you work more efficiently. Job control gives you fine-grained management of processes, and task scheduling with cron allows for automation of recurring tasks. Regular practice and exploration of these features will continue to improve your command line proficiency. Remember to always consider security implications when working with sensitive data in scripts or environmental variables, and to document your work for future reference and collaboration.","title":"9. Summary"},{"location":"advanced-fast-api/","text":"VWC FastAPI Advanced Operations Guide \ud83c\udf96\ufe0f Part 1: Advanced FastAPI Features WebSocket Implementation (Real-time Communications) from fastapi import FastAPI, WebSocket, WebSocketDisconnect from typing import List app = FastAPI() class CommandCenter: def __init__(self): self.active_connections: List[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) command_center = CommandCenter() @app.websocket(\"/ws/mission-updates/{unit_id}\") async def mission_updates(websocket: WebSocket, unit_id: str): await command_center.connect(websocket) try: while True: data = await websocket.receive_text() await command_center.broadcast(f\"Unit {unit_id}: {data}\") except WebSocketDisconnect: command_center.disconnect(websocket) await command_center.broadcast(f\"Unit {unit_id} disconnected\") File Operations with Azure Storage from fastapi import UploadFile, File from azure.storage.blob import BlobServiceClient import os class AzureStorageManager: def __init__(self): conn_str = os.getenv(\"AZURE_STORAGE_CONNECTION_STRING\") self.blob_service_client = BlobServiceClient.from_connection_string(conn_str) self.container_name = \"mission-docs\" async def upload_file(self, file: UploadFile): blob_client = self.blob_service_client.get_blob_client( container=self.container_name, blob=file.filename ) data = await file.read() await blob_client.upload_blob(data) return blob_client.url async def download_file(self, filename: str): blob_client = self.blob_service_client.get_blob_client( container=self.container_name, blob=filename ) return await blob_client.download_blob() storage_manager = AzureStorageManager() @app.post(\"/upload-document/\") async def upload_document(file: UploadFile = File(...)): try: url = await storage_manager.upload_file(file) return {\"status\": \"success\", \"url\": url} except Exception as e: return {\"status\": \"error\", \"message\": str(e)} Rate Limiting from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address limiter = Limiter(key_func=get_remote_address) app = FastAPI() app.state.limiter = limiter app.add_exception_handler(429, _rate_limit_exceeded_handler) @app.get(\"/secure-intel\") @limiter.limit(\"5/minute\") async def get_secure_intel(request: Request): return {\"intel\": \"Classified information\"} Caching with Azure Redis Cache from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache import aioredis @app.on_event(\"startup\") async def startup(): redis = aioredis.from_url( os.getenv(\"AZURE_REDIS_CONNECTION_STRING\"), encoding=\"utf8\" ) FastAPICache.init(RedisBackend(redis), prefix=\"vwc-cache\") @app.get(\"/mission-brief/{mission_id}\") @cache(expire=60) async def get_mission_brief(mission_id: str): return {\"mission_id\": mission_id, \"brief\": \"Mission details...\"} Part 2: Azure Deployment Operations Azure App Service Configuration # config.py from pydantic_settings import BaseSettings class Settings(BaseSettings): APP_NAME: str = \"VWC API\" AZURE_STORAGE_CONNECTION_STRING: str AZURE_REDIS_CONNECTION_STRING: str AZURE_SQL_CONNECTION_STRING: str APPLICATIONINSIGHTS_CONNECTION_STRING: str class Config: env_file = \".env\" Container Registry Setup # Dockerfile FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY ./app ./app CMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"] Azure DevOps Pipeline # azure-pipelines.yml trigger: - main variables: azureSubscription: 'VWC-Azure' containerRegistry: 'vwccontainers.azurecr.io' imageRepository: 'vwc-api' dockerfilePath: 'Dockerfile' tag: '$(Build.BuildId)' stages: - stage: Build jobs: - job: BuildAndTest pool: vmImage: 'ubuntu-latest' steps: - task: Docker@2 inputs: containerRegistry: '$(containerRegistry)' repository: '$(imageRepository)' command: 'buildAndPush' Dockerfile: '$(dockerfilePath)' tags: '$(tag)' - stage: Deploy jobs: - job: Deploy pool: vmImage: 'ubuntu-latest' steps: - task: AzureWebAppContainer@1 inputs: azureSubscription: '$(azureSubscription)' appName: 'vwc-api' containers: '$(containerRegistry)/$(imageRepository):$(tag)' Azure Monitor Integration # monitoring.py from opencensus.ext.azure.trace_exporter import AzureExporter from opencensus.trace.tracer import Tracer from opencensus.trace.samplers import ProbabilitySampler import logging class AzureMonitoring: def __init__(self, connection_string: str): self.tracer = Tracer( exporter=AzureExporter(connection_string=connection_string), sampler=ProbabilitySampler(1.0) ) def track_request(self, name: str): with self.tracer.span(name=name) as span: span.add_attribute(\"service\", \"vwc-api\") return span # Usage in main.py monitoring = AzureMonitoring(os.getenv(\"APPLICATIONINSIGHTS_CONNECTION_STRING\")) @app.middleware(\"http\") async def monitoring_middleware(request: Request, call_next): with monitoring.track_request(f\"{request.method} {request.url.path}\"): response = await call_next(request) return response Azure Key Vault Integration # security.py from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential class SecureConfig: def __init__(self): credential = DefaultAzureCredential() vault_url = os.getenv(\"AZURE_KEYVAULT_URL\") self.client = SecretClient(vault_url=vault_url, credential=credential) def get_secret(self, name: str) -> str: return self.client.get_secret(name).value # Usage secure_config = SecureConfig() db_password = secure_config.get_secret(\"database-password\") Production Configuration # production.py from azure.identity import DefaultAzureCredential from fastapi.middleware.cors import CORSMiddleware def configure_production(app: FastAPI): # CORS configuration app.add_middleware( CORSMiddleware, allow_origins=[\"https://*.azurewebsites.net\"], allow_credentials=True, allow_methods=[\"*\"], allow_headers=[\"*\"], ) # Azure authentication credential = DefaultAzureCredential() # Health check endpoint @app.get(\"/health\") async def health_check(): return {\"status\": \"healthy\", \"environment\": \"azure-production\"} Field Exercise: Complete Azure-Deployed API Here's a complete example combining these concepts: # main.py from fastapi import FastAPI, Depends, HTTPException, Request from azure.identity import DefaultAzureCredential from azure.storage.blob import BlobServiceClient from azure.keyvault.secrets import SecretClient import logging class AzureAPI: def __init__(self): self.app = FastAPI(title=\"VWC Mission Control\") self.credential = DefaultAzureCredential() self.setup_azure_services() self.setup_routes() self.setup_monitoring() def setup_azure_services(self): # Key Vault setup vault_url = os.getenv(\"AZURE_KEYVAULT_URL\") self.key_vault = SecretClient( vault_url=vault_url, credential=self.credential ) # Blob storage setup storage_connection = self.key_vault.get_secret(\"storage-connection\").value self.blob_service = BlobServiceClient.from_connection_string(storage_connection) def setup_monitoring(self): connection_string = self.key_vault.get_secret(\"appinsights-connection\").value self.monitoring = AzureMonitoring(connection_string) def setup_routes(self): @self.app.get(\"/\") async def root(): return {\"status\": \"operational\", \"service\": \"VWC API\"} @self.app.post(\"/documents/\") async def upload_document(file: UploadFile = File(...)): try: container_client = self.blob_service.get_container_client(\"documents\") blob_client = container_client.get_blob_client(file.filename) data = await file.read() await blob_client.upload_blob(data) return {\"status\": \"success\", \"url\": blob_client.url} except Exception as e: logging.error(f\"Upload failed: {str(e)}\") raise HTTPException(status_code=500, detail=str(e)) # Initialize application azure_api = AzureAPI() app = azure_api.app Deployment Commands # Login to Azure az login # Create resource group az group create --name vwc-resources --location eastus # Create App Service plan az appservice plan create \\ --name vwc-service-plan \\ --resource-group vwc-resources \\ --sku B1 \\ --is-linux # Create Web App az webapp create \\ --resource-group vwc-resources \\ --plan vwc-service-plan \\ --name vwc-fastapi-app \\ --runtime \"PYTHON:3.9\" # Configure deployment az webapp config appsettings set \\ --resource-group vwc-resources \\ --name vwc-fastapi-app \\ --settings \\ WEBSITES_PORT=8000 \\ SCM_DO_BUILD_DURING_DEPLOYMENT=true Next Mission Parameters Advanced Azure Features: Azure Functions integration Azure API Management Azure Front Door setup Virtual Networks configuration Security Hardening: Managed Identities Role-Based Access Control Network Security Groups Web Application Firewall Remember: Monitor your resources Set up proper logging Configure automated backups Use managed identities Follow least privilege principle \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Advanced FastAPI"},{"location":"advanced-fast-api/#vwc-fastapi-advanced-operations-guide","text":"","title":"VWC FastAPI Advanced Operations Guide \ud83c\udf96\ufe0f"},{"location":"advanced-fast-api/#part-1-advanced-fastapi-features","text":"","title":"Part 1: Advanced FastAPI Features"},{"location":"advanced-fast-api/#websocket-implementation-real-time-communications","text":"from fastapi import FastAPI, WebSocket, WebSocketDisconnect from typing import List app = FastAPI() class CommandCenter: def __init__(self): self.active_connections: List[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) command_center = CommandCenter() @app.websocket(\"/ws/mission-updates/{unit_id}\") async def mission_updates(websocket: WebSocket, unit_id: str): await command_center.connect(websocket) try: while True: data = await websocket.receive_text() await command_center.broadcast(f\"Unit {unit_id}: {data}\") except WebSocketDisconnect: command_center.disconnect(websocket) await command_center.broadcast(f\"Unit {unit_id} disconnected\")","title":"WebSocket Implementation (Real-time Communications)"},{"location":"advanced-fast-api/#file-operations-with-azure-storage","text":"from fastapi import UploadFile, File from azure.storage.blob import BlobServiceClient import os class AzureStorageManager: def __init__(self): conn_str = os.getenv(\"AZURE_STORAGE_CONNECTION_STRING\") self.blob_service_client = BlobServiceClient.from_connection_string(conn_str) self.container_name = \"mission-docs\" async def upload_file(self, file: UploadFile): blob_client = self.blob_service_client.get_blob_client( container=self.container_name, blob=file.filename ) data = await file.read() await blob_client.upload_blob(data) return blob_client.url async def download_file(self, filename: str): blob_client = self.blob_service_client.get_blob_client( container=self.container_name, blob=filename ) return await blob_client.download_blob() storage_manager = AzureStorageManager() @app.post(\"/upload-document/\") async def upload_document(file: UploadFile = File(...)): try: url = await storage_manager.upload_file(file) return {\"status\": \"success\", \"url\": url} except Exception as e: return {\"status\": \"error\", \"message\": str(e)}","title":"File Operations with Azure Storage"},{"location":"advanced-fast-api/#rate-limiting","text":"from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address limiter = Limiter(key_func=get_remote_address) app = FastAPI() app.state.limiter = limiter app.add_exception_handler(429, _rate_limit_exceeded_handler) @app.get(\"/secure-intel\") @limiter.limit(\"5/minute\") async def get_secure_intel(request: Request): return {\"intel\": \"Classified information\"}","title":"Rate Limiting"},{"location":"advanced-fast-api/#caching-with-azure-redis-cache","text":"from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache import aioredis @app.on_event(\"startup\") async def startup(): redis = aioredis.from_url( os.getenv(\"AZURE_REDIS_CONNECTION_STRING\"), encoding=\"utf8\" ) FastAPICache.init(RedisBackend(redis), prefix=\"vwc-cache\") @app.get(\"/mission-brief/{mission_id}\") @cache(expire=60) async def get_mission_brief(mission_id: str): return {\"mission_id\": mission_id, \"brief\": \"Mission details...\"}","title":"Caching with Azure Redis Cache"},{"location":"advanced-fast-api/#part-2-azure-deployment-operations","text":"","title":"Part 2: Azure Deployment Operations"},{"location":"advanced-fast-api/#azure-app-service-configuration","text":"# config.py from pydantic_settings import BaseSettings class Settings(BaseSettings): APP_NAME: str = \"VWC API\" AZURE_STORAGE_CONNECTION_STRING: str AZURE_REDIS_CONNECTION_STRING: str AZURE_SQL_CONNECTION_STRING: str APPLICATIONINSIGHTS_CONNECTION_STRING: str class Config: env_file = \".env\"","title":"Azure App Service Configuration"},{"location":"advanced-fast-api/#container-registry-setup","text":"# Dockerfile FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY ./app ./app CMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]","title":"Container Registry Setup"},{"location":"advanced-fast-api/#azure-devops-pipeline","text":"# azure-pipelines.yml trigger: - main variables: azureSubscription: 'VWC-Azure' containerRegistry: 'vwccontainers.azurecr.io' imageRepository: 'vwc-api' dockerfilePath: 'Dockerfile' tag: '$(Build.BuildId)' stages: - stage: Build jobs: - job: BuildAndTest pool: vmImage: 'ubuntu-latest' steps: - task: Docker@2 inputs: containerRegistry: '$(containerRegistry)' repository: '$(imageRepository)' command: 'buildAndPush' Dockerfile: '$(dockerfilePath)' tags: '$(tag)' - stage: Deploy jobs: - job: Deploy pool: vmImage: 'ubuntu-latest' steps: - task: AzureWebAppContainer@1 inputs: azureSubscription: '$(azureSubscription)' appName: 'vwc-api' containers: '$(containerRegistry)/$(imageRepository):$(tag)'","title":"Azure DevOps Pipeline"},{"location":"advanced-fast-api/#azure-monitor-integration","text":"# monitoring.py from opencensus.ext.azure.trace_exporter import AzureExporter from opencensus.trace.tracer import Tracer from opencensus.trace.samplers import ProbabilitySampler import logging class AzureMonitoring: def __init__(self, connection_string: str): self.tracer = Tracer( exporter=AzureExporter(connection_string=connection_string), sampler=ProbabilitySampler(1.0) ) def track_request(self, name: str): with self.tracer.span(name=name) as span: span.add_attribute(\"service\", \"vwc-api\") return span # Usage in main.py monitoring = AzureMonitoring(os.getenv(\"APPLICATIONINSIGHTS_CONNECTION_STRING\")) @app.middleware(\"http\") async def monitoring_middleware(request: Request, call_next): with monitoring.track_request(f\"{request.method} {request.url.path}\"): response = await call_next(request) return response","title":"Azure Monitor Integration"},{"location":"advanced-fast-api/#azure-key-vault-integration","text":"# security.py from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential class SecureConfig: def __init__(self): credential = DefaultAzureCredential() vault_url = os.getenv(\"AZURE_KEYVAULT_URL\") self.client = SecretClient(vault_url=vault_url, credential=credential) def get_secret(self, name: str) -> str: return self.client.get_secret(name).value # Usage secure_config = SecureConfig() db_password = secure_config.get_secret(\"database-password\")","title":"Azure Key Vault Integration"},{"location":"advanced-fast-api/#production-configuration","text":"# production.py from azure.identity import DefaultAzureCredential from fastapi.middleware.cors import CORSMiddleware def configure_production(app: FastAPI): # CORS configuration app.add_middleware( CORSMiddleware, allow_origins=[\"https://*.azurewebsites.net\"], allow_credentials=True, allow_methods=[\"*\"], allow_headers=[\"*\"], ) # Azure authentication credential = DefaultAzureCredential() # Health check endpoint @app.get(\"/health\") async def health_check(): return {\"status\": \"healthy\", \"environment\": \"azure-production\"}","title":"Production Configuration"},{"location":"advanced-fast-api/#field-exercise-complete-azure-deployed-api","text":"Here's a complete example combining these concepts: # main.py from fastapi import FastAPI, Depends, HTTPException, Request from azure.identity import DefaultAzureCredential from azure.storage.blob import BlobServiceClient from azure.keyvault.secrets import SecretClient import logging class AzureAPI: def __init__(self): self.app = FastAPI(title=\"VWC Mission Control\") self.credential = DefaultAzureCredential() self.setup_azure_services() self.setup_routes() self.setup_monitoring() def setup_azure_services(self): # Key Vault setup vault_url = os.getenv(\"AZURE_KEYVAULT_URL\") self.key_vault = SecretClient( vault_url=vault_url, credential=self.credential ) # Blob storage setup storage_connection = self.key_vault.get_secret(\"storage-connection\").value self.blob_service = BlobServiceClient.from_connection_string(storage_connection) def setup_monitoring(self): connection_string = self.key_vault.get_secret(\"appinsights-connection\").value self.monitoring = AzureMonitoring(connection_string) def setup_routes(self): @self.app.get(\"/\") async def root(): return {\"status\": \"operational\", \"service\": \"VWC API\"} @self.app.post(\"/documents/\") async def upload_document(file: UploadFile = File(...)): try: container_client = self.blob_service.get_container_client(\"documents\") blob_client = container_client.get_blob_client(file.filename) data = await file.read() await blob_client.upload_blob(data) return {\"status\": \"success\", \"url\": blob_client.url} except Exception as e: logging.error(f\"Upload failed: {str(e)}\") raise HTTPException(status_code=500, detail=str(e)) # Initialize application azure_api = AzureAPI() app = azure_api.app","title":"Field Exercise: Complete Azure-Deployed API"},{"location":"advanced-fast-api/#deployment-commands","text":"# Login to Azure az login # Create resource group az group create --name vwc-resources --location eastus # Create App Service plan az appservice plan create \\ --name vwc-service-plan \\ --resource-group vwc-resources \\ --sku B1 \\ --is-linux # Create Web App az webapp create \\ --resource-group vwc-resources \\ --plan vwc-service-plan \\ --name vwc-fastapi-app \\ --runtime \"PYTHON:3.9\" # Configure deployment az webapp config appsettings set \\ --resource-group vwc-resources \\ --name vwc-fastapi-app \\ --settings \\ WEBSITES_PORT=8000 \\ SCM_DO_BUILD_DURING_DEPLOYMENT=true","title":"Deployment Commands"},{"location":"advanced-fast-api/#next-mission-parameters","text":"Advanced Azure Features: Azure Functions integration Azure API Management Azure Front Door setup Virtual Networks configuration Security Hardening: Managed Identities Role-Based Access Control Network Security Groups Web Application Firewall Remember: Monitor your resources Set up proper logging Configure automated backups Use managed identities Follow least privilege principle \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Next Mission Parameters"},{"location":"advanced-python-operations/","text":"Vets Who Code - Advanced Python Operations \ud83c\udf96\ufe0f Phase 1: Battle Drills (Functions) Basic Function Structure def call_sign_generator(last_name, unit): \"\"\" Docstring: Like a mission brief, explains the function's purpose Args: last_name: String of operator's last name unit: String of unit designation Returns: String: Generated call sign \"\"\" return f\"VIPER_{last_name.upper()}_{unit}\" # Using the function operator_call_sign = call_sign_generator(\"Smith\", \"PYTHON\") print(operator_call_sign) # Output: VIPER_SMITH_PYTHON Function Parameters (Loading Combat Gear) # Default Parameters def create_fire_team(team_leader, size=4, designation=\"Alpha\"): return f\"Team {designation}: {size} operators led by {team_leader}\" # Multiple Parameters def mission_brief(date, time, location, *objectives, **support_units): \"\"\" *objectives: Variable args (tuple) for multiple mission objectives **support_units: Keyword args (dict) for support elements \"\"\" brief = f\"Mission Date: {date} at {time}\\nLocation: {location}\\n\" brief += \"\\nObjectives:\\n\" for obj in objectives: brief += f\"- {obj}\\n\" brief += \"\\nSupport Units:\\n\" for unit, role in support_units.items(): brief += f\"- {unit}: {role}\\n\" return brief # Using complex function brief = mission_brief(\"2024-11-10\", \"0600\", \"Grid Alpha-7\", \"Secure Perimeter\", \"Establish Comms\", \"Deploy Assets\", air_support=\"Close Air Support\", medical=\"Combat Medic Team\") Phase 2: Combat Contingencies (Error Handling) Basic Error Handling def check_ammunition(mag_count): try: if not isinstance(mag_count, int): raise TypeError(\"Magazine count must be a number\") if mag_count < 0: raise ValueError(\"Magazine count cannot be negative\") if mag_count < 3: print(\"Low ammunition warning!\") return f\"Ammunition check: {mag_count} magazines\" except TypeError as e: return f\"Error in ammunition count: {e}\" except ValueError as e: return f\"Invalid ammunition count: {e}\" except Exception as e: return f\"Unknown error in ammunition check: {e}\" finally: print(\"Ammunition check complete\") Custom Exceptions class MissionCriticalError(Exception): \"\"\"Custom exception for mission-critical failures\"\"\" pass def verify_comms(signal_strength): try: if signal_strength < 50: raise MissionCriticalError(\"Communications signal too weak\") return \"Communications operational\" except MissionCriticalError as e: return f\"MISSION CRITICAL: {e}\" Phase 3: Mission Logs (File Operations) Basic File Operations # Writing mission logs def write_mission_log(mission_id, details): try: with open(f\"mission_{mission_id}.log\", \"w\") as log_file: log_file.write(f\"Mission ID: {mission_id}\\n\") log_file.write(f\"Timestamp: {datetime.now()}\\n\") log_file.write(\"Details:\\n\") log_file.write(details) except IOError as e: print(f\"Error writing mission log: {e}\") # Reading mission logs def read_mission_log(mission_id): try: with open(f\"mission_{mission_id}.log\", \"r\") as log_file: return log_file.read() except FileNotFoundError: return \"Mission log not found\" CSV Operations (Personnel Records) import csv def log_personnel_data(filename, personnel_list): with open(filename, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['id', 'name', 'rank', 'unit']) writer.writeheader() for person in personnel_list: writer.writerow(person) def read_personnel_data(filename): with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile) return list(reader) Phase 4: Unit Organization (Classes) Basic Class Structure class MilitaryUnit: def __init__(self, designation, strength, location): self.designation = designation self.strength = strength self.location = location self.status = \"Active\" def deploy(self, new_location): self.location = new_location return f\"{self.designation} deployed to {new_location}\" def report_status(self): return f\"Unit: {self.designation}\\nStrength: {self.strength}\\nLocation: {self.location}\\nStatus: {self.status}\" # Using the class alpha_team = MilitaryUnit(\"Alpha\", 12, \"Base\") print(alpha_team.deploy(\"Grid Bravo-7\")) print(alpha_team.report_status()) Inheritance (Specialized Units) class SpecialOperationsUnit(MilitaryUnit): def __init__(self, designation, strength, location, specialty): super().__init__(designation, strength, location) self.specialty = specialty self.deployed = False def conduct_operation(self, operation_type): if operation_type == self.specialty: return f\"Conducting {operation_type} operation with {self.strength} operators\" return f\"Operation type mismatch with unit specialty\" # Using inherited class delta_force = SpecialOperationsUnit(\"Delta\", 8, \"Classified\", \"Direct Action\") print(delta_force.conduct_operation(\"Direct Action\")) Phase 5: Support Elements (Modules) Creating Custom Modules # mission_utils.py def generate_grid_reference(x, y): return f\"GRID_{x}{y}\" def calculate_bearing(start, end): # Complex bearing calculation logic here pass # Using modules from mission_utils import generate_grid_reference grid = generate_grid_reference(5, 8) Module Organization # Project structure military_ops/ __init__.py personnel/ __init__.py roster.py qualifications.py operations/ __init__.py mission_planning.py logistics.py utils/ __init__.py grid_calc.py comms.py Field Exercise: Combined Arms Operation Let's combine all these concepts in a practical exercise - a Mission Planning System: class MissionPlanningSystem: def __init__(self): self.missions = {} self.units = {} self.logs = [] def plan_mission(self, mission_id, objective): try: if mission_id in self.missions: raise ValueError(\"Mission ID already exists\") mission = { \"id\": mission_id, \"objective\": objective, \"status\": \"Planning\", \"units\": [] } self.missions[mission_id] = mission self._log_event(f\"Mission {mission_id} created\") return \"Mission created successfully\" except Exception as e: self._log_event(f\"Error creating mission: {e}\") raise def assign_unit(self, mission_id, unit): if mission_id in self.missions: self.missions[mission_id][\"units\"].append(unit) self._log_event(f\"Unit {unit.designation} assigned to mission {mission_id}\") def _log_event(self, event): timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") log_entry = f\"[{timestamp}] {event}\" self.logs.append(log_entry) # Write to file with open(\"mission_logs.txt\", \"a\") as f: f.write(log_entry + \"\\n\") # Using the system mps = MissionPlanningSystem() alpha = MilitaryUnit(\"Alpha\", 10, \"Base\") try: mps.plan_mission(\"OPS001\", \"Secure Objective Bravo\") mps.assign_unit(\"OPS001\", alpha) except Exception as e: print(f\"Mission planning failed: {e}\") Movement Orders (Next Steps) Practice implementing these concepts with your own scenarios Build a complete project combining multiple concepts Learn about: Testing (Mission Rehearsal) Debugging (Equipment Checks) Advanced OOP concepts (Unit Organization) API integration (Joint Operations) Remember: Code with discipline Document thoroughly Test rigorously Stay mission-focused \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode Need clarification on any operations or ready for specific exercises?","title":"Advanced Python Operations"},{"location":"advanced-python-operations/#vets-who-code-advanced-python-operations","text":"","title":"Vets Who Code - Advanced Python Operations \ud83c\udf96\ufe0f"},{"location":"advanced-python-operations/#phase-1-battle-drills-functions","text":"","title":"Phase 1: Battle Drills (Functions)"},{"location":"advanced-python-operations/#basic-function-structure","text":"def call_sign_generator(last_name, unit): \"\"\" Docstring: Like a mission brief, explains the function's purpose Args: last_name: String of operator's last name unit: String of unit designation Returns: String: Generated call sign \"\"\" return f\"VIPER_{last_name.upper()}_{unit}\" # Using the function operator_call_sign = call_sign_generator(\"Smith\", \"PYTHON\") print(operator_call_sign) # Output: VIPER_SMITH_PYTHON","title":"Basic Function Structure"},{"location":"advanced-python-operations/#function-parameters-loading-combat-gear","text":"# Default Parameters def create_fire_team(team_leader, size=4, designation=\"Alpha\"): return f\"Team {designation}: {size} operators led by {team_leader}\" # Multiple Parameters def mission_brief(date, time, location, *objectives, **support_units): \"\"\" *objectives: Variable args (tuple) for multiple mission objectives **support_units: Keyword args (dict) for support elements \"\"\" brief = f\"Mission Date: {date} at {time}\\nLocation: {location}\\n\" brief += \"\\nObjectives:\\n\" for obj in objectives: brief += f\"- {obj}\\n\" brief += \"\\nSupport Units:\\n\" for unit, role in support_units.items(): brief += f\"- {unit}: {role}\\n\" return brief # Using complex function brief = mission_brief(\"2024-11-10\", \"0600\", \"Grid Alpha-7\", \"Secure Perimeter\", \"Establish Comms\", \"Deploy Assets\", air_support=\"Close Air Support\", medical=\"Combat Medic Team\")","title":"Function Parameters (Loading Combat Gear)"},{"location":"advanced-python-operations/#phase-2-combat-contingencies-error-handling","text":"","title":"Phase 2: Combat Contingencies (Error Handling)"},{"location":"advanced-python-operations/#basic-error-handling","text":"def check_ammunition(mag_count): try: if not isinstance(mag_count, int): raise TypeError(\"Magazine count must be a number\") if mag_count < 0: raise ValueError(\"Magazine count cannot be negative\") if mag_count < 3: print(\"Low ammunition warning!\") return f\"Ammunition check: {mag_count} magazines\" except TypeError as e: return f\"Error in ammunition count: {e}\" except ValueError as e: return f\"Invalid ammunition count: {e}\" except Exception as e: return f\"Unknown error in ammunition check: {e}\" finally: print(\"Ammunition check complete\")","title":"Basic Error Handling"},{"location":"advanced-python-operations/#custom-exceptions","text":"class MissionCriticalError(Exception): \"\"\"Custom exception for mission-critical failures\"\"\" pass def verify_comms(signal_strength): try: if signal_strength < 50: raise MissionCriticalError(\"Communications signal too weak\") return \"Communications operational\" except MissionCriticalError as e: return f\"MISSION CRITICAL: {e}\"","title":"Custom Exceptions"},{"location":"advanced-python-operations/#phase-3-mission-logs-file-operations","text":"","title":"Phase 3: Mission Logs (File Operations)"},{"location":"advanced-python-operations/#basic-file-operations","text":"# Writing mission logs def write_mission_log(mission_id, details): try: with open(f\"mission_{mission_id}.log\", \"w\") as log_file: log_file.write(f\"Mission ID: {mission_id}\\n\") log_file.write(f\"Timestamp: {datetime.now()}\\n\") log_file.write(\"Details:\\n\") log_file.write(details) except IOError as e: print(f\"Error writing mission log: {e}\") # Reading mission logs def read_mission_log(mission_id): try: with open(f\"mission_{mission_id}.log\", \"r\") as log_file: return log_file.read() except FileNotFoundError: return \"Mission log not found\"","title":"Basic File Operations"},{"location":"advanced-python-operations/#csv-operations-personnel-records","text":"import csv def log_personnel_data(filename, personnel_list): with open(filename, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['id', 'name', 'rank', 'unit']) writer.writeheader() for person in personnel_list: writer.writerow(person) def read_personnel_data(filename): with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile) return list(reader)","title":"CSV Operations (Personnel Records)"},{"location":"advanced-python-operations/#phase-4-unit-organization-classes","text":"","title":"Phase 4: Unit Organization (Classes)"},{"location":"advanced-python-operations/#basic-class-structure","text":"class MilitaryUnit: def __init__(self, designation, strength, location): self.designation = designation self.strength = strength self.location = location self.status = \"Active\" def deploy(self, new_location): self.location = new_location return f\"{self.designation} deployed to {new_location}\" def report_status(self): return f\"Unit: {self.designation}\\nStrength: {self.strength}\\nLocation: {self.location}\\nStatus: {self.status}\" # Using the class alpha_team = MilitaryUnit(\"Alpha\", 12, \"Base\") print(alpha_team.deploy(\"Grid Bravo-7\")) print(alpha_team.report_status())","title":"Basic Class Structure"},{"location":"advanced-python-operations/#inheritance-specialized-units","text":"class SpecialOperationsUnit(MilitaryUnit): def __init__(self, designation, strength, location, specialty): super().__init__(designation, strength, location) self.specialty = specialty self.deployed = False def conduct_operation(self, operation_type): if operation_type == self.specialty: return f\"Conducting {operation_type} operation with {self.strength} operators\" return f\"Operation type mismatch with unit specialty\" # Using inherited class delta_force = SpecialOperationsUnit(\"Delta\", 8, \"Classified\", \"Direct Action\") print(delta_force.conduct_operation(\"Direct Action\"))","title":"Inheritance (Specialized Units)"},{"location":"advanced-python-operations/#phase-5-support-elements-modules","text":"","title":"Phase 5: Support Elements (Modules)"},{"location":"advanced-python-operations/#creating-custom-modules","text":"# mission_utils.py def generate_grid_reference(x, y): return f\"GRID_{x}{y}\" def calculate_bearing(start, end): # Complex bearing calculation logic here pass # Using modules from mission_utils import generate_grid_reference grid = generate_grid_reference(5, 8)","title":"Creating Custom Modules"},{"location":"advanced-python-operations/#module-organization","text":"# Project structure military_ops/ __init__.py personnel/ __init__.py roster.py qualifications.py operations/ __init__.py mission_planning.py logistics.py utils/ __init__.py grid_calc.py comms.py","title":"Module Organization"},{"location":"advanced-python-operations/#field-exercise-combined-arms-operation","text":"Let's combine all these concepts in a practical exercise - a Mission Planning System: class MissionPlanningSystem: def __init__(self): self.missions = {} self.units = {} self.logs = [] def plan_mission(self, mission_id, objective): try: if mission_id in self.missions: raise ValueError(\"Mission ID already exists\") mission = { \"id\": mission_id, \"objective\": objective, \"status\": \"Planning\", \"units\": [] } self.missions[mission_id] = mission self._log_event(f\"Mission {mission_id} created\") return \"Mission created successfully\" except Exception as e: self._log_event(f\"Error creating mission: {e}\") raise def assign_unit(self, mission_id, unit): if mission_id in self.missions: self.missions[mission_id][\"units\"].append(unit) self._log_event(f\"Unit {unit.designation} assigned to mission {mission_id}\") def _log_event(self, event): timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") log_entry = f\"[{timestamp}] {event}\" self.logs.append(log_entry) # Write to file with open(\"mission_logs.txt\", \"a\") as f: f.write(log_entry + \"\\n\") # Using the system mps = MissionPlanningSystem() alpha = MilitaryUnit(\"Alpha\", 10, \"Base\") try: mps.plan_mission(\"OPS001\", \"Secure Objective Bravo\") mps.assign_unit(\"OPS001\", alpha) except Exception as e: print(f\"Mission planning failed: {e}\")","title":"Field Exercise: Combined Arms Operation"},{"location":"advanced-python-operations/#movement-orders-next-steps","text":"Practice implementing these concepts with your own scenarios Build a complete project combining multiple concepts Learn about: Testing (Mission Rehearsal) Debugging (Equipment Checks) Advanced OOP concepts (Unit Organization) API integration (Joint Operations) Remember: Code with discipline Document thoroughly Test rigorously Stay mission-focused \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode Need clarification on any operations or ready for specific exercises?","title":"Movement Orders (Next Steps)"},{"location":"advanced-streamlit/","text":"Vets Who Code: Advanced Streamlit Development Taking Your Streamlit Apps to the Next Level \ud83c\udfaf Advanced Learning Objectives After completing this lesson, you will be able to: Deploy applications to Streamlit Cloud Create custom Streamlit components Implement secure authentication Build responsive layouts Create advanced data visualizations \ud83d\udcda Lesson 1: Streamlit Cloud Deployment Local Setup for Deployment Create requirements.txt : streamlit==1.31.0 pandas==2.0.3 numpy==1.24.3 python-dotenv==1.0.0 Create .gitignore : venv/ .env __pycache__/ *.pyc .DS_Store Create config.toml in .streamlit folder: [theme] primaryColor = \"#D6372E\" # VWC Red backgroundColor = \"#FFFFFF\" secondaryBackgroundColor = \"#F0F2F6\" textColor = \"#262730\" font = \"sans serif\" [server] maxUploadSize = 200 enableXsrfProtection = true Deployment Steps Push to GitHub: git init git add . git commit -m \"Initial commit\" git remote add origin your-repo-url git push -u origin main Streamlit Cloud Setup: Visit streamlit.io/cloud Connect your GitHub repository Select main file Add secrets in dashboard Deploy \ud83d\udcda Lesson 2: Custom Components Basic Custom Component Create custom_components.py : import streamlit as st import streamlit.components.v1 as components def custom_html_component(): components.html( \"\"\"

    Custom HTML Component

    This is a custom component using HTML and JavaScript.

    \"\"\", height=200 ) def custom_chart_component(): components.html( \"\"\"
    \"\"\", height=400 ) # Usage st.title(\"Custom Components Demo\") custom_html_component() custom_chart_component() \ud83d\udcda Lesson 3: Authentication & Security Basic Authentication Create auth.py : import streamlit as st import hmac import hashlib from datetime import datetime, timedelta class Authenticator: def __init__(self): if 'authenticated' not in st.session_state: st.session_state.authenticated = False st.session_state.auth_time = None def _hash_password(self, password: str) -> str: return hashlib.sha256(password.encode()).hexdigest() def _check_password(self, username: str, password: str) -> bool: # Replace with database lookup in production users = { \"demo\": self._hash_password(\"demo123\") } return username in users and users[username] == self._hash_password(password) def login_form(self): if not st.session_state.authenticated: st.title(\"Login\") with st.form(\"login_form\"): username = st.text_input(\"Username\") password = st.text_input(\"Password\", type=\"password\") submitted = st.form_submit_button(\"Login\") if submitted: if self._check_password(username, password): st.session_state.authenticated = True st.session_state.auth_time = datetime.now() st.experimental_rerun() else: st.error(\"Invalid credentials\") return st.session_state.authenticated # Usage example auth = Authenticator() if auth.login_form(): st.write(\"Welcome to the secure area!\") \ud83d\udcda Lesson 4: Responsive Design Responsive Layout Example Create responsive.py : import streamlit as st def get_device_type(): # Basic device detection using viewport width # Note: This is a simplified approach return st.select_slider( \"Preview as:\", options=[\"Mobile\", \"Tablet\", \"Desktop\"], value=\"Desktop\", key=\"device_type\" ) st.title(\"Responsive Design Demo\") device = get_device_type() # Responsive layout based on device if device == \"Mobile\": # Single column layout st.write(\"Mobile Layout\") st.image(\"https://via.placeholder.com/300x200\") st.write(\"Content below image\") elif device == \"Tablet\": # Two column layout col1, col2 = st.columns([1, 1]) with col1: st.write(\"Tablet Layout - Left\") st.image(\"https://via.placeholder.com/400x300\") with col2: st.write(\"Tablet Layout - Right\") st.write(\"Content next to image\") else: # Desktop # Three column layout col1, col2, col3 = st.columns([1, 2, 1]) with col1: st.write(\"Sidebar content\") with col2: st.write(\"Desktop Layout - Main\") st.image(\"https://via.placeholder.com/800x400\") with col3: st.write(\"Additional content\") # Responsive CSS st.markdown(\"\"\" \"\"\", unsafe_allow_html=True) \ud83d\udcda Lesson 5: Advanced Visualizations Interactive Dashboard Create advanced_viz.py : import streamlit as st import pandas as pd import plotly.express as px import plotly.graph_objects as go from datetime import datetime, timedelta # Generate sample data def generate_data(): dates = pd.date_range( start=datetime.now() - timedelta(days=30), end=datetime.now(), freq='D' ) df = pd.DataFrame({ 'date': dates, 'users': np.random.randint(100, 1000, size=len(dates)), 'revenue': np.random.uniform(1000, 5000, size=len(dates)), 'conversion': np.random.uniform(0.1, 0.3, size=len(dates)) }) return df # Create interactive visualizations def create_dashboard(): st.title(\"Advanced Analytics Dashboard\") # Load data df = generate_data() # Date filter date_range = st.date_input( \"Select Date Range\", value=(df['date'].min(), df['date'].max()), key=\"date_range\" ) # Filter data mask = (df['date'].dt.date >= date_range[0]) & (df['date'].dt.date <= date_range[1]) filtered_df = df[mask] # Metrics row col1, col2, col3 = st.columns(3) with col1: st.metric( \"Total Users\", f\"{filtered_df['users'].sum():,.0f}\", f\"{filtered_df['users'].diff().mean():+.1f}/day\" ) with col2: st.metric( \"Total Revenue\", f\"${filtered_df['revenue'].sum():,.2f}\", f\"{filtered_df['revenue'].pct_change().mean()*100:+.1f}%\" ) with col3: st.metric( \"Avg Conversion\", f\"{filtered_df['conversion'].mean()*100:.1f}%\", f\"{filtered_df['conversion'].diff().mean()*100:+.2f}pp\" ) # Interactive charts tab1, tab2 = st.tabs([\"Time Series\", \"Analysis\"]) with tab1: # Create time series chart fig = go.Figure() fig.add_trace(go.Scatter( x=filtered_df['date'], y=filtered_df['users'], name=\"Users\", line=dict(color=\"#D6372E\") )) fig.add_trace(go.Scatter( x=filtered_df['date'], y=filtered_df['revenue'], name=\"Revenue\", yaxis=\"y2\" )) fig.update_layout( title=\"Users and Revenue Over Time\", yaxis=dict(title=\"Users\"), yaxis2=dict(title=\"Revenue\", overlaying=\"y\", side=\"right\"), hovermode=\"x unified\" ) st.plotly_chart(fig, use_container_width=True) with tab2: # Create scatter plot fig = px.scatter( filtered_df, x='users', y='revenue', size='conversion', color='conversion', color_continuous_scale=\"Reds\", title=\"User-Revenue Correlation\" ) st.plotly_chart(fig, use_container_width=True) if __name__ == \"__main__\": create_dashboard() \ud83d\udee0\ufe0f Practice Projects Secure Dashboard Application Implement user authentication Create role-based access control Add secure data storage Deploy to Streamlit Cloud Responsive Chat Interface Build custom chat components Create mobile-friendly layout Add real-time updates Implement message persistence Advanced Analytics Dashboard Create interactive visualizations Add custom filtering Implement data export Build responsive layout \ud83d\udcdd Best Practices Security Use environment variables Implement proper authentication Validate user input Use HTTPS Keep dependencies updated Performance Cache expensive operations Optimize data loading Use efficient layouts Minimize re-runs Deployment Use requirements.txt Configure secrets Set up monitoring Enable error tracking Design Follow responsive design principles Maintain consistent branding Use appropriate color schemes Consider accessibility \ud83d\ude80 Next Steps Explore WebSocket integration Study database connectivity Learn about custom caching Master component lifecycle Practice CI/CD deployment","title":"Advanced Streamlit"},{"location":"advanced-streamlit/#vets-who-code-advanced-streamlit-development","text":"","title":"Vets Who Code: Advanced Streamlit Development"},{"location":"advanced-streamlit/#taking-your-streamlit-apps-to-the-next-level","text":"","title":"Taking Your Streamlit Apps to the Next Level"},{"location":"advanced-streamlit/#advanced-learning-objectives","text":"After completing this lesson, you will be able to: Deploy applications to Streamlit Cloud Create custom Streamlit components Implement secure authentication Build responsive layouts Create advanced data visualizations","title":"\ud83c\udfaf Advanced Learning Objectives"},{"location":"advanced-streamlit/#lesson-1-streamlit-cloud-deployment","text":"","title":"\ud83d\udcda Lesson 1: Streamlit Cloud Deployment"},{"location":"advanced-streamlit/#local-setup-for-deployment","text":"Create requirements.txt : streamlit==1.31.0 pandas==2.0.3 numpy==1.24.3 python-dotenv==1.0.0 Create .gitignore : venv/ .env __pycache__/ *.pyc .DS_Store Create config.toml in .streamlit folder: [theme] primaryColor = \"#D6372E\" # VWC Red backgroundColor = \"#FFFFFF\" secondaryBackgroundColor = \"#F0F2F6\" textColor = \"#262730\" font = \"sans serif\" [server] maxUploadSize = 200 enableXsrfProtection = true","title":"Local Setup for Deployment"},{"location":"advanced-streamlit/#deployment-steps","text":"Push to GitHub: git init git add . git commit -m \"Initial commit\" git remote add origin your-repo-url git push -u origin main Streamlit Cloud Setup: Visit streamlit.io/cloud Connect your GitHub repository Select main file Add secrets in dashboard Deploy","title":"Deployment Steps"},{"location":"advanced-streamlit/#lesson-2-custom-components","text":"","title":"\ud83d\udcda Lesson 2: Custom Components"},{"location":"advanced-streamlit/#basic-custom-component","text":"Create custom_components.py : import streamlit as st import streamlit.components.v1 as components def custom_html_component(): components.html( \"\"\"

    Custom HTML Component

    This is a custom component using HTML and JavaScript.

    \"\"\", height=200 ) def custom_chart_component(): components.html( \"\"\"
    \"\"\", height=400 ) # Usage st.title(\"Custom Components Demo\") custom_html_component() custom_chart_component()","title":"Basic Custom Component"},{"location":"advanced-streamlit/#lesson-3-authentication-security","text":"","title":"\ud83d\udcda Lesson 3: Authentication & Security"},{"location":"advanced-streamlit/#basic-authentication","text":"Create auth.py : import streamlit as st import hmac import hashlib from datetime import datetime, timedelta class Authenticator: def __init__(self): if 'authenticated' not in st.session_state: st.session_state.authenticated = False st.session_state.auth_time = None def _hash_password(self, password: str) -> str: return hashlib.sha256(password.encode()).hexdigest() def _check_password(self, username: str, password: str) -> bool: # Replace with database lookup in production users = { \"demo\": self._hash_password(\"demo123\") } return username in users and users[username] == self._hash_password(password) def login_form(self): if not st.session_state.authenticated: st.title(\"Login\") with st.form(\"login_form\"): username = st.text_input(\"Username\") password = st.text_input(\"Password\", type=\"password\") submitted = st.form_submit_button(\"Login\") if submitted: if self._check_password(username, password): st.session_state.authenticated = True st.session_state.auth_time = datetime.now() st.experimental_rerun() else: st.error(\"Invalid credentials\") return st.session_state.authenticated # Usage example auth = Authenticator() if auth.login_form(): st.write(\"Welcome to the secure area!\")","title":"Basic Authentication"},{"location":"advanced-streamlit/#lesson-4-responsive-design","text":"","title":"\ud83d\udcda Lesson 4: Responsive Design"},{"location":"advanced-streamlit/#responsive-layout-example","text":"Create responsive.py : import streamlit as st def get_device_type(): # Basic device detection using viewport width # Note: This is a simplified approach return st.select_slider( \"Preview as:\", options=[\"Mobile\", \"Tablet\", \"Desktop\"], value=\"Desktop\", key=\"device_type\" ) st.title(\"Responsive Design Demo\") device = get_device_type() # Responsive layout based on device if device == \"Mobile\": # Single column layout st.write(\"Mobile Layout\") st.image(\"https://via.placeholder.com/300x200\") st.write(\"Content below image\") elif device == \"Tablet\": # Two column layout col1, col2 = st.columns([1, 1]) with col1: st.write(\"Tablet Layout - Left\") st.image(\"https://via.placeholder.com/400x300\") with col2: st.write(\"Tablet Layout - Right\") st.write(\"Content next to image\") else: # Desktop # Three column layout col1, col2, col3 = st.columns([1, 2, 1]) with col1: st.write(\"Sidebar content\") with col2: st.write(\"Desktop Layout - Main\") st.image(\"https://via.placeholder.com/800x400\") with col3: st.write(\"Additional content\") # Responsive CSS st.markdown(\"\"\" \"\"\", unsafe_allow_html=True)","title":"Responsive Layout Example"},{"location":"advanced-streamlit/#lesson-5-advanced-visualizations","text":"","title":"\ud83d\udcda Lesson 5: Advanced Visualizations"},{"location":"advanced-streamlit/#interactive-dashboard","text":"Create advanced_viz.py : import streamlit as st import pandas as pd import plotly.express as px import plotly.graph_objects as go from datetime import datetime, timedelta # Generate sample data def generate_data(): dates = pd.date_range( start=datetime.now() - timedelta(days=30), end=datetime.now(), freq='D' ) df = pd.DataFrame({ 'date': dates, 'users': np.random.randint(100, 1000, size=len(dates)), 'revenue': np.random.uniform(1000, 5000, size=len(dates)), 'conversion': np.random.uniform(0.1, 0.3, size=len(dates)) }) return df # Create interactive visualizations def create_dashboard(): st.title(\"Advanced Analytics Dashboard\") # Load data df = generate_data() # Date filter date_range = st.date_input( \"Select Date Range\", value=(df['date'].min(), df['date'].max()), key=\"date_range\" ) # Filter data mask = (df['date'].dt.date >= date_range[0]) & (df['date'].dt.date <= date_range[1]) filtered_df = df[mask] # Metrics row col1, col2, col3 = st.columns(3) with col1: st.metric( \"Total Users\", f\"{filtered_df['users'].sum():,.0f}\", f\"{filtered_df['users'].diff().mean():+.1f}/day\" ) with col2: st.metric( \"Total Revenue\", f\"${filtered_df['revenue'].sum():,.2f}\", f\"{filtered_df['revenue'].pct_change().mean()*100:+.1f}%\" ) with col3: st.metric( \"Avg Conversion\", f\"{filtered_df['conversion'].mean()*100:.1f}%\", f\"{filtered_df['conversion'].diff().mean()*100:+.2f}pp\" ) # Interactive charts tab1, tab2 = st.tabs([\"Time Series\", \"Analysis\"]) with tab1: # Create time series chart fig = go.Figure() fig.add_trace(go.Scatter( x=filtered_df['date'], y=filtered_df['users'], name=\"Users\", line=dict(color=\"#D6372E\") )) fig.add_trace(go.Scatter( x=filtered_df['date'], y=filtered_df['revenue'], name=\"Revenue\", yaxis=\"y2\" )) fig.update_layout( title=\"Users and Revenue Over Time\", yaxis=dict(title=\"Users\"), yaxis2=dict(title=\"Revenue\", overlaying=\"y\", side=\"right\"), hovermode=\"x unified\" ) st.plotly_chart(fig, use_container_width=True) with tab2: # Create scatter plot fig = px.scatter( filtered_df, x='users', y='revenue', size='conversion', color='conversion', color_continuous_scale=\"Reds\", title=\"User-Revenue Correlation\" ) st.plotly_chart(fig, use_container_width=True) if __name__ == \"__main__\": create_dashboard()","title":"Interactive Dashboard"},{"location":"advanced-streamlit/#practice-projects","text":"Secure Dashboard Application Implement user authentication Create role-based access control Add secure data storage Deploy to Streamlit Cloud Responsive Chat Interface Build custom chat components Create mobile-friendly layout Add real-time updates Implement message persistence Advanced Analytics Dashboard Create interactive visualizations Add custom filtering Implement data export Build responsive layout","title":"\ud83d\udee0\ufe0f Practice Projects"},{"location":"advanced-streamlit/#best-practices","text":"Security Use environment variables Implement proper authentication Validate user input Use HTTPS Keep dependencies updated Performance Cache expensive operations Optimize data loading Use efficient layouts Minimize re-runs Deployment Use requirements.txt Configure secrets Set up monitoring Enable error tracking Design Follow responsive design principles Maintain consistent branding Use appropriate color schemes Consider accessibility","title":"\ud83d\udcdd Best Practices"},{"location":"advanced-streamlit/#next-steps","text":"Explore WebSocket integration Study database connectivity Learn about custom caching Master component lifecycle Practice CI/CD deployment","title":"\ud83d\ude80 Next Steps"},{"location":"bash/","text":"Comprehensive Bash Guide: From Basics to Advanced Techniques Table of Contents Comprehensive Bash Guide: From Basics to Advanced Techniques Table of Contents 1. Introduction to Bash 2. Basic Syntax Comments Commands 3. Variables Declaring and Using Variables Command Substitution 4. Control Structures If-Else Statement Loops For Loop While Loop 5. Functions 6. Input and Output Reading User Input Redirecting Output 7. Command Line Arguments 8. Basic String Operations 9. Basic Arithmetic 10. Useful Bash Commands 11. Intermediate Bash Techniques Arrays Case Statements Here Documents Subshells 12. Advanced Bash Techniques Regular Expressions Process Substitution Traps Debugging Parameter Expansion 13. Best Practices and Tips 1. Introduction to Bash Bash (Bourne Again SHell) is a command processor that typically runs in a text window where the user types commands that cause actions. Bash can also read and execute commands from a file, called a script. 2. Basic Syntax Comments # This is a comment Commands echo \"Hello, World!\" # Prints \"Hello, World!\" 3. Variables Declaring and Using Variables name=\"John\" echo \"Hello, $name\" # Prints \"Hello, John\" Command Substitution current_date=$(date) echo \"Today is $current_date\" 4. Control Structures If-Else Statement if [ \"$name\" == \"John\" ]; then echo \"Hello, John!\" else echo \"You're not John\" fi Loops For Loop for i in 1 2 3 4 5 do echo \"Number: $i\" done While Loop count=0 while [ $count -lt 5 ] do echo \"Count: $count\" ((count++)) done 5. Functions greet() { echo \"Hello, $1!\" } greet \"World\" # Calls the function, prints \"Hello, World!\" 6. Input and Output Reading User Input echo \"What's your name?\" read user_name echo \"Hello, $user_name!\" Redirecting Output echo \"This goes to a file\" > output.txt echo \"This is appended to the file\" >> output.txt 7. Command Line Arguments # Save as script.sh and run with: ./script.sh arg1 arg2 echo \"First argument: $1\" echo \"Second argument: $2\" echo \"All arguments: $@\" echo \"Number of arguments: $#\" 8. Basic String Operations string=\"Hello, World!\" echo \"${string:0:5}\" # Prints \"Hello\" echo \"${string/World/Bash}\" # Prints \"Hello, Bash!\" echo \"${#string}\" # Prints the length of the string 9. Basic Arithmetic a=5 b=3 echo $((a + b)) # Addition echo $((a - b)) # Subtraction echo $((a * b)) # Multiplication echo $((a / b)) # Division echo $((a % b)) # Modulus 10. Useful Bash Commands source script.sh : Execute commands from a file in the current shell export VAR=\"value\" : Make a variable available to child processes alias ls='ls -la' : Create a shortcut for a command set -e : Exit immediately if a command exits with a non-zero status set -x : Print commands and their arguments as they are executed 11. Intermediate Bash Techniques Arrays fruits=(\"apple\" \"banana\" \"cherry\") echo ${fruits[1]} # Prints \"banana\" echo ${fruits[@]} # Prints all elements echo ${#fruits[@]} # Prints number of elements Case Statements case $fruit in \"apple\") echo \"It's an apple\" ;; \"banana\"|\"plantain\") echo \"It's a banana or plantain\" ;; *) echo \"Unknown fruit\" ;; esac Here Documents cat << EOF > file.txt This is a multi-line text that will be written to file.txt EOF Subshells (cd /tmp && echo \"Current dir: $PWD\") echo \"We're back in $PWD\" 12. Advanced Bash Techniques Regular Expressions if [[ \"example@email.com\" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}$ ]]; then echo \"Valid email\" fi Process Substitution diff <(ls dir1) <(ls dir2) Traps trap 'echo \"Ctrl+C is trapped\"' INT Debugging set -x # Enable debugging set -e # Exit on error set -u # Treat unset variables as an error Parameter Expansion name=\"John\" echo ${name:-\"Default\"} # Use default if name is unset echo ${name:=\"NewDefault\"} # Assign default if name is unset echo ${name:+\"Alternative\"} # Use alternative if name is set echo ${name:?\"Error message\"} # Display error if name is unset 13. Best Practices and Tips Use shellcheck for script validation Use functions for repeated code Use meaningful variable names Quote variables to prevent word splitting Use set -e to exit on error Use set -u to catch unset variables Use [[ ]] for conditionals instead of [ ] Use $(command) instead of backticks for command substitution Use $() for arithmetic instead of expr Use trap to handle signals and perform cleanup Remember, this guide covers a wide range of Bash features, but Bash is incredibly rich and there's always more to learn. Always refer to the Bash manual ( man bash ) for the most up-to-date and detailed information.","title":"Bash Scripting"},{"location":"bash/#comprehensive-bash-guide-from-basics-to-advanced-techniques","text":"","title":"Comprehensive Bash Guide: From Basics to Advanced Techniques"},{"location":"bash/#table-of-contents","text":"Comprehensive Bash Guide: From Basics to Advanced Techniques Table of Contents 1. Introduction to Bash 2. Basic Syntax Comments Commands 3. Variables Declaring and Using Variables Command Substitution 4. Control Structures If-Else Statement Loops For Loop While Loop 5. Functions 6. Input and Output Reading User Input Redirecting Output 7. Command Line Arguments 8. Basic String Operations 9. Basic Arithmetic 10. Useful Bash Commands 11. Intermediate Bash Techniques Arrays Case Statements Here Documents Subshells 12. Advanced Bash Techniques Regular Expressions Process Substitution Traps Debugging Parameter Expansion 13. Best Practices and Tips","title":"Table of Contents"},{"location":"bash/#1-introduction-to-bash","text":"Bash (Bourne Again SHell) is a command processor that typically runs in a text window where the user types commands that cause actions. Bash can also read and execute commands from a file, called a script.","title":"1. Introduction to Bash"},{"location":"bash/#2-basic-syntax","text":"","title":"2. Basic Syntax"},{"location":"bash/#comments","text":"# This is a comment","title":"Comments"},{"location":"bash/#commands","text":"echo \"Hello, World!\" # Prints \"Hello, World!\"","title":"Commands"},{"location":"bash/#3-variables","text":"","title":"3. Variables"},{"location":"bash/#declaring-and-using-variables","text":"name=\"John\" echo \"Hello, $name\" # Prints \"Hello, John\"","title":"Declaring and Using Variables"},{"location":"bash/#command-substitution","text":"current_date=$(date) echo \"Today is $current_date\"","title":"Command Substitution"},{"location":"bash/#4-control-structures","text":"","title":"4. Control Structures"},{"location":"bash/#if-else-statement","text":"if [ \"$name\" == \"John\" ]; then echo \"Hello, John!\" else echo \"You're not John\" fi","title":"If-Else Statement"},{"location":"bash/#loops","text":"","title":"Loops"},{"location":"bash/#for-loop","text":"for i in 1 2 3 4 5 do echo \"Number: $i\" done","title":"For Loop"},{"location":"bash/#while-loop","text":"count=0 while [ $count -lt 5 ] do echo \"Count: $count\" ((count++)) done","title":"While Loop"},{"location":"bash/#5-functions","text":"greet() { echo \"Hello, $1!\" } greet \"World\" # Calls the function, prints \"Hello, World!\"","title":"5. Functions"},{"location":"bash/#6-input-and-output","text":"","title":"6. Input and Output"},{"location":"bash/#reading-user-input","text":"echo \"What's your name?\" read user_name echo \"Hello, $user_name!\"","title":"Reading User Input"},{"location":"bash/#redirecting-output","text":"echo \"This goes to a file\" > output.txt echo \"This is appended to the file\" >> output.txt","title":"Redirecting Output"},{"location":"bash/#7-command-line-arguments","text":"# Save as script.sh and run with: ./script.sh arg1 arg2 echo \"First argument: $1\" echo \"Second argument: $2\" echo \"All arguments: $@\" echo \"Number of arguments: $#\"","title":"7. Command Line Arguments"},{"location":"bash/#8-basic-string-operations","text":"string=\"Hello, World!\" echo \"${string:0:5}\" # Prints \"Hello\" echo \"${string/World/Bash}\" # Prints \"Hello, Bash!\" echo \"${#string}\" # Prints the length of the string","title":"8. Basic String Operations"},{"location":"bash/#9-basic-arithmetic","text":"a=5 b=3 echo $((a + b)) # Addition echo $((a - b)) # Subtraction echo $((a * b)) # Multiplication echo $((a / b)) # Division echo $((a % b)) # Modulus","title":"9. Basic Arithmetic"},{"location":"bash/#10-useful-bash-commands","text":"source script.sh : Execute commands from a file in the current shell export VAR=\"value\" : Make a variable available to child processes alias ls='ls -la' : Create a shortcut for a command set -e : Exit immediately if a command exits with a non-zero status set -x : Print commands and their arguments as they are executed","title":"10. Useful Bash Commands"},{"location":"bash/#11-intermediate-bash-techniques","text":"","title":"11. Intermediate Bash Techniques"},{"location":"bash/#arrays","text":"fruits=(\"apple\" \"banana\" \"cherry\") echo ${fruits[1]} # Prints \"banana\" echo ${fruits[@]} # Prints all elements echo ${#fruits[@]} # Prints number of elements","title":"Arrays"},{"location":"bash/#case-statements","text":"case $fruit in \"apple\") echo \"It's an apple\" ;; \"banana\"|\"plantain\") echo \"It's a banana or plantain\" ;; *) echo \"Unknown fruit\" ;; esac","title":"Case Statements"},{"location":"bash/#here-documents","text":"cat << EOF > file.txt This is a multi-line text that will be written to file.txt EOF","title":"Here Documents"},{"location":"bash/#subshells","text":"(cd /tmp && echo \"Current dir: $PWD\") echo \"We're back in $PWD\"","title":"Subshells"},{"location":"bash/#12-advanced-bash-techniques","text":"","title":"12. Advanced Bash Techniques"},{"location":"bash/#regular-expressions","text":"if [[ \"example@email.com\" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}$ ]]; then echo \"Valid email\" fi","title":"Regular Expressions"},{"location":"bash/#process-substitution","text":"diff <(ls dir1) <(ls dir2)","title":"Process Substitution"},{"location":"bash/#traps","text":"trap 'echo \"Ctrl+C is trapped\"' INT","title":"Traps"},{"location":"bash/#debugging","text":"set -x # Enable debugging set -e # Exit on error set -u # Treat unset variables as an error","title":"Debugging"},{"location":"bash/#parameter-expansion","text":"name=\"John\" echo ${name:-\"Default\"} # Use default if name is unset echo ${name:=\"NewDefault\"} # Assign default if name is unset echo ${name:+\"Alternative\"} # Use alternative if name is set echo ${name:?\"Error message\"} # Display error if name is unset","title":"Parameter Expansion"},{"location":"bash/#13-best-practices-and-tips","text":"Use shellcheck for script validation Use functions for repeated code Use meaningful variable names Quote variables to prevent word splitting Use set -e to exit on error Use set -u to catch unset variables Use [[ ]] for conditionals instead of [ ] Use $(command) instead of backticks for command substitution Use $() for arithmetic instead of expr Use trap to handle signals and perform cleanup Remember, this guide covers a wide range of Bash features, but Bash is incredibly rich and there's always more to learn. Always refer to the Bash manual ( man bash ) for the most up-to-date and detailed information.","title":"13. Best Practices and Tips"},{"location":"basics-of-git/","text":"Setting up Git Introduction This guide will walk you through the steps to properly set up Git on your machine. You will configure Git, generate SSH keys for secure authentication, set up your user identity, and, if necessary, configure a proxy for Git operations. Objectives By the end of this guide, you will be able to: Configure Git using the terminal. Generate SSH keys for secure communication. Set and manage your Git user identity. Configure a proxy for Git operations (if required). Configuring Git Setting Up User Information To personalize your Git environment, configure your username and email. This information will be attached to every commit you make. Use the following commands: git config --global user.name \"Your Name\" git config --global user.email \"your.email@example.com\" Verifying Configuration To check your current settings, use: git config --list !!! task Set your username and email, then verify the configuration using the above command. Generating SSH Keys SSH keys provide secure access to Git services (like GitHub or GitLab), allowing you to interact with remote repositories without entering your password every time. Generating an SSH Key Run the following command in your terminal: ssh-keygen -t rsa -b 4096 Follow the prompts and press Enter to accept the default file location. Adding SSH Key to GitHub/GitLab Once the key is generated: Copy the public key to your clipboard: bash cat ~/.ssh/id_rsa.pub Go to your GitHub or GitLab account settings. Navigate to SSH and GPG keys and paste the key. !!! task Generate an SSH key and add it to your GitHub or GitLab account. Proxy Configuration (Optional) If you're working behind a corporate firewall or restricted network, you may need to configure Git to use a proxy. Setting Up a Proxy To set up a proxy, run: git config --global http.proxy http://proxy.example.com:8080 Replace proxy.example.com:8080 with your actual proxy details. Verifying Proxy Configuration To confirm the proxy is set up correctly: git config --global http.proxy !!! task If needed, configure your proxy settings and verify them using the above commands. Practical Exercise Follow these steps to complete your setup: Configure Git with your username and email. Generate an SSH key and add it to your GitHub or GitLab account. If necessary, set up a proxy. Verify your configuration with: git config --list Additional Resources Official Git Documentation GitHub SSH Key Setup Guide Git Configuration Best Practices With these steps completed, Git is now properly configured on your machine, and you're ready to start working with version control. Happy coding!","title":"Git Basics"},{"location":"basics-of-git/#setting-up-git","text":"","title":"Setting up Git"},{"location":"basics-of-git/#introduction","text":"This guide will walk you through the steps to properly set up Git on your machine. You will configure Git, generate SSH keys for secure authentication, set up your user identity, and, if necessary, configure a proxy for Git operations.","title":"Introduction"},{"location":"basics-of-git/#objectives","text":"By the end of this guide, you will be able to: Configure Git using the terminal. Generate SSH keys for secure communication. Set and manage your Git user identity. Configure a proxy for Git operations (if required).","title":"Objectives"},{"location":"basics-of-git/#configuring-git","text":"","title":"Configuring Git"},{"location":"basics-of-git/#setting-up-user-information","text":"To personalize your Git environment, configure your username and email. This information will be attached to every commit you make. Use the following commands: git config --global user.name \"Your Name\" git config --global user.email \"your.email@example.com\"","title":"Setting Up User Information"},{"location":"basics-of-git/#verifying-configuration","text":"To check your current settings, use: git config --list !!! task Set your username and email, then verify the configuration using the above command.","title":"Verifying Configuration"},{"location":"basics-of-git/#generating-ssh-keys","text":"SSH keys provide secure access to Git services (like GitHub or GitLab), allowing you to interact with remote repositories without entering your password every time.","title":"Generating SSH Keys"},{"location":"basics-of-git/#generating-an-ssh-key","text":"Run the following command in your terminal: ssh-keygen -t rsa -b 4096 Follow the prompts and press Enter to accept the default file location.","title":"Generating an SSH Key"},{"location":"basics-of-git/#adding-ssh-key-to-githubgitlab","text":"Once the key is generated: Copy the public key to your clipboard: bash cat ~/.ssh/id_rsa.pub Go to your GitHub or GitLab account settings. Navigate to SSH and GPG keys and paste the key. !!! task Generate an SSH key and add it to your GitHub or GitLab account.","title":"Adding SSH Key to GitHub/GitLab"},{"location":"basics-of-git/#proxy-configuration-optional","text":"If you're working behind a corporate firewall or restricted network, you may need to configure Git to use a proxy.","title":"Proxy Configuration (Optional)"},{"location":"basics-of-git/#setting-up-a-proxy","text":"To set up a proxy, run: git config --global http.proxy http://proxy.example.com:8080 Replace proxy.example.com:8080 with your actual proxy details.","title":"Setting Up a Proxy"},{"location":"basics-of-git/#verifying-proxy-configuration","text":"To confirm the proxy is set up correctly: git config --global http.proxy !!! task If needed, configure your proxy settings and verify them using the above commands.","title":"Verifying Proxy Configuration"},{"location":"basics-of-git/#practical-exercise","text":"Follow these steps to complete your setup: Configure Git with your username and email. Generate an SSH key and add it to your GitHub or GitLab account. If necessary, set up a proxy. Verify your configuration with: git config --list","title":"Practical Exercise"},{"location":"basics-of-git/#additional-resources","text":"Official Git Documentation GitHub SSH Key Setup Guide Git Configuration Best Practices With these steps completed, Git is now properly configured on your machine, and you're ready to start working with version control. Happy coding!","title":"Additional Resources"},{"location":"code-of-conduct/","text":"Code of Conduct Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards Examples of behavior that contributes to creating a positive environment include: Using welcoming and inclusive language. Being respectful of differing viewpoints and experiences. Gracefully accepting constructive criticism. Focusing on what is best for the community. Showing empathy towards other community members. Examples of unacceptable behavior by participants include: The use of sexualized language or imagery and unwelcome sexual attention or advances. Trolling, insulting/derogatory comments, and personal or political attacks. Public or private harassment. Deliberate intimidation, stalking, or following. Harassing photography or recording. Sustained disruption of talks or other events. Inappropriate physical contact. Advocating for, or encouraging, any of the above behaviors. Publishing others' private information, such as a physical or electronic address, without explicit permission. Other conduct that is inappropriate for a professional or shared professional environment. Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting Jerome Hardaway directly via slack. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Attribution This Code of Conduct is adapted from the Contributor Covenant, version 1.4, code of conduct.","title":"Code Of Conduct"},{"location":"code-of-conduct/#code-of-conduct","text":"","title":"Code of Conduct"},{"location":"code-of-conduct/#our-pledge","text":"In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.","title":"Our Pledge"},{"location":"code-of-conduct/#our-standards","text":"","title":"Our Standards"},{"location":"code-of-conduct/#examples-of-behavior-that-contributes-to-creating-a-positive-environment-include","text":"Using welcoming and inclusive language. Being respectful of differing viewpoints and experiences. Gracefully accepting constructive criticism. Focusing on what is best for the community. Showing empathy towards other community members.","title":"Examples of behavior that contributes to creating a positive environment include:"},{"location":"code-of-conduct/#examples-of-unacceptable-behavior-by-participants-include","text":"The use of sexualized language or imagery and unwelcome sexual attention or advances. Trolling, insulting/derogatory comments, and personal or political attacks. Public or private harassment. Deliberate intimidation, stalking, or following. Harassing photography or recording. Sustained disruption of talks or other events. Inappropriate physical contact. Advocating for, or encouraging, any of the above behaviors. Publishing others' private information, such as a physical or electronic address, without explicit permission. Other conduct that is inappropriate for a professional or shared professional environment.","title":"Examples of unacceptable behavior by participants include:"},{"location":"code-of-conduct/#our-responsibilities","text":"Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.","title":"Our Responsibilities"},{"location":"code-of-conduct/#scope","text":"This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.","title":"Scope"},{"location":"code-of-conduct/#enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting Jerome Hardaway directly via slack. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.","title":"Enforcement"},{"location":"code-of-conduct/#attribution","text":"This Code of Conduct is adapted from the Contributor Covenant, version 1.4, code of conduct.","title":"Attribution"},{"location":"coding-patterns-for-interviews/","text":"VetsWhoCode: Combat-Ready Coding Patterns \ud83c\udf96\ufe0f \"In code as in combat, patterns and preparation determine success.\" - VetsWhoCode Mission Overview These battle-tested coding patterns form the foundation of technical interviews and efficient problem-solving. Like standard operating procedures (SOPs) in combat, these patterns provide proven solutions to common challenges. Table of Contents Mission Briefing Two Pointers Pattern Sliding Window Pattern Fast & Slow Pointers Pattern Binary Search Pattern After Action Review Mission Briefing These patterns are your tactical toolset for coding interviews. Like a well-maintained weapon system, each pattern serves a specific purpose and should be mastered through consistent practice and application. Battle Rhythm Identify the pattern that fits your mission Apply the appropriate tactical solution Test and verify your implementation Optimize for better performance Two Pointers Pattern Tactical Overview Mission Type: Coordinated Movement Operations Military Context: Like coordinating two fire teams during a patrol - each team moves with purpose and coordination to achieve the mission objective. Just as fire teams maintain relative positioning, our pointers maintain their relationship while moving through the array. Battle Plan Initialize two pointers at strategic positions Move pointers based on mission parameters Maintain coordination between pointer movements Achieve objective with minimal traversal Implementation: Equipment Load Distribution def find_equipment_pairs(weights, target_weight): \"\"\" Mission: Find pairs of equipment that add up to target weight. Tactical Application: - Organizing gear for balanced load distribution - Matching battle buddies for equipment carry - Ensuring optimal weight distribution across the unit Operation Parameters: weights (list): List of equipment weights target_weight (int): Target combined weight Mission Outcome: list: Pairs of weights that match target \"\"\" weights.sort() # Organize equipment by weight left = 0 # Alpha team position right = len(weights) - 1 # Bravo team position pairs = [] while left < right: current_weight = weights[left] + weights[right] if current_weight == target_weight: pairs.append((weights[left], weights[right])) left += 1 # Alpha team advances right -= 1 # Bravo team falls back elif current_weight < target_weight: left += 1 # Alpha team moves forward else: right -= 1 # Bravo team adjusts position return pairs # Field Operations Test equipment_weights = [10, 15, 20, 25, 30, 35] target = 45 pairs = find_equipment_pairs(equipment_weights, target) print(f\"SITREP: Equipment pairs matching {target}lbs: {pairs}\") Mission Applications Finding pairs in sorted arrays (Two Sum) Container optimization (Water Container) Removing duplicates from sorted arrays Combat Tips Always sort when dealing with pair finding Consider edge cases like empty arrays Watch for pointer bounds [Additional sections follow same enhanced format...] After Action Review Key Tactical Points Each pattern represents a battle-tested approach to solving specific types of problems Practice these patterns until they become muscle memory Remember: In both coding and combat, preparation and pattern recognition are key to success Field Notes Document your approaches Learn from failed attempts Build your pattern recognition skills Training Resources VetsWhoCode Pattern Drills Technical Interview Prep Guide Combat Coding Exercises Standard Operating Procedures Always identify the pattern before coding Test with multiple scenarios Consider edge cases Optimize after achieving basic functionality \"Code with Honor, Debug with Discipline\" - VetsWhoCode \"Mission success through tactical coding excellence\"","title":"Coding Interview Patterns"},{"location":"coding-patterns-for-interviews/#vetswhocode-combat-ready-coding-patterns","text":"\"In code as in combat, patterns and preparation determine success.\" - VetsWhoCode","title":"VetsWhoCode: Combat-Ready Coding Patterns \ud83c\udf96\ufe0f"},{"location":"coding-patterns-for-interviews/#mission-overview","text":"These battle-tested coding patterns form the foundation of technical interviews and efficient problem-solving. Like standard operating procedures (SOPs) in combat, these patterns provide proven solutions to common challenges.","title":"Mission Overview"},{"location":"coding-patterns-for-interviews/#table-of-contents","text":"Mission Briefing Two Pointers Pattern Sliding Window Pattern Fast & Slow Pointers Pattern Binary Search Pattern After Action Review","title":"Table of Contents"},{"location":"coding-patterns-for-interviews/#mission-briefing","text":"These patterns are your tactical toolset for coding interviews. Like a well-maintained weapon system, each pattern serves a specific purpose and should be mastered through consistent practice and application.","title":"Mission Briefing"},{"location":"coding-patterns-for-interviews/#battle-rhythm","text":"Identify the pattern that fits your mission Apply the appropriate tactical solution Test and verify your implementation Optimize for better performance","title":"Battle Rhythm"},{"location":"coding-patterns-for-interviews/#two-pointers-pattern","text":"","title":"Two Pointers Pattern"},{"location":"coding-patterns-for-interviews/#tactical-overview","text":"Mission Type: Coordinated Movement Operations Military Context: Like coordinating two fire teams during a patrol - each team moves with purpose and coordination to achieve the mission objective. Just as fire teams maintain relative positioning, our pointers maintain their relationship while moving through the array.","title":"Tactical Overview"},{"location":"coding-patterns-for-interviews/#battle-plan","text":"Initialize two pointers at strategic positions Move pointers based on mission parameters Maintain coordination between pointer movements Achieve objective with minimal traversal","title":"Battle Plan"},{"location":"coding-patterns-for-interviews/#implementation-equipment-load-distribution","text":"def find_equipment_pairs(weights, target_weight): \"\"\" Mission: Find pairs of equipment that add up to target weight. Tactical Application: - Organizing gear for balanced load distribution - Matching battle buddies for equipment carry - Ensuring optimal weight distribution across the unit Operation Parameters: weights (list): List of equipment weights target_weight (int): Target combined weight Mission Outcome: list: Pairs of weights that match target \"\"\" weights.sort() # Organize equipment by weight left = 0 # Alpha team position right = len(weights) - 1 # Bravo team position pairs = [] while left < right: current_weight = weights[left] + weights[right] if current_weight == target_weight: pairs.append((weights[left], weights[right])) left += 1 # Alpha team advances right -= 1 # Bravo team falls back elif current_weight < target_weight: left += 1 # Alpha team moves forward else: right -= 1 # Bravo team adjusts position return pairs # Field Operations Test equipment_weights = [10, 15, 20, 25, 30, 35] target = 45 pairs = find_equipment_pairs(equipment_weights, target) print(f\"SITREP: Equipment pairs matching {target}lbs: {pairs}\")","title":"Implementation: Equipment Load Distribution"},{"location":"coding-patterns-for-interviews/#mission-applications","text":"Finding pairs in sorted arrays (Two Sum) Container optimization (Water Container) Removing duplicates from sorted arrays","title":"Mission Applications"},{"location":"coding-patterns-for-interviews/#combat-tips","text":"Always sort when dealing with pair finding Consider edge cases like empty arrays Watch for pointer bounds [Additional sections follow same enhanced format...]","title":"Combat Tips"},{"location":"coding-patterns-for-interviews/#after-action-review","text":"","title":"After Action Review"},{"location":"coding-patterns-for-interviews/#key-tactical-points","text":"Each pattern represents a battle-tested approach to solving specific types of problems Practice these patterns until they become muscle memory Remember: In both coding and combat, preparation and pattern recognition are key to success","title":"Key Tactical Points"},{"location":"coding-patterns-for-interviews/#field-notes","text":"Document your approaches Learn from failed attempts Build your pattern recognition skills","title":"Field Notes"},{"location":"coding-patterns-for-interviews/#training-resources","text":"VetsWhoCode Pattern Drills Technical Interview Prep Guide Combat Coding Exercises","title":"Training Resources"},{"location":"coding-patterns-for-interviews/#standard-operating-procedures","text":"Always identify the pattern before coding Test with multiple scenarios Consider edge cases Optimize after achieving basic functionality \"Code with Honor, Debug with Discipline\" - VetsWhoCode \"Mission success through tactical coding excellence\"","title":"Standard Operating Procedures"},{"location":"command-line-basics/","text":"Command Line Basics SOP 1. Introduction This Standard Operating Procedure (SOP) outlines the fundamental commands and techniques for effective command line usage. Mastering these basics is crucial for efficient system navigation, file management, and maintaining operational security in a digital environment. 2. Navigating Directories 2.1 Essential Navigation Commands 2.1.1 pwd (Print Working Directory) Confirms your current location in the file system. pwd 2.1.2 cd (Change Directory) Primary command for moving between directories. - Move to home directory: cd or cd ~ - Move to previous directory: cd - - Move up one level: cd .. - Move to specific directory: cd /path/to/directory 2.1.3 ls (List) Provides reconnaissance on directory contents. - Basic listing: ls - Detailed listing: ls -l - Show hidden files: ls -a - Detailed listing with hidden files: ls -la - Sort by size: ls -S 2.1.4 tree Offers a hierarchical view of the directory structure. - Limited depth view: tree -L 2 - Directory-only view: tree -d 2.2 Advanced Navigation Techniques Use tab completion to auto-complete file and directory names. Utilize the up and down arrow keys to navigate command history. Create aliases for frequently used commands to enhance efficiency. 3. File Operations 3.1 Basic File Management 3.1.1 cp (Copy) Copies files or directories. cp source_file target_file cp -R source_directory target_directory 3.1.2 mv (Move) Moves or renames files and directories. mv old_filename new_filename mv file_to_move target_directory/ 3.1.3 rm (Remove) Deletes files or directories. rm filename rm -r directory_name rm -i filename # Interactive mode, asks for confirmation 3.1.4 touch Creates new empty files or updates file timestamps. touch new_file 3.1.5 mkdir (Make Directory) Creates new directories. mkdir new_directory mkdir -p parent_directory/new_directory 3.2 Advanced File Operations 3.2.1 find Searches for files and directories based on various criteria. find /path/to/search -name \"filename\" find ~ -name \"*.txt\" # Find all .txt files in home directory 3.2.2 locate Quickly searches for files using a pre-built database. locate filename sudo updatedb # Update the database 4. Working with Wildcards Wildcards enhance precision and efficiency in file operations. 4.1 Asterisk (*) Matches zero or more characters. ls *.jpg # Lists all JPEG files 4.2 Question Mark (?) Matches exactly one character. ls report_?.txt # Matches report_1.txt, report_2.txt, but not report_10.txt 4.3 Square Brackets ([]) Matches any single character within the brackets. ls [a-c]*.txt # Lists files starting with a, b, or c and ending with .txt 4.4 Curly Braces ({}) Specifies multiple discrete patterns. ls {*.txt,*.pdf} # Lists all text and PDF files 5. Managing Permissions Proper permission management is crucial for system security. 5.1 chmod (Change Mode) Adjusts file and directory permissions. chmod u+x file.txt # Adds execute permission for the owner chmod 755 script.sh # Sets rwxr-xr-x permissions 5.2 chown (Change Owner) Transfers file or directory ownership. chown user:group file.txt 5.3 chgrp (Change Group) Modifies the group ownership of files or directories. chgrp team project/ 5.4 umask Sets default creation permissions for new files and directories. umask 022 # Sets default permissions to 644 for files and 755 for directories 6. Disk and Directory Usage 6.1 df (Disk Free) Displays disk space usage. df -h # Human-readable format 6.2 du (Disk Usage) Estimates space used by directories and files. du -sh /path/to/directory 7. Summary Mastering these command line basics provides a solid foundation for efficient system management and navigation. Regular practice and application of these commands will enhance your operational capabilities in a digital environment. Remember, the command line is your primary interface for precise control and management of your system resources.","title":"Command Line Basics"},{"location":"command-line-basics/#command-line-basics-sop","text":"","title":"Command Line Basics SOP"},{"location":"command-line-basics/#1-introduction","text":"This Standard Operating Procedure (SOP) outlines the fundamental commands and techniques for effective command line usage. Mastering these basics is crucial for efficient system navigation, file management, and maintaining operational security in a digital environment.","title":"1. Introduction"},{"location":"command-line-basics/#2-navigating-directories","text":"","title":"2. Navigating Directories"},{"location":"command-line-basics/#21-essential-navigation-commands","text":"","title":"2.1 Essential Navigation Commands"},{"location":"command-line-basics/#211-pwd-print-working-directory","text":"Confirms your current location in the file system. pwd","title":"2.1.1 pwd (Print Working Directory)"},{"location":"command-line-basics/#212-cd-change-directory","text":"Primary command for moving between directories. - Move to home directory: cd or cd ~ - Move to previous directory: cd - - Move up one level: cd .. - Move to specific directory: cd /path/to/directory","title":"2.1.2 cd (Change Directory)"},{"location":"command-line-basics/#213-ls-list","text":"Provides reconnaissance on directory contents. - Basic listing: ls - Detailed listing: ls -l - Show hidden files: ls -a - Detailed listing with hidden files: ls -la - Sort by size: ls -S","title":"2.1.3 ls (List)"},{"location":"command-line-basics/#214-tree","text":"Offers a hierarchical view of the directory structure. - Limited depth view: tree -L 2 - Directory-only view: tree -d","title":"2.1.4 tree"},{"location":"command-line-basics/#22-advanced-navigation-techniques","text":"Use tab completion to auto-complete file and directory names. Utilize the up and down arrow keys to navigate command history. Create aliases for frequently used commands to enhance efficiency.","title":"2.2 Advanced Navigation Techniques"},{"location":"command-line-basics/#3-file-operations","text":"","title":"3. File Operations"},{"location":"command-line-basics/#31-basic-file-management","text":"","title":"3.1 Basic File Management"},{"location":"command-line-basics/#311-cp-copy","text":"Copies files or directories. cp source_file target_file cp -R source_directory target_directory","title":"3.1.1 cp (Copy)"},{"location":"command-line-basics/#312-mv-move","text":"Moves or renames files and directories. mv old_filename new_filename mv file_to_move target_directory/","title":"3.1.2 mv (Move)"},{"location":"command-line-basics/#313-rm-remove","text":"Deletes files or directories. rm filename rm -r directory_name rm -i filename # Interactive mode, asks for confirmation","title":"3.1.3 rm (Remove)"},{"location":"command-line-basics/#314-touch","text":"Creates new empty files or updates file timestamps. touch new_file","title":"3.1.4 touch"},{"location":"command-line-basics/#315-mkdir-make-directory","text":"Creates new directories. mkdir new_directory mkdir -p parent_directory/new_directory","title":"3.1.5 mkdir (Make Directory)"},{"location":"command-line-basics/#32-advanced-file-operations","text":"","title":"3.2 Advanced File Operations"},{"location":"command-line-basics/#321-find","text":"Searches for files and directories based on various criteria. find /path/to/search -name \"filename\" find ~ -name \"*.txt\" # Find all .txt files in home directory","title":"3.2.1 find"},{"location":"command-line-basics/#322-locate","text":"Quickly searches for files using a pre-built database. locate filename sudo updatedb # Update the database","title":"3.2.2 locate"},{"location":"command-line-basics/#4-working-with-wildcards","text":"Wildcards enhance precision and efficiency in file operations.","title":"4. Working with Wildcards"},{"location":"command-line-basics/#41-asterisk","text":"Matches zero or more characters. ls *.jpg # Lists all JPEG files","title":"4.1 Asterisk (*)"},{"location":"command-line-basics/#42-question-mark","text":"Matches exactly one character. ls report_?.txt # Matches report_1.txt, report_2.txt, but not report_10.txt","title":"4.2 Question Mark (?)"},{"location":"command-line-basics/#43-square-brackets","text":"Matches any single character within the brackets. ls [a-c]*.txt # Lists files starting with a, b, or c and ending with .txt","title":"4.3 Square Brackets ([])"},{"location":"command-line-basics/#44-curly-braces","text":"Specifies multiple discrete patterns. ls {*.txt,*.pdf} # Lists all text and PDF files","title":"4.4 Curly Braces ({})"},{"location":"command-line-basics/#5-managing-permissions","text":"Proper permission management is crucial for system security.","title":"5. Managing Permissions"},{"location":"command-line-basics/#51-chmod-change-mode","text":"Adjusts file and directory permissions. chmod u+x file.txt # Adds execute permission for the owner chmod 755 script.sh # Sets rwxr-xr-x permissions","title":"5.1 chmod (Change Mode)"},{"location":"command-line-basics/#52-chown-change-owner","text":"Transfers file or directory ownership. chown user:group file.txt","title":"5.2 chown (Change Owner)"},{"location":"command-line-basics/#53-chgrp-change-group","text":"Modifies the group ownership of files or directories. chgrp team project/","title":"5.3 chgrp (Change Group)"},{"location":"command-line-basics/#54-umask","text":"Sets default creation permissions for new files and directories. umask 022 # Sets default permissions to 644 for files and 755 for directories","title":"5.4 umask"},{"location":"command-line-basics/#6-disk-and-directory-usage","text":"","title":"6. Disk and Directory Usage"},{"location":"command-line-basics/#61-df-disk-free","text":"Displays disk space usage. df -h # Human-readable format","title":"6.1 df (Disk Free)"},{"location":"command-line-basics/#62-du-disk-usage","text":"Estimates space used by directories and files. du -sh /path/to/directory","title":"6.2 du (Disk Usage)"},{"location":"command-line-basics/#7-summary","text":"Mastering these command line basics provides a solid foundation for efficient system management and navigation. Regular practice and application of these commands will enhance your operational capabilities in a digital environment. Remember, the command line is your primary interface for precise control and management of your system resources.","title":"7. Summary"},{"location":"command-line-cheat-sheet/","text":"Command Line Cheat Sheet Navigation pwd # Print working directory ls # List directory contents ls -la # List detailed contents, including hidden files cd # Change directory cd .. # Move up one directory cd ~ # Go to home directory File Operations touch # Create a new file mkdir # Create a new directory cp # Copy file or directory mv # Move or rename file or directory rm # Remove a file rm -r # Remove a directory and its contents File Viewing and Editing cat # Display file contents less # View file contents with pagination head # Show first 10 lines of file tail # Show last 10 lines of file nano # Open file in nano text editor vim # Open file in vim text editor File Permissions chmod +x # Make file executable chmod 755 # Set read, write, execute permissions chown # Change file owner System Information uname -a # Display system information df -h # Show disk usage free -h # Display free and used memory top # Show running processes (interactive) ps aux # List all running processes Network ping # Ping a host ssh @ # SSH into a remote machine scp @: # Secure copy file to remote host wget # Download file from web curl # Send HTTP request Package Management (Debian/Ubuntu) apt update # Update package list apt upgrade # Upgrade installed packages apt install # Install a package apt remove # Remove a package Text Processing grep # Search for pattern in file sed 's/old/new/g' # Replace text in file awk '{print $1}' # Print first column of file Process Management & # Run command in background jobs # List background jobs fg # Bring most recent job to foreground kill # Terminate process by ID Shortcuts Ctrl + C # Interrupt current process Ctrl + Z # Suspend current process Ctrl + D # Exit current shell Ctrl + L # Clear screen Ctrl + R # Search command history Miscellaneous man # Display manual for command history # Show command history echo $PATH # Display PATH environment variable which # Show full path of command Remember, these commands may vary slightly depending on your specific operating system and shell. Always refer to the man pages ( man ) for detailed information about each command.","title":"Command Line Cheat Sheet"},{"location":"command-line-cheat-sheet/#command-line-cheat-sheet","text":"","title":"Command Line Cheat Sheet"},{"location":"command-line-cheat-sheet/#navigation","text":"pwd # Print working directory ls # List directory contents ls -la # List detailed contents, including hidden files cd # Change directory cd .. # Move up one directory cd ~ # Go to home directory","title":"Navigation"},{"location":"command-line-cheat-sheet/#file-operations","text":"touch # Create a new file mkdir # Create a new directory cp # Copy file or directory mv # Move or rename file or directory rm # Remove a file rm -r # Remove a directory and its contents","title":"File Operations"},{"location":"command-line-cheat-sheet/#file-viewing-and-editing","text":"cat # Display file contents less # View file contents with pagination head # Show first 10 lines of file tail # Show last 10 lines of file nano # Open file in nano text editor vim # Open file in vim text editor","title":"File Viewing and Editing"},{"location":"command-line-cheat-sheet/#file-permissions","text":"chmod +x # Make file executable chmod 755 # Set read, write, execute permissions chown # Change file owner","title":"File Permissions"},{"location":"command-line-cheat-sheet/#system-information","text":"uname -a # Display system information df -h # Show disk usage free -h # Display free and used memory top # Show running processes (interactive) ps aux # List all running processes","title":"System Information"},{"location":"command-line-cheat-sheet/#network","text":"ping # Ping a host ssh @ # SSH into a remote machine scp @: # Secure copy file to remote host wget # Download file from web curl # Send HTTP request","title":"Network"},{"location":"command-line-cheat-sheet/#package-management-debianubuntu","text":"apt update # Update package list apt upgrade # Upgrade installed packages apt install # Install a package apt remove # Remove a package","title":"Package Management (Debian/Ubuntu)"},{"location":"command-line-cheat-sheet/#text-processing","text":"grep # Search for pattern in file sed 's/old/new/g' # Replace text in file awk '{print $1}' # Print first column of file","title":"Text Processing"},{"location":"command-line-cheat-sheet/#process-management","text":" & # Run command in background jobs # List background jobs fg # Bring most recent job to foreground kill # Terminate process by ID","title":"Process Management"},{"location":"command-line-cheat-sheet/#shortcuts","text":"Ctrl + C # Interrupt current process Ctrl + Z # Suspend current process Ctrl + D # Exit current shell Ctrl + L # Clear screen Ctrl + R # Search command history","title":"Shortcuts"},{"location":"command-line-cheat-sheet/#miscellaneous","text":"man # Display manual for command history # Show command history echo $PATH # Display PATH environment variable which # Show full path of command Remember, these commands may vary slightly depending on your specific operating system and shell. Always refer to the man pages ( man ) for detailed information about each command.","title":"Miscellaneous"},{"location":"command-line-text-manipulation/","text":"Command Line Text Manipulation SOP 1. Introduction This Standard Operating Procedure (SOP) outlines essential techniques and tools for text manipulation using the command line. Mastering these skills is crucial for efficient data processing, log analysis, file management, and text editing in various operational contexts. Whether you're a software engineer, writer, or instructor based in Atlanta, these skills will significantly enhance your command line proficiency. 2. Viewing Files 2.1 cat Displays entire file content at once. cat file.txt cat -n file.txt # Add line numbers cat -s file.txt # Squeeze multiple blank lines 2.2 less Views files one screen at a time with advanced navigation. less file.txt # Inside less: # /pattern - search forward # ?pattern - search backward # g - go to beginning # G - go to end 2.3 more Similar to less, but with fewer features. more file.txt # Inside more: # Space - next screen # b - previous screen # /pattern - search forward 2.4 tac Displays file content in reverse order. tac file.txt tac -s 'separator' file.txt # Use custom separator 3. Redirects and Pipes [Content remains the same as in the previous version] 4. Regular Expressions [Content remains the same as in the previous version] 5. Searching and Editing [Content remains the same as in the previous version] 6. Sorting and Uniqueness [Content remains the same as in the previous version] 7. Text Comparison [Content remains the same as in the previous version] 8. Text Editing 8.1 nano Simple and user-friendly text editor. nano file.txt # Ctrl+G - Help # Ctrl+O - Save # Ctrl+X - Exit 8.2 vi/vim Powerful and efficient text editor with different modes. vi file.txt # :w - Save # :q - Quit # :wq - Save and quit # /pattern - Search for pattern 8.3 emacs Extensible and customizable text editor. emacs file.txt # Ctrl+x Ctrl+s - Save # Ctrl+x Ctrl+c - Exit # Ctrl+s - Search forward # Ctrl+r - Search backward 8.4 gedit Graphical text editor that can be run from terminal. gedit file.txt gedit --new-window file.txt 9. Best Practices Always make backups before performing large-scale text manipulations. Use version control systems when working with source code. Test complex commands on a small subset of data before applying to large datasets. Combine multiple tools using pipes for more powerful operations. Use man pages or --help flags to explore advanced options of each command. Choose the appropriate text editor based on the task complexity and your familiarity. Practice regularly with different text manipulation tools to improve proficiency. 10. Summary Mastering command line text manipulation tools enhances operational efficiency in various tech-related tasks. From basic file viewing and searching to complex pattern matching, file comparisons, and text editing, these utilities form a powerful toolkit for data processing and file management. The ability to efficiently view, search, manipulate, and edit text files directly from the command line is invaluable in roles such as software development, system administration, and data analysis. By mastering tools like cat, less, grep, sed, awk, and various text editors, you'll be well-equipped to handle a wide range of text-related tasks quickly and effectively. Regular practice with these tools will significantly improve your command line proficiency, data handling capabilities, and overall productivity in tech-related fields. Remember, the key to mastery is consistent application of these skills in real-world scenarios.","title":"Command Line Text Manipulation"},{"location":"command-line-text-manipulation/#command-line-text-manipulation-sop","text":"","title":"Command Line Text Manipulation SOP"},{"location":"command-line-text-manipulation/#1-introduction","text":"This Standard Operating Procedure (SOP) outlines essential techniques and tools for text manipulation using the command line. Mastering these skills is crucial for efficient data processing, log analysis, file management, and text editing in various operational contexts. Whether you're a software engineer, writer, or instructor based in Atlanta, these skills will significantly enhance your command line proficiency.","title":"1. Introduction"},{"location":"command-line-text-manipulation/#2-viewing-files","text":"","title":"2. Viewing Files"},{"location":"command-line-text-manipulation/#21-cat","text":"Displays entire file content at once. cat file.txt cat -n file.txt # Add line numbers cat -s file.txt # Squeeze multiple blank lines","title":"2.1 cat"},{"location":"command-line-text-manipulation/#22-less","text":"Views files one screen at a time with advanced navigation. less file.txt # Inside less: # /pattern - search forward # ?pattern - search backward # g - go to beginning # G - go to end","title":"2.2 less"},{"location":"command-line-text-manipulation/#23-more","text":"Similar to less, but with fewer features. more file.txt # Inside more: # Space - next screen # b - previous screen # /pattern - search forward","title":"2.3 more"},{"location":"command-line-text-manipulation/#24-tac","text":"Displays file content in reverse order. tac file.txt tac -s 'separator' file.txt # Use custom separator","title":"2.4 tac"},{"location":"command-line-text-manipulation/#3-redirects-and-pipes","text":"[Content remains the same as in the previous version]","title":"3. Redirects and Pipes"},{"location":"command-line-text-manipulation/#4-regular-expressions","text":"[Content remains the same as in the previous version]","title":"4. Regular Expressions"},{"location":"command-line-text-manipulation/#5-searching-and-editing","text":"[Content remains the same as in the previous version]","title":"5. Searching and Editing"},{"location":"command-line-text-manipulation/#6-sorting-and-uniqueness","text":"[Content remains the same as in the previous version]","title":"6. Sorting and Uniqueness"},{"location":"command-line-text-manipulation/#7-text-comparison","text":"[Content remains the same as in the previous version]","title":"7. Text Comparison"},{"location":"command-line-text-manipulation/#8-text-editing","text":"","title":"8. Text Editing"},{"location":"command-line-text-manipulation/#81-nano","text":"Simple and user-friendly text editor. nano file.txt # Ctrl+G - Help # Ctrl+O - Save # Ctrl+X - Exit","title":"8.1 nano"},{"location":"command-line-text-manipulation/#82-vivim","text":"Powerful and efficient text editor with different modes. vi file.txt # :w - Save # :q - Quit # :wq - Save and quit # /pattern - Search for pattern","title":"8.2 vi/vim"},{"location":"command-line-text-manipulation/#83-emacs","text":"Extensible and customizable text editor. emacs file.txt # Ctrl+x Ctrl+s - Save # Ctrl+x Ctrl+c - Exit # Ctrl+s - Search forward # Ctrl+r - Search backward","title":"8.3 emacs"},{"location":"command-line-text-manipulation/#84-gedit","text":"Graphical text editor that can be run from terminal. gedit file.txt gedit --new-window file.txt","title":"8.4 gedit"},{"location":"command-line-text-manipulation/#9-best-practices","text":"Always make backups before performing large-scale text manipulations. Use version control systems when working with source code. Test complex commands on a small subset of data before applying to large datasets. Combine multiple tools using pipes for more powerful operations. Use man pages or --help flags to explore advanced options of each command. Choose the appropriate text editor based on the task complexity and your familiarity. Practice regularly with different text manipulation tools to improve proficiency.","title":"9. Best Practices"},{"location":"command-line-text-manipulation/#10-summary","text":"Mastering command line text manipulation tools enhances operational efficiency in various tech-related tasks. From basic file viewing and searching to complex pattern matching, file comparisons, and text editing, these utilities form a powerful toolkit for data processing and file management. The ability to efficiently view, search, manipulate, and edit text files directly from the command line is invaluable in roles such as software development, system administration, and data analysis. By mastering tools like cat, less, grep, sed, awk, and various text editors, you'll be well-equipped to handle a wide range of text-related tasks quickly and effectively. Regular practice with these tools will significantly improve your command line proficiency, data handling capabilities, and overall productivity in tech-related fields. Remember, the key to mastery is consistent application of these skills in real-world scenarios.","title":"10. Summary"},{"location":"command-line-utilities/","text":"Command Line Utilities SOP 1. Introduction This Standard Operating Procedure (SOP) outlines essential command line utilities that enhance productivity and efficiency in various tech-related tasks. These tools are crucial for data transfer, file compression, network management, package management, system monitoring, and user administration. Mastering these utilities will significantly improve your command line proficiency and overall system management capabilities. 2. Data Transfer 2.1 scp (Secure Copy Protocol) Securely transfer files between systems using SSH. scp -P 2222 user@remote:/path/to/file /local/directory scp -r user@remote:/directory/ /local/directory 2.2 rsync (Remote Sync) Efficiently synchronize files and directories between systems. rsync -avz user@remote:/source /local/destination rsync -av --exclude 'path/to/exclude' /source /destination rsync --bwlimit=1000 /source /destination 2.3 wget (Web Get) Retrieve files from web servers. wget -b url wget --retry-connrefused --waitretry=10 --timeout=60 url 2.4 ftp (File Transfer Protocol) Basic file transfer for non-secure data movements. ftp -p host ftp -s:script.txt host 3. File Compression 3.1 zip Package and compress files for easy sharing and storage. zip archive.zip -r target_folder/ -x \\*exclude_pattern\\* zip -u archive.zip updated_file.txt 3.2 tar Bundle files and directories efficiently. tar --listed-incremental=snapshot.file -cvzf backup.tar.gz target_directory/ tar czf - target_directory/ | ssh user@remote \"cat > remote_backup.tar.gz\" 3.3 gzip Maximize compression ratios for faster transfers. gzip -S .custom_suffix large_file cat archive_part1.gz archive_part2.gz > combined_archive.gz 3.4 bzip2 Provide superior compression efficiency for large-scale archival. bzip2 -dc archive.bz2 > output_file pbzip2 -p4 massive_file 4. Network Tools 4.1 ping Test connectivity and measure round-trip time to a host. ping -c 4 google.com 4.2 ssh (Secure Shell) Securely access and execute commands on remote machines. ssh -p port user@hostname ssh -i ~/.ssh/mykey user@192.168.1.100 5. Package Management 5.1 apt (Advanced Package Tool) Manage software on Debian-based systems. sudo apt update && sudo apt upgrade -y echo \"package_name hold\" | sudo dpkg --set-selections 5.2 brew (Homebrew) Package management for macOS. brew tap custom/repo brew services start service_name 5.3 yum (Yellowdog Updater, Modified) Manage RPM packages on Red Hat-based systems. yum history yum --enablerepo=repo_name install package_name 5.4 dpkg (Debian Package) Low-level package management for Debian-based systems. dpkg-query -l dpkg-reconfigure package_name 6. System Information Tools 6.1 uname Display system information. uname -a # Display all information uname -s # Display kernel name uname -r # Display kernel release 6.2 lscpu Display CPU architecture information. lscpu lscpu | grep Virtualization # Check virtualization support 6.3 lshw Display detailed hardware information. sudo lshw -short # Display brief hardware summary sudo lshw -C network # Display network hardware details 6.4 dmesg Display kernel messages. dmesg -Tw # Display kernel messages in real-time with timestamps 7. System Monitoring 7.1 top Monitor system processes and resource usage in real-time. top -b -n 1 > top_output.txt # Capture a snapshot of system state top -p PID1,PID2 # Monitor specific processes 7.2 htop Interactive process viewer and system monitor. htop -u username # Monitor processes for a specific user htop --output-setup-json > setup.json # Export htop configuration 7.3 iostat Report CPU statistics and I/O statistics for devices and partitions. iostat -d /dev/sda # Display I/O statistics for a specific device iostat -e # Display extended statistics 7.4 vmstat Report virtual memory statistics. vmstat -d # Display disk statistics vmstat -e # Display event counter information 8. User and Group Management 8.1 useradd Create a new user account. useradd -m -d /home/jdoe -e 2023-12-31 jdoe # Create user with home directory and expiration date 8.2 groupadd Create a new group. groupadd -r -g 101 developers # Create a system group with specific GID 8.3 sudo Execute a command as another user, typically with administrative privileges. sudo -u jdoe ls /home/jdoe # Execute command as another user 8.4 passwd Change user password and manage account locks. passwd -l jdoe # Lock user account passwd -u jdoe # Unlock user account 9. Best Practices Always verify the integrity of transferred data. Use compression to reduce bandwidth usage and storage requirements. Regularly update package lists and installed software to ensure security. Exercise caution when removing packages to avoid unintended consequences. Use SSH keys for secure, passwordless authentication when accessing remote systems. Implement rate limiting and throttling for large data transfers to avoid network congestion. Choose the appropriate compression algorithm based on the specific requirements of speed, size, and computational resources. Regularly review and update SSH keys to maintain security. Regularly monitor system performance and resource usage to identify and address issues proactively. Use system information tools to gather detailed hardware and software information for troubleshooting and inventory management. Implement proper user and group management practices to enhance system security and organization. Utilize sudo instead of switching to the root user for better security and accountability. Regularly review and update user accounts, removing or disabling unnecessary accounts to maintain system security. 10. Summary Mastering these command line utilities provides a comprehensive toolkit for efficient system management, data handling, network operations, system monitoring, and user management. From secure file transfers and compression to network diagnostics, package management, and system performance analysis, these tools form the backbone of effective command line operations. The ability to gather detailed system information, monitor performance in real-time, and manage users and groups effectively are crucial skills for system administrators and power users. By incorporating these utilities into your workflow, you can significantly enhance your ability to manage, troubleshoot, and optimize Linux systems. Regular practice and application of these utilities will significantly enhance your proficiency in various tech-related roles, from system administration to software development and cybersecurity.","title":"Command Line Utilities"},{"location":"command-line-utilities/#command-line-utilities-sop","text":"","title":"Command Line Utilities SOP"},{"location":"command-line-utilities/#1-introduction","text":"This Standard Operating Procedure (SOP) outlines essential command line utilities that enhance productivity and efficiency in various tech-related tasks. These tools are crucial for data transfer, file compression, network management, package management, system monitoring, and user administration. Mastering these utilities will significantly improve your command line proficiency and overall system management capabilities.","title":"1. Introduction"},{"location":"command-line-utilities/#2-data-transfer","text":"","title":"2. Data Transfer"},{"location":"command-line-utilities/#21-scp-secure-copy-protocol","text":"Securely transfer files between systems using SSH. scp -P 2222 user@remote:/path/to/file /local/directory scp -r user@remote:/directory/ /local/directory","title":"2.1 scp (Secure Copy Protocol)"},{"location":"command-line-utilities/#22-rsync-remote-sync","text":"Efficiently synchronize files and directories between systems. rsync -avz user@remote:/source /local/destination rsync -av --exclude 'path/to/exclude' /source /destination rsync --bwlimit=1000 /source /destination","title":"2.2 rsync (Remote Sync)"},{"location":"command-line-utilities/#23-wget-web-get","text":"Retrieve files from web servers. wget -b url wget --retry-connrefused --waitretry=10 --timeout=60 url","title":"2.3 wget (Web Get)"},{"location":"command-line-utilities/#24-ftp-file-transfer-protocol","text":"Basic file transfer for non-secure data movements. ftp -p host ftp -s:script.txt host","title":"2.4 ftp (File Transfer Protocol)"},{"location":"command-line-utilities/#3-file-compression","text":"","title":"3. File Compression"},{"location":"command-line-utilities/#31-zip","text":"Package and compress files for easy sharing and storage. zip archive.zip -r target_folder/ -x \\*exclude_pattern\\* zip -u archive.zip updated_file.txt","title":"3.1 zip"},{"location":"command-line-utilities/#32-tar","text":"Bundle files and directories efficiently. tar --listed-incremental=snapshot.file -cvzf backup.tar.gz target_directory/ tar czf - target_directory/ | ssh user@remote \"cat > remote_backup.tar.gz\"","title":"3.2 tar"},{"location":"command-line-utilities/#33-gzip","text":"Maximize compression ratios for faster transfers. gzip -S .custom_suffix large_file cat archive_part1.gz archive_part2.gz > combined_archive.gz","title":"3.3 gzip"},{"location":"command-line-utilities/#34-bzip2","text":"Provide superior compression efficiency for large-scale archival. bzip2 -dc archive.bz2 > output_file pbzip2 -p4 massive_file","title":"3.4 bzip2"},{"location":"command-line-utilities/#4-network-tools","text":"","title":"4. Network Tools"},{"location":"command-line-utilities/#41-ping","text":"Test connectivity and measure round-trip time to a host. ping -c 4 google.com","title":"4.1 ping"},{"location":"command-line-utilities/#42-ssh-secure-shell","text":"Securely access and execute commands on remote machines. ssh -p port user@hostname ssh -i ~/.ssh/mykey user@192.168.1.100","title":"4.2 ssh (Secure Shell)"},{"location":"command-line-utilities/#5-package-management","text":"","title":"5. Package Management"},{"location":"command-line-utilities/#51-apt-advanced-package-tool","text":"Manage software on Debian-based systems. sudo apt update && sudo apt upgrade -y echo \"package_name hold\" | sudo dpkg --set-selections","title":"5.1 apt (Advanced Package Tool)"},{"location":"command-line-utilities/#52-brew-homebrew","text":"Package management for macOS. brew tap custom/repo brew services start service_name","title":"5.2 brew (Homebrew)"},{"location":"command-line-utilities/#53-yum-yellowdog-updater-modified","text":"Manage RPM packages on Red Hat-based systems. yum history yum --enablerepo=repo_name install package_name","title":"5.3 yum (Yellowdog Updater, Modified)"},{"location":"command-line-utilities/#54-dpkg-debian-package","text":"Low-level package management for Debian-based systems. dpkg-query -l dpkg-reconfigure package_name","title":"5.4 dpkg (Debian Package)"},{"location":"command-line-utilities/#6-system-information-tools","text":"","title":"6. System Information Tools"},{"location":"command-line-utilities/#61-uname","text":"Display system information. uname -a # Display all information uname -s # Display kernel name uname -r # Display kernel release","title":"6.1 uname"},{"location":"command-line-utilities/#62-lscpu","text":"Display CPU architecture information. lscpu lscpu | grep Virtualization # Check virtualization support","title":"6.2 lscpu"},{"location":"command-line-utilities/#63-lshw","text":"Display detailed hardware information. sudo lshw -short # Display brief hardware summary sudo lshw -C network # Display network hardware details","title":"6.3 lshw"},{"location":"command-line-utilities/#64-dmesg","text":"Display kernel messages. dmesg -Tw # Display kernel messages in real-time with timestamps","title":"6.4 dmesg"},{"location":"command-line-utilities/#7-system-monitoring","text":"","title":"7. System Monitoring"},{"location":"command-line-utilities/#71-top","text":"Monitor system processes and resource usage in real-time. top -b -n 1 > top_output.txt # Capture a snapshot of system state top -p PID1,PID2 # Monitor specific processes","title":"7.1 top"},{"location":"command-line-utilities/#72-htop","text":"Interactive process viewer and system monitor. htop -u username # Monitor processes for a specific user htop --output-setup-json > setup.json # Export htop configuration","title":"7.2 htop"},{"location":"command-line-utilities/#73-iostat","text":"Report CPU statistics and I/O statistics for devices and partitions. iostat -d /dev/sda # Display I/O statistics for a specific device iostat -e # Display extended statistics","title":"7.3 iostat"},{"location":"command-line-utilities/#74-vmstat","text":"Report virtual memory statistics. vmstat -d # Display disk statistics vmstat -e # Display event counter information","title":"7.4 vmstat"},{"location":"command-line-utilities/#8-user-and-group-management","text":"","title":"8. User and Group Management"},{"location":"command-line-utilities/#81-useradd","text":"Create a new user account. useradd -m -d /home/jdoe -e 2023-12-31 jdoe # Create user with home directory and expiration date","title":"8.1 useradd"},{"location":"command-line-utilities/#82-groupadd","text":"Create a new group. groupadd -r -g 101 developers # Create a system group with specific GID","title":"8.2 groupadd"},{"location":"command-line-utilities/#83-sudo","text":"Execute a command as another user, typically with administrative privileges. sudo -u jdoe ls /home/jdoe # Execute command as another user","title":"8.3 sudo"},{"location":"command-line-utilities/#84-passwd","text":"Change user password and manage account locks. passwd -l jdoe # Lock user account passwd -u jdoe # Unlock user account","title":"8.4 passwd"},{"location":"command-line-utilities/#9-best-practices","text":"Always verify the integrity of transferred data. Use compression to reduce bandwidth usage and storage requirements. Regularly update package lists and installed software to ensure security. Exercise caution when removing packages to avoid unintended consequences. Use SSH keys for secure, passwordless authentication when accessing remote systems. Implement rate limiting and throttling for large data transfers to avoid network congestion. Choose the appropriate compression algorithm based on the specific requirements of speed, size, and computational resources. Regularly review and update SSH keys to maintain security. Regularly monitor system performance and resource usage to identify and address issues proactively. Use system information tools to gather detailed hardware and software information for troubleshooting and inventory management. Implement proper user and group management practices to enhance system security and organization. Utilize sudo instead of switching to the root user for better security and accountability. Regularly review and update user accounts, removing or disabling unnecessary accounts to maintain system security.","title":"9. Best Practices"},{"location":"command-line-utilities/#10-summary","text":"Mastering these command line utilities provides a comprehensive toolkit for efficient system management, data handling, network operations, system monitoring, and user management. From secure file transfers and compression to network diagnostics, package management, and system performance analysis, these tools form the backbone of effective command line operations. The ability to gather detailed system information, monitor performance in real-time, and manage users and groups effectively are crucial skills for system administrators and power users. By incorporating these utilities into your workflow, you can significantly enhance your ability to manage, troubleshoot, and optimize Linux systems. Regular practice and application of these utilities will significantly enhance your proficiency in various tech-related roles, from system administration to software development and cybersecurity.","title":"10. Summary"},{"location":"data-patterns/","text":"VetsWhoCode: Intelligence & Data Operations Patterns \ud83c\udf96\ufe0f \"Like military intelligence, data operations require precision, scale, and adaptability.\" - VetsWhoCode Overview This field manual covers patterns for handling large-scale data operations and AI systems, explained through military analogies and practical implementations. Table of Contents Data Processing Patterns Machine Learning Patterns Data Storage Patterns Data Integration Patterns Data Processing Patterns Military Context Like coordinating large-scale military operations, these patterns handle massive data processing operations efficiently and reliably. 1. MapReduce - Distributed Intelligence Analysis class MapReduceFramework: \"\"\" Mission: Process large datasets using distributed computing resources. Tactical Application: - Like coordinating multiple intelligence teams - Each team processes specific intel (Map) - Command aggregates findings (Reduce) \"\"\" def __init__(self): self.data_chunks = [] self.results = [] def map_phase(self, data, map_function): # Distribute data to processing units mapped_data = [] for chunk in self.data_chunks: result = map_function(chunk) mapped_data.append(result) return mapped_data def reduce_phase(self, mapped_data, reduce_function): # Combine results from all units return reduce_function(mapped_data) def execute(self, data, map_fn, reduce_fn): self.data_chunks = self._split_data(data) mapped_data = self.map_phase(self.data_chunks, map_fn) return self.reduce_phase(mapped_data, reduce_fn) def _split_data(self, data, chunk_size=1000): return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)] # Field Implementation def word_count_map(text): return [(word, 1) for word in text.split()] def word_count_reduce(mapped_data): word_counts = {} for word, count in mapped_data: word_counts[word] = word_counts.get(word, 0) + count return word_counts mapreduce = MapReduceFramework() intel_data = \"Enemy movement detected in sector alpha...\" results = mapreduce.execute(intel_data, word_count_map, word_count_reduce) 2. Stream Processing - Real-time Intelligence from datetime import datetime from queue import Queue class StreamProcessor: \"\"\" Mission: Process continuous data streams in real-time. Tactical Application: - Like real-time battlefield monitoring - Continuous intelligence gathering - Immediate threat detection \"\"\" def __init__(self): self.data_stream = Queue() self.processors = [] self.alert_threshold = 0.8 def add_processor(self, processor): self.processors.append(processor) def process_event(self, event): event['timestamp'] = datetime.now() for processor in self.processors: event = processor.process(event) if self._detect_threat(event): self._raise_alert(event) return event def _detect_threat(self, event): return event.get('threat_level', 0) > self.alert_threshold def _raise_alert(self, event): print(f\"ALERT: High threat detected - {event}\") # Field Implementation class ThreatDetector: def process(self, event): # Analyze event for threats if 'enemy_activity' in event['data']: event['threat_level'] = 0.9 return event stream_processor = StreamProcessor() stream_processor.add_processor(ThreatDetector()) Machine Learning Patterns Military Context Like training and deploying specialized units, ML patterns focus on building and deploying intelligent systems. 1. Feature Engineering - Intelligence Preparation import numpy as np class FeatureEngineer: \"\"\" Mission: Transform raw intelligence into actionable features. Tactical Application: - Like processing raw intel into actionable intelligence - Identify key indicators - Standardize reporting formats \"\"\" def __init__(self): self.feature_transformers = {} self.feature_importance = {} def add_transformer(self, feature_name, transformer): self.feature_transformers[feature_name] = transformer def transform_features(self, raw_data): features = {} for name, transformer in self.feature_transformers.items(): features[name] = transformer(raw_data) return self._normalize_features(features) def _normalize_features(self, features): # Standardize feature values for name, values in features.items(): if isinstance(values, (list, np.ndarray)): features[name] = (values - np.mean(values)) / np.std(values) return features # Field Implementation def location_transformer(data): # Convert location data to grid coordinates return [data['lat'], data['lon']] engineer = FeatureEngineer() engineer.add_transformer('location', location_transformer) 2. Model Deployment - Unit Deployment class ModelDeployment: \"\"\" Mission: Deploy and monitor ML models in production. Tactical Application: - Like deploying specialized units - Continuous monitoring - Performance evaluation \"\"\" def __init__(self, model, version): self.model = model self.version = version self.metrics = { 'accuracy': [], 'latency': [], 'errors': [] } def predict(self, input_data): try: start_time = time.time() prediction = self.model.predict(input_data) latency = time.time() - start_time self._update_metrics(prediction, latency) return prediction except Exception as e: self._log_error(e) return None def _update_metrics(self, prediction, latency): self.metrics['latency'].append(latency) # Update other metrics def _log_error(self, error): self.metrics['errors'].append({ 'timestamp': datetime.now(), 'error': str(error) }) # Field Implementation model_deployment = ModelDeployment(trained_model, version=\"1.0\") Data Storage Patterns Military Context Like managing military logistics and intelligence archives, these patterns handle data storage and retrieval efficiently. 1. Data Lake - Central Intelligence Repository class DataLake: \"\"\" Mission: Store vast amounts of raw intelligence data. Tactical Application: - Like central intelligence repository - Raw data storage - Multiple access patterns \"\"\" def __init__(self, storage_path): self.storage_path = storage_path self.metadata = {} self.access_logs = [] def store_data(self, data_id, data, metadata=None): # Store raw data with metadata file_path = f\"{self.storage_path}/{data_id}\" self._write_data(file_path, data) if metadata: self.metadata[data_id] = metadata self._log_access('write', data_id) def retrieve_data(self, data_id): # Retrieve data and log access file_path = f\"{self.storage_path}/{data_id}\" data = self._read_data(file_path) self._log_access('read', data_id) return data def _log_access(self, operation, data_id): self.access_logs.append({ 'timestamp': datetime.now(), 'operation': operation, 'data_id': data_id }) # Field Implementation data_lake = DataLake(\"/path/to/storage\") data_lake.store_data(\"intel_001\", intel_data, {\"classification\": \"SECRET\"}) 2. Hot-Warm-Cold Storage - Intelligence Tiering class TieredStorage: \"\"\" Mission: Optimize data storage based on access patterns. Tactical Application: - Like tiered intelligence classification - Priority-based access - Resource optimization \"\"\" def __init__(self): self.hot_storage = {} # Active intelligence self.warm_storage = {} # Recent intelligence self.cold_storage = {} # Archived intelligence def store_data(self, data_id, data, tier='hot'): if tier == 'hot': self.hot_storage[data_id] = data elif tier == 'warm': self.warm_storage[data_id] = data else: self.cold_storage[data_id] = data def access_data(self, data_id): # Check each tier and promote if needed if data_id in self.cold_storage: data = self.cold_storage.pop(data_id) self.warm_storage[data_id] = data return data if data_id in self.warm_storage: data = self.warm_storage.pop(data_id) self.hot_storage[data_id] = data return data return self.hot_storage.get(data_id) # Field Implementation storage = TieredStorage() storage.store_data(\"current_ops\", ops_data, \"hot\") storage.store_data(\"last_month\", old_data, \"warm\") Data Integration Patterns Military Context Like coordinating joint operations, these patterns ensure smooth data flow between different systems. 1. Data Pipeline - Intelligence Flow class DataPipeline: \"\"\" Mission: Coordinate data flow between systems. Tactical Application: - Like intelligence flow in joint operations - Coordinated data movement - Quality control \"\"\" def __init__(self): self.stages = [] self.monitoring = PipelineMonitor() def add_stage(self, stage): self.stages.append(stage) def execute(self, data): current_data = data for stage in self.stages: try: current_data = stage.process(current_data) self.monitoring.log_success(stage.name) except Exception as e: self.monitoring.log_failure(stage.name, str(e)) raise e return current_data # Field Implementation class DataStage: def __init__(self, name, process_fn): self.name = name self.process = process_fn pipeline = DataPipeline() pipeline.add_stage(DataStage(\"extract\", extract_fn)) pipeline.add_stage(DataStage(\"transform\", transform_fn)) 2. Event-Driven ETL - Intelligence Updates class EventDrivenETL: \"\"\" Mission: Process data updates in real-time. Tactical Application: - Like real-time intelligence updates - Immediate data processing - Automated responses \"\"\" def __init__(self): self.event_handlers = {} self.event_queue = Queue() def register_handler(self, event_type, handler): self.event_handlers[event_type] = handler def process_event(self, event): event_type = event['type'] if event_type in self.event_handlers: handler = self.event_handlers[event_type] return handler(event['data']) else: raise ValueError(f\"No handler for event type: {event_type}\") # Field Implementation def intel_update_handler(data): # Process intelligence update return processed_data etl = EventDrivenETL() etl.register_handler(\"intel_update\", intel_update_handler) Additional Resources Training Materials Data Operations Field Manual AI/ML Deployment Guide Field Notes Data operations require strategic planning and tactical execution Always consider: Data quality (intelligence accuracy) Processing efficiency (operational speed) Storage optimization (resource management) Remember: Good data leads to good decisions \"Processing data with military precision\" - VetsWhoCode","title":"Data Patterns"},{"location":"data-patterns/#vetswhocode-intelligence-data-operations-patterns","text":"\"Like military intelligence, data operations require precision, scale, and adaptability.\" - VetsWhoCode","title":"VetsWhoCode: Intelligence & Data Operations Patterns \ud83c\udf96\ufe0f"},{"location":"data-patterns/#overview","text":"This field manual covers patterns for handling large-scale data operations and AI systems, explained through military analogies and practical implementations.","title":"Overview"},{"location":"data-patterns/#table-of-contents","text":"Data Processing Patterns Machine Learning Patterns Data Storage Patterns Data Integration Patterns","title":"Table of Contents"},{"location":"data-patterns/#data-processing-patterns","text":"","title":"Data Processing Patterns"},{"location":"data-patterns/#military-context","text":"Like coordinating large-scale military operations, these patterns handle massive data processing operations efficiently and reliably.","title":"Military Context"},{"location":"data-patterns/#1-mapreduce-distributed-intelligence-analysis","text":"class MapReduceFramework: \"\"\" Mission: Process large datasets using distributed computing resources. Tactical Application: - Like coordinating multiple intelligence teams - Each team processes specific intel (Map) - Command aggregates findings (Reduce) \"\"\" def __init__(self): self.data_chunks = [] self.results = [] def map_phase(self, data, map_function): # Distribute data to processing units mapped_data = [] for chunk in self.data_chunks: result = map_function(chunk) mapped_data.append(result) return mapped_data def reduce_phase(self, mapped_data, reduce_function): # Combine results from all units return reduce_function(mapped_data) def execute(self, data, map_fn, reduce_fn): self.data_chunks = self._split_data(data) mapped_data = self.map_phase(self.data_chunks, map_fn) return self.reduce_phase(mapped_data, reduce_fn) def _split_data(self, data, chunk_size=1000): return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)] # Field Implementation def word_count_map(text): return [(word, 1) for word in text.split()] def word_count_reduce(mapped_data): word_counts = {} for word, count in mapped_data: word_counts[word] = word_counts.get(word, 0) + count return word_counts mapreduce = MapReduceFramework() intel_data = \"Enemy movement detected in sector alpha...\" results = mapreduce.execute(intel_data, word_count_map, word_count_reduce)","title":"1. MapReduce - Distributed Intelligence Analysis"},{"location":"data-patterns/#2-stream-processing-real-time-intelligence","text":"from datetime import datetime from queue import Queue class StreamProcessor: \"\"\" Mission: Process continuous data streams in real-time. Tactical Application: - Like real-time battlefield monitoring - Continuous intelligence gathering - Immediate threat detection \"\"\" def __init__(self): self.data_stream = Queue() self.processors = [] self.alert_threshold = 0.8 def add_processor(self, processor): self.processors.append(processor) def process_event(self, event): event['timestamp'] = datetime.now() for processor in self.processors: event = processor.process(event) if self._detect_threat(event): self._raise_alert(event) return event def _detect_threat(self, event): return event.get('threat_level', 0) > self.alert_threshold def _raise_alert(self, event): print(f\"ALERT: High threat detected - {event}\") # Field Implementation class ThreatDetector: def process(self, event): # Analyze event for threats if 'enemy_activity' in event['data']: event['threat_level'] = 0.9 return event stream_processor = StreamProcessor() stream_processor.add_processor(ThreatDetector())","title":"2. Stream Processing - Real-time Intelligence"},{"location":"data-patterns/#machine-learning-patterns","text":"","title":"Machine Learning Patterns"},{"location":"data-patterns/#military-context_1","text":"Like training and deploying specialized units, ML patterns focus on building and deploying intelligent systems.","title":"Military Context"},{"location":"data-patterns/#1-feature-engineering-intelligence-preparation","text":"import numpy as np class FeatureEngineer: \"\"\" Mission: Transform raw intelligence into actionable features. Tactical Application: - Like processing raw intel into actionable intelligence - Identify key indicators - Standardize reporting formats \"\"\" def __init__(self): self.feature_transformers = {} self.feature_importance = {} def add_transformer(self, feature_name, transformer): self.feature_transformers[feature_name] = transformer def transform_features(self, raw_data): features = {} for name, transformer in self.feature_transformers.items(): features[name] = transformer(raw_data) return self._normalize_features(features) def _normalize_features(self, features): # Standardize feature values for name, values in features.items(): if isinstance(values, (list, np.ndarray)): features[name] = (values - np.mean(values)) / np.std(values) return features # Field Implementation def location_transformer(data): # Convert location data to grid coordinates return [data['lat'], data['lon']] engineer = FeatureEngineer() engineer.add_transformer('location', location_transformer)","title":"1. Feature Engineering - Intelligence Preparation"},{"location":"data-patterns/#2-model-deployment-unit-deployment","text":"class ModelDeployment: \"\"\" Mission: Deploy and monitor ML models in production. Tactical Application: - Like deploying specialized units - Continuous monitoring - Performance evaluation \"\"\" def __init__(self, model, version): self.model = model self.version = version self.metrics = { 'accuracy': [], 'latency': [], 'errors': [] } def predict(self, input_data): try: start_time = time.time() prediction = self.model.predict(input_data) latency = time.time() - start_time self._update_metrics(prediction, latency) return prediction except Exception as e: self._log_error(e) return None def _update_metrics(self, prediction, latency): self.metrics['latency'].append(latency) # Update other metrics def _log_error(self, error): self.metrics['errors'].append({ 'timestamp': datetime.now(), 'error': str(error) }) # Field Implementation model_deployment = ModelDeployment(trained_model, version=\"1.0\")","title":"2. Model Deployment - Unit Deployment"},{"location":"data-patterns/#data-storage-patterns","text":"","title":"Data Storage Patterns"},{"location":"data-patterns/#military-context_2","text":"Like managing military logistics and intelligence archives, these patterns handle data storage and retrieval efficiently.","title":"Military Context"},{"location":"data-patterns/#1-data-lake-central-intelligence-repository","text":"class DataLake: \"\"\" Mission: Store vast amounts of raw intelligence data. Tactical Application: - Like central intelligence repository - Raw data storage - Multiple access patterns \"\"\" def __init__(self, storage_path): self.storage_path = storage_path self.metadata = {} self.access_logs = [] def store_data(self, data_id, data, metadata=None): # Store raw data with metadata file_path = f\"{self.storage_path}/{data_id}\" self._write_data(file_path, data) if metadata: self.metadata[data_id] = metadata self._log_access('write', data_id) def retrieve_data(self, data_id): # Retrieve data and log access file_path = f\"{self.storage_path}/{data_id}\" data = self._read_data(file_path) self._log_access('read', data_id) return data def _log_access(self, operation, data_id): self.access_logs.append({ 'timestamp': datetime.now(), 'operation': operation, 'data_id': data_id }) # Field Implementation data_lake = DataLake(\"/path/to/storage\") data_lake.store_data(\"intel_001\", intel_data, {\"classification\": \"SECRET\"})","title":"1. Data Lake - Central Intelligence Repository"},{"location":"data-patterns/#2-hot-warm-cold-storage-intelligence-tiering","text":"class TieredStorage: \"\"\" Mission: Optimize data storage based on access patterns. Tactical Application: - Like tiered intelligence classification - Priority-based access - Resource optimization \"\"\" def __init__(self): self.hot_storage = {} # Active intelligence self.warm_storage = {} # Recent intelligence self.cold_storage = {} # Archived intelligence def store_data(self, data_id, data, tier='hot'): if tier == 'hot': self.hot_storage[data_id] = data elif tier == 'warm': self.warm_storage[data_id] = data else: self.cold_storage[data_id] = data def access_data(self, data_id): # Check each tier and promote if needed if data_id in self.cold_storage: data = self.cold_storage.pop(data_id) self.warm_storage[data_id] = data return data if data_id in self.warm_storage: data = self.warm_storage.pop(data_id) self.hot_storage[data_id] = data return data return self.hot_storage.get(data_id) # Field Implementation storage = TieredStorage() storage.store_data(\"current_ops\", ops_data, \"hot\") storage.store_data(\"last_month\", old_data, \"warm\")","title":"2. Hot-Warm-Cold Storage - Intelligence Tiering"},{"location":"data-patterns/#data-integration-patterns","text":"","title":"Data Integration Patterns"},{"location":"data-patterns/#military-context_3","text":"Like coordinating joint operations, these patterns ensure smooth data flow between different systems.","title":"Military Context"},{"location":"data-patterns/#1-data-pipeline-intelligence-flow","text":"class DataPipeline: \"\"\" Mission: Coordinate data flow between systems. Tactical Application: - Like intelligence flow in joint operations - Coordinated data movement - Quality control \"\"\" def __init__(self): self.stages = [] self.monitoring = PipelineMonitor() def add_stage(self, stage): self.stages.append(stage) def execute(self, data): current_data = data for stage in self.stages: try: current_data = stage.process(current_data) self.monitoring.log_success(stage.name) except Exception as e: self.monitoring.log_failure(stage.name, str(e)) raise e return current_data # Field Implementation class DataStage: def __init__(self, name, process_fn): self.name = name self.process = process_fn pipeline = DataPipeline() pipeline.add_stage(DataStage(\"extract\", extract_fn)) pipeline.add_stage(DataStage(\"transform\", transform_fn))","title":"1. Data Pipeline - Intelligence Flow"},{"location":"data-patterns/#2-event-driven-etl-intelligence-updates","text":"class EventDrivenETL: \"\"\" Mission: Process data updates in real-time. Tactical Application: - Like real-time intelligence updates - Immediate data processing - Automated responses \"\"\" def __init__(self): self.event_handlers = {} self.event_queue = Queue() def register_handler(self, event_type, handler): self.event_handlers[event_type] = handler def process_event(self, event): event_type = event['type'] if event_type in self.event_handlers: handler = self.event_handlers[event_type] return handler(event['data']) else: raise ValueError(f\"No handler for event type: {event_type}\") # Field Implementation def intel_update_handler(data): # Process intelligence update return processed_data etl = EventDrivenETL() etl.register_handler(\"intel_update\", intel_update_handler)","title":"2. Event-Driven ETL - Intelligence Updates"},{"location":"data-patterns/#additional-resources","text":"","title":"Additional Resources"},{"location":"data-patterns/#training-materials","text":"Data Operations Field Manual AI/ML Deployment Guide","title":"Training Materials"},{"location":"data-patterns/#field-notes","text":"Data operations require strategic planning and tactical execution Always consider: Data quality (intelligence accuracy) Processing efficiency (operational speed) Storage optimization (resource management) Remember: Good data leads to good decisions \"Processing data with military precision\" - VetsWhoCode","title":"Field Notes"},{"location":"fast-api-testing/","text":"","title":"Testing In FastAPI"},{"location":"fast-api/","text":"Vets Who Code - FastAPI Operations Guide \ud83c\udf96\ufe0f Mission Brief: FastAPI Introduction FastAPI is like a highly efficient FOB (Forward Operating Base) for your web operations. It's: Fast (high-performance) Easy to deploy Built for modern Python operations Automatically documented Production-ready Phase 1: Base Setup Required Equipment # Create virtual environment python -m venv venv # Activate virtual environment # Windows: venv\\Scripts\\activate # Mac/Linux: source venv/bin/activate # Install dependencies pip install fastapi uvicorn First Deployment # main.py from fastapi import FastAPI # Initialize FOB (Create FastAPI instance) app = FastAPI( title=\"VWC API Operations\", description=\"Veteran-focused API operations\", version=\"1.0.0\" ) # First Checkpoint (Root endpoint) @app.get(\"/\") async def base_check(): return { \"status\": \"operational\", \"message\": \"VWC API Standing By\" } Launch Operations # Start the server uvicorn main:app --reload Phase 2: Basic Operations (Routes) Personnel Management System from typing import List, Optional from pydantic import BaseModel from datetime import date # Data Models (Intel Structure) class ServiceMember(BaseModel): id: int first_name: str last_name: str rank: str branch: str service_start: date status: str = \"Active\" # Database Simulation db_personnel = [] # Routes @app.post(\"/personnel/\", response_model=ServiceMember) async def create_personnel(member: ServiceMember): db_personnel.append(member) return member @app.get(\"/personnel/\", response_model=List[ServiceMember]) async def get_all_personnel(): return db_personnel @app.get(\"/personnel/{member_id}\", response_model=ServiceMember) async def get_personnel(member_id: int): for member in db_personnel: if member.id == member_id: return member raise HTTPException(status_code=404, detail=\"Service member not found\") Phase 3: Advanced Operations Authentication & Security from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from datetime import datetime, timedelta # Security Configuration SECRET_KEY = \"your-secret-key\" ALGORITHM = \"HS256\" ACCESS_TOKEN_EXPIRE_MINUTES = 30 pwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\") oauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\") # User Model class User(BaseModel): username: str full_name: Optional[str] = None disabled: Optional[bool] = None # Token Generation def create_access_token(data: dict): to_encode = data.copy() expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({\"exp\": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt # Authentication Route @app.post(\"/token\") async def login(form_data: OAuth2PasswordRequestForm = Depends()): # Authentication logic here access_token = create_access_token(data={\"sub\": form_data.username}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} Award System API from enum import Enum class AwardType(str, Enum): PURPLE_HEART = \"Purple Heart\" BRONZE_STAR = \"Bronze Star\" COMBAT_ACTION = \"Combat Action Ribbon\" class Award(BaseModel): type: AwardType recipient_id: int award_date: date citation: Optional[str] = None @app.post(\"/awards/\") async def issue_award(award: Award, token: str = Depends(oauth2_scheme)): # Award issuing logic return {\"status\": \"Award issued\", \"award\": award} @app.get(\"/personnel/{member_id}/awards\") async def get_member_awards(member_id: int, token: str = Depends(oauth2_scheme)): # Award retrieval logic return {\"member_id\": member_id, \"awards\": []} Phase 4: Database Integration Using SQLAlchemy from sqlalchemy import create_engine, Column, Integer, String, Date from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = \"sqlite:///./vwc_operations.db\" engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() # Database Models class DBServiceMember(Base): __tablename__ = \"service_members\" id = Column(Integer, primary_key=True, index=True) first_name = Column(String) last_name = Column(String) rank = Column(String) branch = Column(String) service_start = Column(Date) status = Column(String) # Database Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() # Updated Routes with Database @app.post(\"/personnel/\", response_model=ServiceMember) async def create_personnel( member: ServiceMember, db: Session = Depends(get_db) ): db_member = DBServiceMember(**member.dict()) db.add(db_member) db.commit() db.refresh(db_member) return db_member Phase 5: Background Tasks Mission Status Updates from fastapi import BackgroundTasks def update_mission_status(mission_id: str): # Simulate long-running task time.sleep(5) # Update mission status logic here print(f\"Mission {mission_id} status updated\") @app.post(\"/missions/{mission_id}/status\") async def update_status( mission_id: str, background_tasks: BackgroundTasks ): background_tasks.add_task(update_mission_status, mission_id) return {\"message\": \"Status update initiated\"} Field Exercise: Complete API Implementation Here's a practical exercise combining these concepts - a Veteran Service Record System: # Complete implementation example from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks from typing import List, Optional from pydantic import BaseModel from datetime import date import asyncio app = FastAPI(title=\"Veteran Service Record System\") # Models class ServiceRecord(BaseModel): id: int name: str service_number: str branch: str rank: str start_date: date end_date: Optional[date] = None status: str awards: List[str] = [] # Simulated Database records_db = {} # Routes @app.post(\"/records/\", response_model=ServiceRecord) async def create_record(record: ServiceRecord): if record.id in records_db: raise HTTPException(status_code=400, detail=\"Record already exists\") records_db[record.id] = record return record @app.get(\"/records/{record_id}\", response_model=ServiceRecord) async def get_record(record_id: int): if record_id not in records_db: raise HTTPException(status_code=404, detail=\"Record not found\") return records_db[record_id] @app.put(\"/records/{record_id}/awards\") async def add_award( record_id: int, award: str, background_tasks: BackgroundTasks ): if record_id not in records_db: raise HTTPException(status_code=404, detail=\"Record not found\") background_tasks.add_task(update_award_database, record_id, award) records_db[record_id].awards.append(award) return {\"message\": \"Award added successfully\"} # Background task async def update_award_database(record_id: int, award: str): await asyncio.sleep(2) # Simulate database update print(f\"Award {award} recorded for service member {record_id}\") Next Mission Parameters Advanced Topics: WebSocket implementations File uploads/downloads Rate limiting Caching Testing FastAPI applications Deployment Operations: Docker containerization Cloud deployment (AWS, Azure, GCP) CI/CD pipelines Production configurations Remember: Document your APIs thoroughly Implement proper security measures Test all endpoints Handle errors gracefully Monitor performance \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Introduction To FastAPI"},{"location":"fast-api/#vets-who-code-fastapi-operations-guide","text":"","title":"Vets Who Code - FastAPI Operations Guide \ud83c\udf96\ufe0f"},{"location":"fast-api/#mission-brief-fastapi-introduction","text":"FastAPI is like a highly efficient FOB (Forward Operating Base) for your web operations. It's: Fast (high-performance) Easy to deploy Built for modern Python operations Automatically documented Production-ready","title":"Mission Brief: FastAPI Introduction"},{"location":"fast-api/#phase-1-base-setup","text":"","title":"Phase 1: Base Setup"},{"location":"fast-api/#required-equipment","text":"# Create virtual environment python -m venv venv # Activate virtual environment # Windows: venv\\Scripts\\activate # Mac/Linux: source venv/bin/activate # Install dependencies pip install fastapi uvicorn","title":"Required Equipment"},{"location":"fast-api/#first-deployment","text":"# main.py from fastapi import FastAPI # Initialize FOB (Create FastAPI instance) app = FastAPI( title=\"VWC API Operations\", description=\"Veteran-focused API operations\", version=\"1.0.0\" ) # First Checkpoint (Root endpoint) @app.get(\"/\") async def base_check(): return { \"status\": \"operational\", \"message\": \"VWC API Standing By\" }","title":"First Deployment"},{"location":"fast-api/#launch-operations","text":"# Start the server uvicorn main:app --reload","title":"Launch Operations"},{"location":"fast-api/#phase-2-basic-operations-routes","text":"","title":"Phase 2: Basic Operations (Routes)"},{"location":"fast-api/#personnel-management-system","text":"from typing import List, Optional from pydantic import BaseModel from datetime import date # Data Models (Intel Structure) class ServiceMember(BaseModel): id: int first_name: str last_name: str rank: str branch: str service_start: date status: str = \"Active\" # Database Simulation db_personnel = [] # Routes @app.post(\"/personnel/\", response_model=ServiceMember) async def create_personnel(member: ServiceMember): db_personnel.append(member) return member @app.get(\"/personnel/\", response_model=List[ServiceMember]) async def get_all_personnel(): return db_personnel @app.get(\"/personnel/{member_id}\", response_model=ServiceMember) async def get_personnel(member_id: int): for member in db_personnel: if member.id == member_id: return member raise HTTPException(status_code=404, detail=\"Service member not found\")","title":"Personnel Management System"},{"location":"fast-api/#phase-3-advanced-operations","text":"","title":"Phase 3: Advanced Operations"},{"location":"fast-api/#authentication-security","text":"from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from datetime import datetime, timedelta # Security Configuration SECRET_KEY = \"your-secret-key\" ALGORITHM = \"HS256\" ACCESS_TOKEN_EXPIRE_MINUTES = 30 pwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\") oauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\") # User Model class User(BaseModel): username: str full_name: Optional[str] = None disabled: Optional[bool] = None # Token Generation def create_access_token(data: dict): to_encode = data.copy() expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({\"exp\": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt # Authentication Route @app.post(\"/token\") async def login(form_data: OAuth2PasswordRequestForm = Depends()): # Authentication logic here access_token = create_access_token(data={\"sub\": form_data.username}) return {\"access_token\": access_token, \"token_type\": \"bearer\"}","title":"Authentication & Security"},{"location":"fast-api/#award-system-api","text":"from enum import Enum class AwardType(str, Enum): PURPLE_HEART = \"Purple Heart\" BRONZE_STAR = \"Bronze Star\" COMBAT_ACTION = \"Combat Action Ribbon\" class Award(BaseModel): type: AwardType recipient_id: int award_date: date citation: Optional[str] = None @app.post(\"/awards/\") async def issue_award(award: Award, token: str = Depends(oauth2_scheme)): # Award issuing logic return {\"status\": \"Award issued\", \"award\": award} @app.get(\"/personnel/{member_id}/awards\") async def get_member_awards(member_id: int, token: str = Depends(oauth2_scheme)): # Award retrieval logic return {\"member_id\": member_id, \"awards\": []}","title":"Award System API"},{"location":"fast-api/#phase-4-database-integration","text":"","title":"Phase 4: Database Integration"},{"location":"fast-api/#using-sqlalchemy","text":"from sqlalchemy import create_engine, Column, Integer, String, Date from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = \"sqlite:///./vwc_operations.db\" engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() # Database Models class DBServiceMember(Base): __tablename__ = \"service_members\" id = Column(Integer, primary_key=True, index=True) first_name = Column(String) last_name = Column(String) rank = Column(String) branch = Column(String) service_start = Column(Date) status = Column(String) # Database Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() # Updated Routes with Database @app.post(\"/personnel/\", response_model=ServiceMember) async def create_personnel( member: ServiceMember, db: Session = Depends(get_db) ): db_member = DBServiceMember(**member.dict()) db.add(db_member) db.commit() db.refresh(db_member) return db_member","title":"Using SQLAlchemy"},{"location":"fast-api/#phase-5-background-tasks","text":"","title":"Phase 5: Background Tasks"},{"location":"fast-api/#mission-status-updates","text":"from fastapi import BackgroundTasks def update_mission_status(mission_id: str): # Simulate long-running task time.sleep(5) # Update mission status logic here print(f\"Mission {mission_id} status updated\") @app.post(\"/missions/{mission_id}/status\") async def update_status( mission_id: str, background_tasks: BackgroundTasks ): background_tasks.add_task(update_mission_status, mission_id) return {\"message\": \"Status update initiated\"}","title":"Mission Status Updates"},{"location":"fast-api/#field-exercise-complete-api-implementation","text":"Here's a practical exercise combining these concepts - a Veteran Service Record System: # Complete implementation example from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks from typing import List, Optional from pydantic import BaseModel from datetime import date import asyncio app = FastAPI(title=\"Veteran Service Record System\") # Models class ServiceRecord(BaseModel): id: int name: str service_number: str branch: str rank: str start_date: date end_date: Optional[date] = None status: str awards: List[str] = [] # Simulated Database records_db = {} # Routes @app.post(\"/records/\", response_model=ServiceRecord) async def create_record(record: ServiceRecord): if record.id in records_db: raise HTTPException(status_code=400, detail=\"Record already exists\") records_db[record.id] = record return record @app.get(\"/records/{record_id}\", response_model=ServiceRecord) async def get_record(record_id: int): if record_id not in records_db: raise HTTPException(status_code=404, detail=\"Record not found\") return records_db[record_id] @app.put(\"/records/{record_id}/awards\") async def add_award( record_id: int, award: str, background_tasks: BackgroundTasks ): if record_id not in records_db: raise HTTPException(status_code=404, detail=\"Record not found\") background_tasks.add_task(update_award_database, record_id, award) records_db[record_id].awards.append(award) return {\"message\": \"Award added successfully\"} # Background task async def update_award_database(record_id: int, award: str): await asyncio.sleep(2) # Simulate database update print(f\"Award {award} recorded for service member {record_id}\")","title":"Field Exercise: Complete API Implementation"},{"location":"fast-api/#next-mission-parameters","text":"Advanced Topics: WebSocket implementations File uploads/downloads Rate limiting Caching Testing FastAPI applications Deployment Operations: Docker containerization Cloud deployment (AWS, Azure, GCP) CI/CD pipelines Production configurations Remember: Document your APIs thoroughly Implement proper security measures Test all endpoints Handle errors gracefully Monitor performance \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Next Mission Parameters"},{"location":"getting-to-know-the-command-line/","text":"Getting to Know the Command Line Introduction The command line interface (CLI) is a powerful tool that allows users to interact directly with their computer's operating system through text-based commands. Despite the prevalence of graphical user interfaces (GUIs), the command line remains an essential skill for developers, system administrators, and power users. This guide will introduce you to the world of command-line interfaces, explain their importance, and help you understand the key components involved. What is the Command Line? The command line, or CLI, is an environment where users can input text commands to perform specific tasks on a computer. Unlike GUIs, which use visual elements for interaction, the CLI relies entirely on textual input and output. Historical Context Originating in the 1960s, the command line predates graphical interfaces, offering an advanced method of computer interaction. This era of computing required users to engage directly with the system through typed commands, a significant evolution from punch cards and manual input methods. Why Use the Command Line? Despite the user-friendliness of modern GUIs, the command line offers several compelling advantages: Speed : Execute commands and manage system resources quickly, bypassing graphical overhead. Versatility : Perform complex operations that might be cumbersome or impossible through a GUI. Automation : Write scripts to automate tasks, saving time and reducing human error. Remote Management : Access and control remote systems without needing a graphical interface. These benefits make the CLI an invaluable tool for various tech-related fields, including software development, system administration, and data science. Understanding Terminals and Shells To effectively use the command line, it's crucial to understand two key components: terminals and shells. Terminal Emulators A terminal emulator is a software application that provides a graphical interface for interacting with the shell. It simulates the functionality of traditional hardware terminals within modern desktop environments. Popular terminal emulators include: Hyper : Cross-platform, built with web technologies, and highly extensible. iTerm2 : Feature-rich terminal for macOS with advanced customization options. PuTTY : Commonly used in Windows environments, supporting various network protocols. Shells The shell acts as an interpreter, executing user commands and managing communication between the user and the kernel. It provides a scripting language and executes system commands and scripts. Common shell types include: Bash (Bourne-Again SHell) : The default shell in many Linux distributions and older macOS versions. Zsh (Z Shell) : The default shell in newer macOS versions, known for its customizability. Fish (Friendly Interactive SHell) : Focused on user-friendliness with features like autosuggestions. Dash (Debian Almquist Shell) : Prioritizes efficiency and speed, often used for system-level scripting. Key Differences: Terminal vs. Shell While often mentioned together, terminals and shells serve distinct roles: Terminal : Provides the user interface for command input and system feedback. Shell : Interprets and executes the commands entered in the terminal. Understanding this distinction helps clarify the layers of interaction in command-line usage. Getting Started with the Command Line To begin using the command line: Open your system's terminal emulator (e.g., Terminal on macOS, Command Prompt on Windows). Familiarize yourself with basic commands like ls (list files), cd (change directory), and pwd (print working directory). Experiment with command options and arguments to modify their behavior. Learn about your system's default shell and consider exploring alternatives that might better suit your needs. Customization and Productivity Tips Enhance your command-line experience with these tips: Customize your terminal's appearance with themes and color schemes. Learn keyboard shortcuts to navigate and edit commands more efficiently. Explore shell plugins and extensions to add functionality. Practice scripting to automate repetitive tasks. Conclusion The command line is a powerful tool that offers speed, versatility, and control over your computing environment. By understanding the roles of terminals and shells and learning to navigate the CLI effectively, you can significantly enhance your productivity and capabilities in various tech-related fields. Whether you're a beginner or looking to deepen your skills, mastering the command line is a valuable investment in your technical toolkit.","title":"Getting To Know The Command Line"},{"location":"getting-to-know-the-command-line/#getting-to-know-the-command-line","text":"","title":"Getting to Know the Command Line"},{"location":"getting-to-know-the-command-line/#introduction","text":"The command line interface (CLI) is a powerful tool that allows users to interact directly with their computer's operating system through text-based commands. Despite the prevalence of graphical user interfaces (GUIs), the command line remains an essential skill for developers, system administrators, and power users. This guide will introduce you to the world of command-line interfaces, explain their importance, and help you understand the key components involved.","title":"Introduction"},{"location":"getting-to-know-the-command-line/#what-is-the-command-line","text":"The command line, or CLI, is an environment where users can input text commands to perform specific tasks on a computer. Unlike GUIs, which use visual elements for interaction, the CLI relies entirely on textual input and output.","title":"What is the Command Line?"},{"location":"getting-to-know-the-command-line/#historical-context","text":"Originating in the 1960s, the command line predates graphical interfaces, offering an advanced method of computer interaction. This era of computing required users to engage directly with the system through typed commands, a significant evolution from punch cards and manual input methods.","title":"Historical Context"},{"location":"getting-to-know-the-command-line/#why-use-the-command-line","text":"Despite the user-friendliness of modern GUIs, the command line offers several compelling advantages: Speed : Execute commands and manage system resources quickly, bypassing graphical overhead. Versatility : Perform complex operations that might be cumbersome or impossible through a GUI. Automation : Write scripts to automate tasks, saving time and reducing human error. Remote Management : Access and control remote systems without needing a graphical interface. These benefits make the CLI an invaluable tool for various tech-related fields, including software development, system administration, and data science.","title":"Why Use the Command Line?"},{"location":"getting-to-know-the-command-line/#understanding-terminals-and-shells","text":"To effectively use the command line, it's crucial to understand two key components: terminals and shells.","title":"Understanding Terminals and Shells"},{"location":"getting-to-know-the-command-line/#terminal-emulators","text":"A terminal emulator is a software application that provides a graphical interface for interacting with the shell. It simulates the functionality of traditional hardware terminals within modern desktop environments. Popular terminal emulators include: Hyper : Cross-platform, built with web technologies, and highly extensible. iTerm2 : Feature-rich terminal for macOS with advanced customization options. PuTTY : Commonly used in Windows environments, supporting various network protocols.","title":"Terminal Emulators"},{"location":"getting-to-know-the-command-line/#shells","text":"The shell acts as an interpreter, executing user commands and managing communication between the user and the kernel. It provides a scripting language and executes system commands and scripts. Common shell types include: Bash (Bourne-Again SHell) : The default shell in many Linux distributions and older macOS versions. Zsh (Z Shell) : The default shell in newer macOS versions, known for its customizability. Fish (Friendly Interactive SHell) : Focused on user-friendliness with features like autosuggestions. Dash (Debian Almquist Shell) : Prioritizes efficiency and speed, often used for system-level scripting.","title":"Shells"},{"location":"getting-to-know-the-command-line/#key-differences-terminal-vs-shell","text":"While often mentioned together, terminals and shells serve distinct roles: Terminal : Provides the user interface for command input and system feedback. Shell : Interprets and executes the commands entered in the terminal. Understanding this distinction helps clarify the layers of interaction in command-line usage.","title":"Key Differences: Terminal vs. Shell"},{"location":"getting-to-know-the-command-line/#getting-started-with-the-command-line","text":"To begin using the command line: Open your system's terminal emulator (e.g., Terminal on macOS, Command Prompt on Windows). Familiarize yourself with basic commands like ls (list files), cd (change directory), and pwd (print working directory). Experiment with command options and arguments to modify their behavior. Learn about your system's default shell and consider exploring alternatives that might better suit your needs.","title":"Getting Started with the Command Line"},{"location":"getting-to-know-the-command-line/#customization-and-productivity-tips","text":"Enhance your command-line experience with these tips: Customize your terminal's appearance with themes and color schemes. Learn keyboard shortcuts to navigate and edit commands more efficiently. Explore shell plugins and extensions to add functionality. Practice scripting to automate repetitive tasks.","title":"Customization and Productivity Tips"},{"location":"getting-to-know-the-command-line/#conclusion","text":"The command line is a powerful tool that offers speed, versatility, and control over your computing environment. By understanding the roles of terminals and shells and learning to navigate the CLI effectively, you can significantly enhance your productivity and capabilities in various tech-related fields. Whether you're a beginner or looking to deepen your skills, mastering the command line is a valuable investment in your technical toolkit.","title":"Conclusion"},{"location":"git-and-github-voice-overview/","text":"Lessons Voice Overview Welcome to the voice overview of all the lessons. In this audio guide, we will cover the key topics and concepts that you'll be learning throughout the course. Listen to the Overview Your browser does not support the audio element.","title":"AI Voice Overview"},{"location":"git-and-github-voice-overview/#lessons-voice-overview","text":"Welcome to the voice overview of all the lessons. In this audio guide, we will cover the key topics and concepts that you'll be learning throughout the course.","title":"Lessons Voice Overview"},{"location":"git-and-github-voice-overview/#listen-to-the-overview","text":"Your browser does not support the audio element.","title":"Listen to the Overview"},{"location":"git-and-github/","text":"Git and GitHub (Terminal & UI) Overview Welcome to the \u201cGit and GitHub (Terminal & UI)\u201d guide! Whether you\u2019re a beginner or an experienced developer, this resource provides everything you need to master Git, GitHub, and AI-powered tools like GitHub Copilot. From essential workflows to advanced concepts, this guide will help you optimize your development process. What You Will Learn Getting Started with Git Install and configure Git on your system. Set up your user identity for version control. Create a local Git repository and commit code changes. Sync your local repository with GitHub for collaboration and secure cloud storage. GitHub Account Setup and Profile Optimization Create and set up your GitHub account. Optimize your GitHub profile with README files, pinned repositories, and SSH keys. Explore GitHub\u2019s collaborative features like Issues, Pull Requests, and Discussions to manage projects and engage with the developer community. Basic Git Operations Master fundamental Git commands: git init , git clone , git add , git commit , git push , and git pull . Learn to manage branches effectively for feature-based development. Use GitHub\u2019s web interface to visualize changes, open pull requests, and collaborate with developers. Intermediate and Advanced Git Concepts Learn branching and merging strategies for managing complex projects. Dive into rebasing, stashing, and conflict resolution. Use reflog and cherry-pick to recover lost commits or move changes between branches. Implement strategies for meaningful commit messages and maintaining a clean Git history. Collaboration on GitHub Fork repositories, open pull requests, and manage Issues and Projects for collaborative development. Set up Continuous Integration (CI) pipelines in GitHub to automatically run tests and maintain code quality. Use GitHub\u2019s security features like vulnerability alerts, branch protection, and Code Scanning to secure your projects. GitHub Copilot and AI-Driven Coding Learn about GitHub Copilot, an AI-powered tool for code completion. Integrate Copilot to generate code snippets and boost productivity. Explore GitHub Copilot CLI for automating tasks like project scaffolding and file generation. Practical Applications and Hands-On Practice Follow real-world examples to set up repositories, manage branches, and contribute to open-source projects. Hands-on labs reinforce concepts, allowing you to apply Git workflows in your own projects. Practice resolving merge conflicts, writing effective pull requests, and setting up GitHub Actions. Best Practices for Git and GitHub Maintain clean repositories using .gitignore , squashing commits, and writing clear commit messages. Explore workflows like Gitflow, feature branching, and trunk-based development, and choose the best approach for your projects. Learn guidelines for contributing to open-source projects, including issue tracking, code reviews, and community contribution. Why Learn Git and GitHub? Git and GitHub are indispensable tools in modern software development. Git allows you to track code changes, collaborate with others, and experiment without affecting the main project. GitHub builds on this by offering a platform for hosting repositories, remote collaboration, and integrating with tools for seamless version control. Mastering Git and GitHub will enhance your ability to manage code, collaborate effectively, and contribute to open-source projects. Leveraging AI-powered tools like GitHub Copilot will also streamline your workflow, keeping you ahead in the fast-paced tech industry. Who Is This Guide For? New developers looking to build a solid foundation in version control and collaborative development. Intermediate developers aiming to refine their skills with advanced Git techniques like conflict resolution, branching strategies, and GitHub Actions. Experienced developers seeking to optimize their workflow with AI-powered tools like GitHub Copilot and Copilot CLI. By the end of this guide, you\u2019ll confidently use Git for version control, collaborate on GitHub, and integrate AI-driven tools into your development process. Whether working on solo projects or large-scale collaborations, this guide will help you get the most out of Git, GitHub, and Copilot.","title":"Git And Github"},{"location":"git-and-github/#git-and-github-terminal-ui-overview","text":"Welcome to the \u201cGit and GitHub (Terminal & UI)\u201d guide! Whether you\u2019re a beginner or an experienced developer, this resource provides everything you need to master Git, GitHub, and AI-powered tools like GitHub Copilot. From essential workflows to advanced concepts, this guide will help you optimize your development process.","title":"Git and GitHub (Terminal & UI) Overview"},{"location":"git-and-github/#what-you-will-learn","text":"","title":"What You Will Learn"},{"location":"git-and-github/#getting-started-with-git","text":"Install and configure Git on your system. Set up your user identity for version control. Create a local Git repository and commit code changes. Sync your local repository with GitHub for collaboration and secure cloud storage.","title":"Getting Started with Git"},{"location":"git-and-github/#github-account-setup-and-profile-optimization","text":"Create and set up your GitHub account. Optimize your GitHub profile with README files, pinned repositories, and SSH keys. Explore GitHub\u2019s collaborative features like Issues, Pull Requests, and Discussions to manage projects and engage with the developer community.","title":"GitHub Account Setup and Profile Optimization"},{"location":"git-and-github/#basic-git-operations","text":"Master fundamental Git commands: git init , git clone , git add , git commit , git push , and git pull . Learn to manage branches effectively for feature-based development. Use GitHub\u2019s web interface to visualize changes, open pull requests, and collaborate with developers.","title":"Basic Git Operations"},{"location":"git-and-github/#intermediate-and-advanced-git-concepts","text":"Learn branching and merging strategies for managing complex projects. Dive into rebasing, stashing, and conflict resolution. Use reflog and cherry-pick to recover lost commits or move changes between branches. Implement strategies for meaningful commit messages and maintaining a clean Git history.","title":"Intermediate and Advanced Git Concepts"},{"location":"git-and-github/#collaboration-on-github","text":"Fork repositories, open pull requests, and manage Issues and Projects for collaborative development. Set up Continuous Integration (CI) pipelines in GitHub to automatically run tests and maintain code quality. Use GitHub\u2019s security features like vulnerability alerts, branch protection, and Code Scanning to secure your projects.","title":"Collaboration on GitHub"},{"location":"git-and-github/#github-copilot-and-ai-driven-coding","text":"Learn about GitHub Copilot, an AI-powered tool for code completion. Integrate Copilot to generate code snippets and boost productivity. Explore GitHub Copilot CLI for automating tasks like project scaffolding and file generation.","title":"GitHub Copilot and AI-Driven Coding"},{"location":"git-and-github/#practical-applications-and-hands-on-practice","text":"Follow real-world examples to set up repositories, manage branches, and contribute to open-source projects. Hands-on labs reinforce concepts, allowing you to apply Git workflows in your own projects. Practice resolving merge conflicts, writing effective pull requests, and setting up GitHub Actions.","title":"Practical Applications and Hands-On Practice"},{"location":"git-and-github/#best-practices-for-git-and-github","text":"Maintain clean repositories using .gitignore , squashing commits, and writing clear commit messages. Explore workflows like Gitflow, feature branching, and trunk-based development, and choose the best approach for your projects. Learn guidelines for contributing to open-source projects, including issue tracking, code reviews, and community contribution.","title":"Best Practices for Git and GitHub"},{"location":"git-and-github/#why-learn-git-and-github","text":"Git and GitHub are indispensable tools in modern software development. Git allows you to track code changes, collaborate with others, and experiment without affecting the main project. GitHub builds on this by offering a platform for hosting repositories, remote collaboration, and integrating with tools for seamless version control. Mastering Git and GitHub will enhance your ability to manage code, collaborate effectively, and contribute to open-source projects. Leveraging AI-powered tools like GitHub Copilot will also streamline your workflow, keeping you ahead in the fast-paced tech industry.","title":"Why Learn Git and GitHub?"},{"location":"git-and-github/#who-is-this-guide-for","text":"New developers looking to build a solid foundation in version control and collaborative development. Intermediate developers aiming to refine their skills with advanced Git techniques like conflict resolution, branching strategies, and GitHub Actions. Experienced developers seeking to optimize their workflow with AI-powered tools like GitHub Copilot and Copilot CLI. By the end of this guide, you\u2019ll confidently use Git for version control, collaborate on GitHub, and integrate AI-driven tools into your development process. Whether working on solo projects or large-scale collaborations, this guide will help you get the most out of Git, GitHub, and Copilot.","title":"Who Is This Guide For?"},{"location":"git-flow/","text":"Git Flow Overview Understanding Git Flow Introduction This guide will help you understand Git Flow, an advanced workflow that simplifies the management of complex projects. Git Flow introduces a branching model designed to keep your development process organized, from feature development to handling hotfixes and releases. Learning Outcomes By the end of this guide, you will: Understand what Git Flow is and how it improves project workflow. Implement a feature using Git Flow. Manage hotfixes and releases effectively. Use Git tags for version control and learn versioning best practices. What is Git Flow? (UI & Terminal) Definition Git Flow is a branching model that helps teams manage project development in a structured way. It ensures that work on new features, bug fixes, and releases is done in isolation and merged back into the main codebase when ready. Key Components Main Branch : The production-ready branch, always reflecting the latest release. Develop Branch : The integration branch where features are merged and tested before release. Feature Branches : Temporary branches for developing new features or functionalities. Release Branches : Used to prepare new releases, allowing final fixes and tests. Hotfix Branches : Created for critical patches in the production branch. Implementing a Feature using Git Flow (Terminal) Workflow for Features Git Flow makes it easy to develop new features in isolation before integrating them into the main codebase. Checkout the develop branch: bash git checkout develop Create a new feature branch: bash git checkout -b feature/new-feature Develop the feature: Add your code and commit regularly: bash git add . git commit -m \"Start implementing new feature\" Merge the feature back into develop: Once the feature is complete: bash git checkout develop git merge feature/new-feature Delete the feature branch (optional): Clean up by deleting the feature branch: bash git branch -d feature/new-feature Hotfixes and Releases (Terminal) Hotfix Workflow Hotfixes are quick patches applied directly to the production code. Git Flow makes it easy to apply fixes and keep both the main and develop branches updated. Create a hotfix branch from main: bash git checkout -b hotfix/urgent-fix main Apply the fix and commit it: bash git add . git commit -m \"Apply urgent fix for production\" Merge the fix back into main and develop: bash git checkout main git merge hotfix/urgent-fix git checkout develop git merge hotfix/urgent-fix Release Workflow Releases prepare the develop branch for production. Final bug fixes, versioning, and testing occur on the release branch before merging into main. Create a release branch from develop: bash git checkout -b release/v1.0 develop Perform final changes and commit: bash git add . git commit -m \"Prepare for release v1.0\" Merge the release into main and tag the release: bash git checkout main git merge release/v1.0 git tag -a v1.0 -m \"Release version 1.0\" Merge the release back into develop (to ensure any last-minute fixes are included): bash git checkout develop git merge main Git Tags and Versioning (Terminal) Using Git Tags Tags allow you to mark important points in your project's history, such as a new release. Tags can be lightweight (simple references) or annotated (contain metadata). Create an annotated tag for a release: bash git tag -a v1.0 -m \"Release version 1.0\" Push the tags to your remote repository: bash git push origin --tags Versioning Practices When tagging releases, many developers follow semantic versioning, which uses the format MAJOR.MINOR.PATCH. For example: MAJOR: Increment for incompatible changes (e.g., v2.0.0). MINOR: Increment for new backward-compatible functionality (e.g., v1.1.0). PATCH: Increment for backward-compatible bug fixes (e.g., v1.0.1). Summary With Git Flow, you've learned how to manage features, releases, and hotfixes in a structured, organized way. You also gained an understanding of tagging releases and versioning best practices to keep your projects clean and maintainable. Keep practicing these workflows, and you'll streamline your project management processes significantly!","title":"Git Flow"},{"location":"git-flow/#git-flow-overview","text":"","title":"Git Flow Overview"},{"location":"git-flow/#understanding-git-flow","text":"","title":"Understanding Git Flow"},{"location":"git-flow/#introduction","text":"This guide will help you understand Git Flow, an advanced workflow that simplifies the management of complex projects. Git Flow introduces a branching model designed to keep your development process organized, from feature development to handling hotfixes and releases.","title":"Introduction"},{"location":"git-flow/#learning-outcomes","text":"By the end of this guide, you will: Understand what Git Flow is and how it improves project workflow. Implement a feature using Git Flow. Manage hotfixes and releases effectively. Use Git tags for version control and learn versioning best practices.","title":"Learning Outcomes"},{"location":"git-flow/#what-is-git-flow-ui-terminal","text":"","title":"What is Git Flow? (UI & Terminal)"},{"location":"git-flow/#definition","text":"Git Flow is a branching model that helps teams manage project development in a structured way. It ensures that work on new features, bug fixes, and releases is done in isolation and merged back into the main codebase when ready.","title":"Definition"},{"location":"git-flow/#key-components","text":"Main Branch : The production-ready branch, always reflecting the latest release. Develop Branch : The integration branch where features are merged and tested before release. Feature Branches : Temporary branches for developing new features or functionalities. Release Branches : Used to prepare new releases, allowing final fixes and tests. Hotfix Branches : Created for critical patches in the production branch.","title":"Key Components"},{"location":"git-flow/#implementing-a-feature-using-git-flow-terminal","text":"","title":"Implementing a Feature using Git Flow (Terminal)"},{"location":"git-flow/#workflow-for-features","text":"Git Flow makes it easy to develop new features in isolation before integrating them into the main codebase. Checkout the develop branch: bash git checkout develop Create a new feature branch: bash git checkout -b feature/new-feature Develop the feature: Add your code and commit regularly: bash git add . git commit -m \"Start implementing new feature\" Merge the feature back into develop: Once the feature is complete: bash git checkout develop git merge feature/new-feature Delete the feature branch (optional): Clean up by deleting the feature branch: bash git branch -d feature/new-feature","title":"Workflow for Features"},{"location":"git-flow/#hotfixes-and-releases-terminal","text":"","title":"Hotfixes and Releases (Terminal)"},{"location":"git-flow/#hotfix-workflow","text":"Hotfixes are quick patches applied directly to the production code. Git Flow makes it easy to apply fixes and keep both the main and develop branches updated. Create a hotfix branch from main: bash git checkout -b hotfix/urgent-fix main Apply the fix and commit it: bash git add . git commit -m \"Apply urgent fix for production\" Merge the fix back into main and develop: bash git checkout main git merge hotfix/urgent-fix git checkout develop git merge hotfix/urgent-fix","title":"Hotfix Workflow"},{"location":"git-flow/#release-workflow","text":"Releases prepare the develop branch for production. Final bug fixes, versioning, and testing occur on the release branch before merging into main. Create a release branch from develop: bash git checkout -b release/v1.0 develop Perform final changes and commit: bash git add . git commit -m \"Prepare for release v1.0\" Merge the release into main and tag the release: bash git checkout main git merge release/v1.0 git tag -a v1.0 -m \"Release version 1.0\" Merge the release back into develop (to ensure any last-minute fixes are included): bash git checkout develop git merge main","title":"Release Workflow"},{"location":"git-flow/#git-tags-and-versioning-terminal","text":"","title":"Git Tags and Versioning (Terminal)"},{"location":"git-flow/#using-git-tags","text":"Tags allow you to mark important points in your project's history, such as a new release. Tags can be lightweight (simple references) or annotated (contain metadata). Create an annotated tag for a release: bash git tag -a v1.0 -m \"Release version 1.0\" Push the tags to your remote repository: bash git push origin --tags","title":"Using Git Tags"},{"location":"git-flow/#versioning-practices","text":"When tagging releases, many developers follow semantic versioning, which uses the format MAJOR.MINOR.PATCH. For example: MAJOR: Increment for incompatible changes (e.g., v2.0.0). MINOR: Increment for new backward-compatible functionality (e.g., v1.1.0). PATCH: Increment for backward-compatible bug fixes (e.g., v1.0.1).","title":"Versioning Practices"},{"location":"git-flow/#summary","text":"With Git Flow, you've learned how to manage features, releases, and hotfixes in a structured, organized way. You also gained an understanding of tagging releases and versioning best practices to keep your projects clean and maintainable. Keep practicing these workflows, and you'll streamline your project management processes significantly!","title":"Summary"},{"location":"github-cli/","text":"GitHub CLI Overview Introduction to GitHub CLI Introduction This guide covers the essential aspects of GitHub CLI (Command Line Interface), a powerful tool that allows you to interact with GitHub repositories directly from your terminal. Whether you're creating pull requests, managing issues, or navigating repositories, GitHub CLI helps streamline your workflow. Learning Outcomes By the end of this guide, you will: Install GitHub CLI Execute basic GitHub CLI commands Create and manage aliases for frequently used operations Authenticate your GitHub account via the CLI Installing GitHub CLI (Terminal) Installation Steps For macOS users: brew install gh For Ubuntu users: sudo apt install gh Verification To ensure the installation was successful, check the installed version: gh --version Basic GitHub CLI Commands (Terminal) Key Commands View repository details: gh repo view Check pull request status: gh pr status List repository issues: gh issue list Creating Aliases in GitHub CLI (Terminal) Aliases let you create shortcuts for frequently used commands to save time. For example, to create an alias for viewing pull requests: gh alias set pr-list 'pr list' Now, instead of typing gh pr list , you can simply type gh pr-list . Authentication with GitHub CLI (Terminal) To authenticate GitHub CLI with your GitHub account, use the following command: gh auth login Follow the on-screen prompts to complete the authentication process. Managing Repositories with GitHub CLI Learning Outcomes Create and clone repositories using GitHub CLI Fork repositories and create pull requests Manage issues within a repository Clean up repositories efficiently Creating and Cloning Repositories (Terminal) To create a new repository: gh repo create To clone an existing repository: gh repo clone Forking and Making Pull Requests (Terminal) Fork a repository to your account: gh repo fork Create a pull request from your branch: gh pr create Follow the interactive prompts to provide a title, description, and reviewers for your pull request. Issue Management (Terminal) To create a new issue: gh issue create List all open issues: gh issue list Close an issue by its number: gh issue close Cleaning Up Repositories (Terminal) To delete a repository from GitHub: gh repo delete Navigating GitHub with GitHub CLI Learning Outcomes Manage issues and pull requests efficiently Work with GitHub Gists and Actions Navigate between repositories Use search filters to find specific repositories or issues Managing Issues and Pull Requests (Terminal) To view the status of all open issues: gh issue status To check the status of pull requests: gh pr status Working with Gists and Actions (Terminal) To create a GitHub Gist from a file: gh gist create To view the list of GitHub Actions workflows: gh run list Navigating Repositories (Terminal) To open the main page of a repository in your browser: gh repo view --web This command opens the repository's webpage, making it easier to review and interact with the project. Searching and Filtering (Terminal) To search for repositories owned by a specific user or organization: gh repo list --limit To filter issues based on specific labels: gh issue list --label \"bug\" By mastering GitHub CLI, you can significantly boost your productivity by performing GitHub operations directly from the terminal. Keep practicing these commands and use GitHub CLI as part of your development workflow for faster and more efficient project management!","title":"Github CLI"},{"location":"github-cli/#github-cli-overview","text":"","title":"GitHub CLI Overview"},{"location":"github-cli/#introduction-to-github-cli","text":"","title":"Introduction to GitHub CLI"},{"location":"github-cli/#introduction","text":"This guide covers the essential aspects of GitHub CLI (Command Line Interface), a powerful tool that allows you to interact with GitHub repositories directly from your terminal. Whether you're creating pull requests, managing issues, or navigating repositories, GitHub CLI helps streamline your workflow.","title":"Introduction"},{"location":"github-cli/#learning-outcomes","text":"By the end of this guide, you will: Install GitHub CLI Execute basic GitHub CLI commands Create and manage aliases for frequently used operations Authenticate your GitHub account via the CLI","title":"Learning Outcomes"},{"location":"github-cli/#installing-github-cli-terminal","text":"","title":"Installing GitHub CLI (Terminal)"},{"location":"github-cli/#installation-steps","text":"For macOS users: brew install gh For Ubuntu users: sudo apt install gh","title":"Installation Steps"},{"location":"github-cli/#verification","text":"To ensure the installation was successful, check the installed version: gh --version","title":"Verification"},{"location":"github-cli/#basic-github-cli-commands-terminal","text":"","title":"Basic GitHub CLI Commands (Terminal)"},{"location":"github-cli/#key-commands","text":"View repository details: gh repo view Check pull request status: gh pr status List repository issues: gh issue list","title":"Key Commands"},{"location":"github-cli/#creating-aliases-in-github-cli-terminal","text":"Aliases let you create shortcuts for frequently used commands to save time. For example, to create an alias for viewing pull requests: gh alias set pr-list 'pr list' Now, instead of typing gh pr list , you can simply type gh pr-list .","title":"Creating Aliases in GitHub CLI (Terminal)"},{"location":"github-cli/#authentication-with-github-cli-terminal","text":"To authenticate GitHub CLI with your GitHub account, use the following command: gh auth login Follow the on-screen prompts to complete the authentication process.","title":"Authentication with GitHub CLI (Terminal)"},{"location":"github-cli/#managing-repositories-with-github-cli","text":"","title":"Managing Repositories with GitHub CLI"},{"location":"github-cli/#learning-outcomes_1","text":"Create and clone repositories using GitHub CLI Fork repositories and create pull requests Manage issues within a repository Clean up repositories efficiently","title":"Learning Outcomes"},{"location":"github-cli/#creating-and-cloning-repositories-terminal","text":"To create a new repository: gh repo create To clone an existing repository: gh repo clone ","title":"Creating and Cloning Repositories (Terminal)"},{"location":"github-cli/#forking-and-making-pull-requests-terminal","text":"Fork a repository to your account: gh repo fork Create a pull request from your branch: gh pr create Follow the interactive prompts to provide a title, description, and reviewers for your pull request.","title":"Forking and Making Pull Requests (Terminal)"},{"location":"github-cli/#issue-management-terminal","text":"To create a new issue: gh issue create List all open issues: gh issue list Close an issue by its number: gh issue close ","title":"Issue Management (Terminal)"},{"location":"github-cli/#cleaning-up-repositories-terminal","text":"To delete a repository from GitHub: gh repo delete ","title":"Cleaning Up Repositories (Terminal)"},{"location":"github-cli/#navigating-github-with-github-cli","text":"","title":"Navigating GitHub with GitHub CLI"},{"location":"github-cli/#learning-outcomes_2","text":"Manage issues and pull requests efficiently Work with GitHub Gists and Actions Navigate between repositories Use search filters to find specific repositories or issues","title":"Learning Outcomes"},{"location":"github-cli/#managing-issues-and-pull-requests-terminal","text":"To view the status of all open issues: gh issue status To check the status of pull requests: gh pr status","title":"Managing Issues and Pull Requests (Terminal)"},{"location":"github-cli/#working-with-gists-and-actions-terminal","text":"To create a GitHub Gist from a file: gh gist create To view the list of GitHub Actions workflows: gh run list","title":"Working with Gists and Actions (Terminal)"},{"location":"github-cli/#navigating-repositories-terminal","text":"To open the main page of a repository in your browser: gh repo view --web This command opens the repository's webpage, making it easier to review and interact with the project.","title":"Navigating Repositories (Terminal)"},{"location":"github-cli/#searching-and-filtering-terminal","text":"To search for repositories owned by a specific user or organization: gh repo list --limit To filter issues based on specific labels: gh issue list --label \"bug\" By mastering GitHub CLI, you can significantly boost your productivity by performing GitHub operations directly from the terminal. Keep practicing these commands and use GitHub CLI as part of your development workflow for faster and more efficient project management!","title":"Searching and Filtering (Terminal)"},{"location":"intro-to-python/","text":"Vets Who Code - Python Fundamentals \ud83c\udf96\ufe0f Mission Briefing Welcome to the Python track of Vets Who Code! Like any good military operation, we'll break this down into clear, manageable objectives. Your military experience has already equipped you with the discipline and problem-solving skills needed to excel in programming. Phase 1: Establishing Base (Setup) Setting Up Your FOB (Forward Operating Base) Download Python from python.org (like requisitioning new equipment) Install with \"Add Python to PATH\" checked (establishing your supply lines) Verify installation in terminal: python --version First Boots on the Ground # Your first line of code is like your first patrol print(\"Vets Who Code: Reporting for Duty!\") Phase 2: Basic Training Intelligence Types (Data Types) # Personnel Count (Integer) squad_size = 12 # Supply Levels (Float) fuel_level = 85.5 # Call Signs (String) unit_name = \"Alpha\" status = 'Oscar Mike' # 'On Mission' # Mission Status (Boolean) is_deployed = True mission_complete = False # Intel Not Available (None) pending_orders = None Field Communications (Basic Operations) # Tactical Math available_transport = 5 required_transport = 3 total_transport = available_transport + required_transport remaining_transport = available_transport - required_transport # Unit Designations battalion = \"2nd\" division = \"Infantry\" unit = battalion + \" \" + division # 2nd Infantry # Field Reports print(f\"Unit Strength: {squad_size}\") print(f\"Unit Status: {status}\") Phase 3: Combat Operations (Control Flow) Mission Planning (If Statements) def check_readiness(troops, vehicles): if troops >= 10 and vehicles >= 2: return \"Unit is Combat Ready\" elif troops >= 5: return \"Unit is Patrol Ready\" else: return \"Unit Needs Reinforcement\" # Example Usage unit_status = check_readiness(8, 1) print(unit_status) Patrol Patterns (Loops) # Perimeter Check (For Loop) sectors = [\"North\", \"East\", \"South\", \"West\"] for sector in sectors: print(f\"Sector {sector} is secure\") # Watch Rotation (While Loop) watch_hours = 4 current_hour = 0 while current_hour < watch_hours: print(f\"Hour {current_hour + 1} of watch\") current_hour += 1 Phase 4: Equipment and Logistics (Data Structures) Equipment Roster (Lists) # Basic gear list gear = [\"rifle\", \"nods\", \"radio\", \"ruck\"] # Adding gear gear.append(\"ifak\") # Adds to end gear.insert(0, \"weapon\") # Adds at position # Checking gear print(f\"First item: {gear[0]}\") print(f\"Last item: {gear[-1]}\") # Removing gear gear.remove(\"radio\") # Removes specific item last_item = gear.pop() # Removes and returns last item Mission Intel (Dictionaries) # Mission details mission = { \"type\": \"Training\", \"location\": \"Virtual FOB\", \"duration\": 14, \"unit\": \"VWC Python Platoon\" } # Accessing intel print(f\"Mission Type: {mission['type']}\") print(f\"Location: {mission.get('location')}\") # Updating intel mission[\"status\"] = \"In Progress\" mission[\"duration\"] = 21 Phase 5: Field Exercise Here's a practical exercise combining the concepts - a Military Awards Database: def awards_database(): \"\"\" Military Awards Reference System \"\"\" awards = { \"1\": { \"name\": \"Purple Heart\", \"criteria\": \"Wounded in combat\", \"precedence\": \"High\", \"branch\": \"All services\" }, \"2\": { \"name\": \"Combat Action Ribbon\", \"criteria\": \"Engaged in combat\", \"precedence\": \"Medium\", \"branch\": \"Navy/Marines\" } } while True: print(\"\\nVWC Awards Database\") print(\"------------------\") for key, award in awards.items(): print(f\"{key}: {award['name']}\") print(\"3: Exit System\") selection = input(\"\\nEnter award number: \") if selection == \"3\": print(\"Database Secured!\") break elif selection in awards: award = awards[selection] print(f\"\\nName: {award['name']}\") print(f\"Criteria: {award['criteria']}\") print(f\"Precedence: {award['precedence']}\") print(f\"Branch: {award['branch']}\") else: print(\"Invalid selection, try again\") if __name__ == \"__main__\": awards_database() Next Mission Parameters Coming Up Next: Functions (Battle Drills) Error Handling (Combat Contingencies) File Operations (Mission Logs) Classes (Unit Organization) Modules (Support Elements) Core Values to Remember: Attention to Detail (Clean Code) Adapt and Overcome (Problem Solving) Leave No One Behind (Help Others Learn) Mission First (Working Code) Ready to move to advanced operations? Remember: Stay motivated Keep practicing Debug with discipline Learn from each mission \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Introduction To Python"},{"location":"intro-to-python/#vets-who-code-python-fundamentals","text":"","title":"Vets Who Code - Python Fundamentals \ud83c\udf96\ufe0f"},{"location":"intro-to-python/#mission-briefing","text":"Welcome to the Python track of Vets Who Code! Like any good military operation, we'll break this down into clear, manageable objectives. Your military experience has already equipped you with the discipline and problem-solving skills needed to excel in programming.","title":"Mission Briefing"},{"location":"intro-to-python/#phase-1-establishing-base-setup","text":"","title":"Phase 1: Establishing Base (Setup)"},{"location":"intro-to-python/#setting-up-your-fob-forward-operating-base","text":"Download Python from python.org (like requisitioning new equipment) Install with \"Add Python to PATH\" checked (establishing your supply lines) Verify installation in terminal: python --version","title":"Setting Up Your FOB (Forward Operating Base)"},{"location":"intro-to-python/#first-boots-on-the-ground","text":"# Your first line of code is like your first patrol print(\"Vets Who Code: Reporting for Duty!\")","title":"First Boots on the Ground"},{"location":"intro-to-python/#phase-2-basic-training","text":"","title":"Phase 2: Basic Training"},{"location":"intro-to-python/#intelligence-types-data-types","text":"# Personnel Count (Integer) squad_size = 12 # Supply Levels (Float) fuel_level = 85.5 # Call Signs (String) unit_name = \"Alpha\" status = 'Oscar Mike' # 'On Mission' # Mission Status (Boolean) is_deployed = True mission_complete = False # Intel Not Available (None) pending_orders = None","title":"Intelligence Types (Data Types)"},{"location":"intro-to-python/#field-communications-basic-operations","text":"# Tactical Math available_transport = 5 required_transport = 3 total_transport = available_transport + required_transport remaining_transport = available_transport - required_transport # Unit Designations battalion = \"2nd\" division = \"Infantry\" unit = battalion + \" \" + division # 2nd Infantry # Field Reports print(f\"Unit Strength: {squad_size}\") print(f\"Unit Status: {status}\")","title":"Field Communications (Basic Operations)"},{"location":"intro-to-python/#phase-3-combat-operations-control-flow","text":"","title":"Phase 3: Combat Operations (Control Flow)"},{"location":"intro-to-python/#mission-planning-if-statements","text":"def check_readiness(troops, vehicles): if troops >= 10 and vehicles >= 2: return \"Unit is Combat Ready\" elif troops >= 5: return \"Unit is Patrol Ready\" else: return \"Unit Needs Reinforcement\" # Example Usage unit_status = check_readiness(8, 1) print(unit_status)","title":"Mission Planning (If Statements)"},{"location":"intro-to-python/#patrol-patterns-loops","text":"# Perimeter Check (For Loop) sectors = [\"North\", \"East\", \"South\", \"West\"] for sector in sectors: print(f\"Sector {sector} is secure\") # Watch Rotation (While Loop) watch_hours = 4 current_hour = 0 while current_hour < watch_hours: print(f\"Hour {current_hour + 1} of watch\") current_hour += 1","title":"Patrol Patterns (Loops)"},{"location":"intro-to-python/#phase-4-equipment-and-logistics-data-structures","text":"","title":"Phase 4: Equipment and Logistics (Data Structures)"},{"location":"intro-to-python/#equipment-roster-lists","text":"# Basic gear list gear = [\"rifle\", \"nods\", \"radio\", \"ruck\"] # Adding gear gear.append(\"ifak\") # Adds to end gear.insert(0, \"weapon\") # Adds at position # Checking gear print(f\"First item: {gear[0]}\") print(f\"Last item: {gear[-1]}\") # Removing gear gear.remove(\"radio\") # Removes specific item last_item = gear.pop() # Removes and returns last item","title":"Equipment Roster (Lists)"},{"location":"intro-to-python/#mission-intel-dictionaries","text":"# Mission details mission = { \"type\": \"Training\", \"location\": \"Virtual FOB\", \"duration\": 14, \"unit\": \"VWC Python Platoon\" } # Accessing intel print(f\"Mission Type: {mission['type']}\") print(f\"Location: {mission.get('location')}\") # Updating intel mission[\"status\"] = \"In Progress\" mission[\"duration\"] = 21","title":"Mission Intel (Dictionaries)"},{"location":"intro-to-python/#phase-5-field-exercise","text":"Here's a practical exercise combining the concepts - a Military Awards Database: def awards_database(): \"\"\" Military Awards Reference System \"\"\" awards = { \"1\": { \"name\": \"Purple Heart\", \"criteria\": \"Wounded in combat\", \"precedence\": \"High\", \"branch\": \"All services\" }, \"2\": { \"name\": \"Combat Action Ribbon\", \"criteria\": \"Engaged in combat\", \"precedence\": \"Medium\", \"branch\": \"Navy/Marines\" } } while True: print(\"\\nVWC Awards Database\") print(\"------------------\") for key, award in awards.items(): print(f\"{key}: {award['name']}\") print(\"3: Exit System\") selection = input(\"\\nEnter award number: \") if selection == \"3\": print(\"Database Secured!\") break elif selection in awards: award = awards[selection] print(f\"\\nName: {award['name']}\") print(f\"Criteria: {award['criteria']}\") print(f\"Precedence: {award['precedence']}\") print(f\"Branch: {award['branch']}\") else: print(\"Invalid selection, try again\") if __name__ == \"__main__\": awards_database()","title":"Phase 5: Field Exercise"},{"location":"intro-to-python/#next-mission-parameters","text":"","title":"Next Mission Parameters"},{"location":"intro-to-python/#coming-up-next","text":"Functions (Battle Drills) Error Handling (Combat Contingencies) File Operations (Mission Logs) Classes (Unit Organization) Modules (Support Elements)","title":"Coming Up Next:"},{"location":"intro-to-python/#core-values-to-remember","text":"Attention to Detail (Clean Code) Adapt and Overcome (Problem Solving) Leave No One Behind (Help Others Learn) Mission First (Working Code) Ready to move to advanced operations? Remember: Stay motivated Keep practicing Debug with discipline Learn from each mission \ud83c\uddfa\ud83c\uddf8 #VetsWhoCode","title":"Core Values to Remember:"},{"location":"software-design-patterns/","text":"VetsWhoCode: Strategic Design Patterns \ud83c\udf96\ufe0f \"Good architecture, like good leadership, creates a foundation for success.\" - VetsWhoCode Overview This field manual covers essential software design patterns through a military lens. Each pattern is presented with tactical analogies and practical Python implementations. Table of Contents Creational Patterns Structural Patterns Behavioral Patterns Creational Patterns Military Context Like establishing different types of military installations, creational patterns define how we set up and organize our software assets. Each pattern serves a specific strategic purpose. 1. Singleton Pattern - Command Center class CommandCenter: \"\"\" Mission: Ensure only one command center exists for coordinating operations. Tactical Application: - Central command and control - Unified communications hub - Resource management center \"\"\" _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.operations_log = [] cls._instance.active_units = {} return cls._instance def log_operation(self, operation): self.operations_log.append(operation) def register_unit(self, unit_id, unit_type): self.active_units[unit_id] = unit_type # Field Test command1 = CommandCenter() command2 = CommandCenter() print(f\"Same command center: {command1 is command2}\") # True 2. Factory Method - Equipment Factory from abc import ABC, abstractmethod class Equipment(ABC): @abstractmethod def operate(self): pass class Rifle(Equipment): def operate(self): return \"Rifle ready for operation\" class Radio(Equipment): def operate(self): return \"Radio established comms\" class EquipmentFactory: \"\"\" Mission: Standardize equipment creation process. Tactical Application: - Standardized equipment procurement - Quality control - Inventory management \"\"\" @staticmethod def create_equipment(equipment_type): if equipment_type == \"rifle\": return Rifle() elif equipment_type == \"radio\": return Radio() raise ValueError(f\"Unknown equipment type: {equipment_type}\") # Field Test factory = EquipmentFactory() rifle = factory.create_equipment(\"rifle\") radio = factory.create_equipment(\"radio\") 3. Builder Pattern - Mission Planner class MissionPlan: def __init__(self): self.objectives = [] self.resources = [] self.timeline = None self.extraction_plan = None class MissionBuilder: \"\"\" Mission: Construct complex mission plans step by step. Tactical Application: - Detailed mission planning - Resource allocation - Contingency planning \"\"\" def __init__(self): self.mission = MissionPlan() def add_objective(self, objective): self.mission.objectives.append(objective) return self def add_resource(self, resource): self.mission.resources.append(resource) return self def set_timeline(self, timeline): self.mission.timeline = timeline return self def set_extraction(self, extraction_plan): self.mission.extraction_plan = extraction_plan return self def build(self): return self.mission # Field Test mission = (MissionBuilder() .add_objective(\"Secure perimeter\") .add_resource(\"Alpha Team\") .set_timeline(\"H-Hour to H+6\") .set_extraction(\"Helo pickup at LZ Bravo\") .build()) Structural Patterns Military Context Like organizing units and establishing command relationships, structural patterns define how different components of the system work together. 1. Adapter Pattern - Communications Interface class ModernRadio: def transmit_digital(self, message): return f\"Digital transmission: {message}\" class LegacyRadio: def send_analog(self, message): return f\"Analog signal: {message}\" class RadioAdapter: \"\"\" Mission: Enable communication between modern and legacy systems. Tactical Application: - Cross-platform communications - Legacy system integration - Interoperability assurance \"\"\" def __init__(self, legacy_radio): self.legacy_radio = legacy_radio def transmit_digital(self, message): analog_message = self.convert_to_analog(message) return self.legacy_radio.send_analog(analog_message) def convert_to_analog(self, message): return f\"Converted: {message}\" # Field Test modern = ModernRadio() legacy = LegacyRadio() adapter = RadioAdapter(legacy) print(adapter.transmit_digital(\"Alpha moving to objective\")) 2. Decorator Pattern - Equipment Modifications from abc import ABC, abstractmethod class Weapon(ABC): @abstractmethod def operate(self): pass class BaseRifle(Weapon): def operate(self): return \"Standard rifle operations\" class WeaponModification(Weapon): \"\"\" Mission: Add modular capabilities to equipment. Tactical Application: - Equipment customization - Mission-specific modifications - Capability enhancement \"\"\" def __init__(self, weapon): self._weapon = weapon class ScopeDecorator(WeaponModification): def operate(self): return f\"{self._weapon.operate()} + Enhanced targeting\" class SuppressorDecorator(WeaponModification): def operate(self): return f\"{self._weapon.operate()} + Noise reduction\" # Field Test rifle = BaseRifle() scoped_rifle = ScopeDecorator(rifle) tactical_rifle = SuppressorDecorator(scoped_rifle) print(tactical_rifle.operate()) Behavioral Patterns Military Context Like standard operating procedures (SOPs), behavioral patterns define how different components communicate and operate together. 1. Observer Pattern - Alert System from abc import ABC, abstractmethod class AlertSystem(ABC): @abstractmethod def update(self, message): pass class Unit(AlertSystem): def __init__(self, name): self.name = name def update(self, message): print(f\"{self.name} received alert: {message}\") class CommandPost: \"\"\" Mission: Coordinate and disseminate information to multiple units. Tactical Application: - Alert dissemination - Unit coordination - Information broadcasting \"\"\" def __init__(self): self._units = [] def attach(self, unit): self._units.append(unit) def detach(self, unit): self._units.remove(unit) def notify(self, message): for unit in self._units: unit.update(message) # Field Test command_post = CommandPost() alpha_team = Unit(\"Alpha Team\") bravo_team = Unit(\"Bravo Team\") command_post.attach(alpha_team) command_post.attach(bravo_team) command_post.notify(\"Enemy contact at grid 123456\") 2. Strategy Pattern - Mission Tactics from abc import ABC, abstractmethod class TacticalApproach(ABC): @abstractmethod def execute(self): pass class StealthApproach(TacticalApproach): def execute(self): return \"Executing silent approach\" class DirectAssault(TacticalApproach): def execute(self): return \"Executing frontal assault\" class MissionExecutor: \"\"\" Mission: Adapt tactical approach based on situation. Tactical Application: - Flexible mission execution - Adaptable tactics - Situational response \"\"\" def __init__(self, strategy: TacticalApproach): self._strategy = strategy def change_strategy(self, strategy: TacticalApproach): self._strategy = strategy def execute_mission(self): return self._strategy.execute() # Field Test mission = MissionExecutor(StealthApproach()) print(mission.execute_mission()) mission.change_strategy(DirectAssault()) print(mission.execute_mission()) Field Notes Design patterns are like battle-tested strategies - use them wisely Each pattern solves specific tactical problems Remember: Good architecture enables mission success \"Building robust systems with military precision\" - VetsWhoCode","title":"Software Engineering Design Patterns"},{"location":"software-design-patterns/#vetswhocode-strategic-design-patterns","text":"\"Good architecture, like good leadership, creates a foundation for success.\" - VetsWhoCode","title":"VetsWhoCode: Strategic Design Patterns \ud83c\udf96\ufe0f"},{"location":"software-design-patterns/#overview","text":"This field manual covers essential software design patterns through a military lens. Each pattern is presented with tactical analogies and practical Python implementations.","title":"Overview"},{"location":"software-design-patterns/#table-of-contents","text":"Creational Patterns Structural Patterns Behavioral Patterns","title":"Table of Contents"},{"location":"software-design-patterns/#creational-patterns","text":"","title":"Creational Patterns"},{"location":"software-design-patterns/#military-context","text":"Like establishing different types of military installations, creational patterns define how we set up and organize our software assets. Each pattern serves a specific strategic purpose.","title":"Military Context"},{"location":"software-design-patterns/#1-singleton-pattern-command-center","text":"class CommandCenter: \"\"\" Mission: Ensure only one command center exists for coordinating operations. Tactical Application: - Central command and control - Unified communications hub - Resource management center \"\"\" _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.operations_log = [] cls._instance.active_units = {} return cls._instance def log_operation(self, operation): self.operations_log.append(operation) def register_unit(self, unit_id, unit_type): self.active_units[unit_id] = unit_type # Field Test command1 = CommandCenter() command2 = CommandCenter() print(f\"Same command center: {command1 is command2}\") # True","title":"1. Singleton Pattern - Command Center"},{"location":"software-design-patterns/#2-factory-method-equipment-factory","text":"from abc import ABC, abstractmethod class Equipment(ABC): @abstractmethod def operate(self): pass class Rifle(Equipment): def operate(self): return \"Rifle ready for operation\" class Radio(Equipment): def operate(self): return \"Radio established comms\" class EquipmentFactory: \"\"\" Mission: Standardize equipment creation process. Tactical Application: - Standardized equipment procurement - Quality control - Inventory management \"\"\" @staticmethod def create_equipment(equipment_type): if equipment_type == \"rifle\": return Rifle() elif equipment_type == \"radio\": return Radio() raise ValueError(f\"Unknown equipment type: {equipment_type}\") # Field Test factory = EquipmentFactory() rifle = factory.create_equipment(\"rifle\") radio = factory.create_equipment(\"radio\")","title":"2. Factory Method - Equipment Factory"},{"location":"software-design-patterns/#3-builder-pattern-mission-planner","text":"class MissionPlan: def __init__(self): self.objectives = [] self.resources = [] self.timeline = None self.extraction_plan = None class MissionBuilder: \"\"\" Mission: Construct complex mission plans step by step. Tactical Application: - Detailed mission planning - Resource allocation - Contingency planning \"\"\" def __init__(self): self.mission = MissionPlan() def add_objective(self, objective): self.mission.objectives.append(objective) return self def add_resource(self, resource): self.mission.resources.append(resource) return self def set_timeline(self, timeline): self.mission.timeline = timeline return self def set_extraction(self, extraction_plan): self.mission.extraction_plan = extraction_plan return self def build(self): return self.mission # Field Test mission = (MissionBuilder() .add_objective(\"Secure perimeter\") .add_resource(\"Alpha Team\") .set_timeline(\"H-Hour to H+6\") .set_extraction(\"Helo pickup at LZ Bravo\") .build())","title":"3. Builder Pattern - Mission Planner"},{"location":"software-design-patterns/#structural-patterns","text":"","title":"Structural Patterns"},{"location":"software-design-patterns/#military-context_1","text":"Like organizing units and establishing command relationships, structural patterns define how different components of the system work together.","title":"Military Context"},{"location":"software-design-patterns/#1-adapter-pattern-communications-interface","text":"class ModernRadio: def transmit_digital(self, message): return f\"Digital transmission: {message}\" class LegacyRadio: def send_analog(self, message): return f\"Analog signal: {message}\" class RadioAdapter: \"\"\" Mission: Enable communication between modern and legacy systems. Tactical Application: - Cross-platform communications - Legacy system integration - Interoperability assurance \"\"\" def __init__(self, legacy_radio): self.legacy_radio = legacy_radio def transmit_digital(self, message): analog_message = self.convert_to_analog(message) return self.legacy_radio.send_analog(analog_message) def convert_to_analog(self, message): return f\"Converted: {message}\" # Field Test modern = ModernRadio() legacy = LegacyRadio() adapter = RadioAdapter(legacy) print(adapter.transmit_digital(\"Alpha moving to objective\"))","title":"1. Adapter Pattern - Communications Interface"},{"location":"software-design-patterns/#2-decorator-pattern-equipment-modifications","text":"from abc import ABC, abstractmethod class Weapon(ABC): @abstractmethod def operate(self): pass class BaseRifle(Weapon): def operate(self): return \"Standard rifle operations\" class WeaponModification(Weapon): \"\"\" Mission: Add modular capabilities to equipment. Tactical Application: - Equipment customization - Mission-specific modifications - Capability enhancement \"\"\" def __init__(self, weapon): self._weapon = weapon class ScopeDecorator(WeaponModification): def operate(self): return f\"{self._weapon.operate()} + Enhanced targeting\" class SuppressorDecorator(WeaponModification): def operate(self): return f\"{self._weapon.operate()} + Noise reduction\" # Field Test rifle = BaseRifle() scoped_rifle = ScopeDecorator(rifle) tactical_rifle = SuppressorDecorator(scoped_rifle) print(tactical_rifle.operate())","title":"2. Decorator Pattern - Equipment Modifications"},{"location":"software-design-patterns/#behavioral-patterns","text":"","title":"Behavioral Patterns"},{"location":"software-design-patterns/#military-context_2","text":"Like standard operating procedures (SOPs), behavioral patterns define how different components communicate and operate together.","title":"Military Context"},{"location":"software-design-patterns/#1-observer-pattern-alert-system","text":"from abc import ABC, abstractmethod class AlertSystem(ABC): @abstractmethod def update(self, message): pass class Unit(AlertSystem): def __init__(self, name): self.name = name def update(self, message): print(f\"{self.name} received alert: {message}\") class CommandPost: \"\"\" Mission: Coordinate and disseminate information to multiple units. Tactical Application: - Alert dissemination - Unit coordination - Information broadcasting \"\"\" def __init__(self): self._units = [] def attach(self, unit): self._units.append(unit) def detach(self, unit): self._units.remove(unit) def notify(self, message): for unit in self._units: unit.update(message) # Field Test command_post = CommandPost() alpha_team = Unit(\"Alpha Team\") bravo_team = Unit(\"Bravo Team\") command_post.attach(alpha_team) command_post.attach(bravo_team) command_post.notify(\"Enemy contact at grid 123456\")","title":"1. Observer Pattern - Alert System"},{"location":"software-design-patterns/#2-strategy-pattern-mission-tactics","text":"from abc import ABC, abstractmethod class TacticalApproach(ABC): @abstractmethod def execute(self): pass class StealthApproach(TacticalApproach): def execute(self): return \"Executing silent approach\" class DirectAssault(TacticalApproach): def execute(self): return \"Executing frontal assault\" class MissionExecutor: \"\"\" Mission: Adapt tactical approach based on situation. Tactical Application: - Flexible mission execution - Adaptable tactics - Situational response \"\"\" def __init__(self, strategy: TacticalApproach): self._strategy = strategy def change_strategy(self, strategy: TacticalApproach): self._strategy = strategy def execute_mission(self): return self._strategy.execute() # Field Test mission = MissionExecutor(StealthApproach()) print(mission.execute_mission()) mission.change_strategy(DirectAssault()) print(mission.execute_mission())","title":"2. Strategy Pattern - Mission Tactics"},{"location":"software-design-patterns/#field-notes","text":"Design patterns are like battle-tested strategies - use them wisely Each pattern solves specific tactical problems Remember: Good architecture enables mission success \"Building robust systems with military precision\" - VetsWhoCode","title":"Field Notes"},{"location":"streamlit-fundamentals/","text":"Vets Who Code: Streamlit Fundamentals Building Interactive Web Applications with Python \ud83c\udfaf Lesson Objectives After completing this lesson, you will be able to: Set up a Streamlit development environment Understand core Streamlit components and layouts Create interactive user interfaces Handle user input and state management Build data visualizations Deploy Streamlit applications \ud83d\udee0\ufe0f Setup Instructions Ensure Python 3.10 is installed: python --version # Should show Python 3.10.x Create and activate a virtual environment: python -m venv vwc-streamlit source vwc-streamlit/bin/activate # Windows: vwc-streamlit\\Scripts\\activate Install required packages: pip install streamlit==1.31.0 pandas numpy \ud83d\udcda Lesson 1: Streamlit Basics Create a file named lesson1.py : import streamlit as st # Page configuration st.set_page_config( page_title=\"VWC Streamlit Lesson 1\", page_icon=\"\ud83c\udf96\ufe0f\", layout=\"wide\" ) # Basic text elements st.title(\"Welcome to Streamlit! \ud83d\ude80\") st.header(\"Let's learn the basics\") st.subheader(\"Text elements and markdown\") # Markdown support st.markdown(\"\"\" Here's what we can do with markdown: - **Bold text** - *Italic text* - `Code snippets` - [Links](https://vetswhocode.io) \"\"\") # Interactive elements if st.button(\"Click me!\"): st.write(\"Button was clicked!\") user_input = st.text_input(\"Enter your name\") if user_input: st.write(f\"Hello, {user_input}!\") # Run with: streamlit run lesson1.py \ud83d\udcda Lesson 2: Layouts and Containers Create lesson2.py : import streamlit as st st.title(\"Layout in Streamlit\") # Columns col1, col2 = st.columns(2) with col1: st.header(\"Column 1\") st.write(\"This is the left column\") st.button(\"Left Button\") with col2: st.header(\"Column 2\") st.write(\"This is the right column\") st.button(\"Right Button\") # Sidebar with st.sidebar: st.header(\"Sidebar\") option = st.selectbox( \"Choose an option\", [\"Option 1\", \"Option 2\", \"Option 3\"] ) # Tabs tab1, tab2 = st.tabs([\"Tab 1\", \"Tab 2\"]) with tab1: st.write(\"This is tab 1\") with tab2: st.write(\"This is tab 2\") # Containers with st.container(): st.write(\"This is a container\") st.write(\"It helps organize content\") \ud83d\udcda Lesson 3: State Management Create lesson3.py : import streamlit as st # Initialize session state if \"counter\" not in st.session_state: st.session_state.counter = 0 st.title(\"State Management in Streamlit\") # Display counter st.write(f\"Counter value: {st.session_state.counter}\") # Buttons to modify state if st.button(\"Increment\"): st.session_state.counter += 1 st.experimental_rerun() if st.button(\"Decrement\"): st.session_state.counter -= 1 st.experimental_rerun() # Form example with st.form(\"my_form\"): name = st.text_input(\"Name\") age = st.number_input(\"Age\", min_value=0, max_value=120) submitted = st.form_submit_button(\"Submit\") if submitted: st.write(f\"Name: {name}, Age: {age}\") \ud83d\udcda Lesson 4: Chat Interface Components Create lesson4.py : import streamlit as st from datetime import datetime # Initialize chat history if \"messages\" not in st.session_state: st.session_state.messages = [] st.title(\"Chat Interface Components\") # Chat display for message in st.session_state.messages: with st.container(): st.write(f\"{message['role']}: {message['content']}\") st.caption(f\"Sent at {message['timestamp']}\") # Message input message = st.text_input(\"Type a message\") if st.button(\"Send\") and message: # Add message to history st.session_state.messages.append({ \"role\": \"user\", \"content\": message, \"timestamp\": datetime.now().strftime(\"%I:%M %p\") }) # Simulate response st.session_state.messages.append({ \"role\": \"assistant\", \"content\": f\"You said: {message}\", \"timestamp\": datetime.now().strftime(\"%I:%M %p\") }) st.experimental_rerun() # Clear chat button if st.button(\"Clear Chat\"): st.session_state.messages = [] st.experimental_rerun() \ud83d\udcda Lesson 5: Data Visualization Create lesson5.py : import streamlit as st import pandas as pd import numpy as np st.title(\"Data Visualization in Streamlit\") # Create sample data data = pd.DataFrame({ 'date': pd.date_range('2024-01-01', '2024-01-10'), 'values': np.random.randn(10).cumsum() }) # Line chart st.subheader(\"Line Chart\") st.line_chart(data.set_index('date')) # Bar chart st.subheader(\"Bar Chart\") st.bar_chart(data.set_index('date')) # Metrics col1, col2, col3 = st.columns(3) with col1: st.metric(\"Total\", f\"{data['values'].sum():.2f}\") with col2: st.metric(\"Average\", f\"{data['values'].mean():.2f}\") with col3: st.metric(\"Max\", f\"{data['values'].max():.2f}\") \ud83d\udd04 Practice Exercises Create a todo list application using session state Build a simple calculator with a form Create a data dashboard with multiple visualizations Implement a file uploader with preview Build a multi-page application using st.sidebar \ud83d\ude80 Mini-Projects AI Chat Interface Implement message history Add user input handling Create styled message bubbles Add typing indicators Data Dashboard Load and display data Add interactive filters Create multiple visualizations Implement data download \ud83d\udcdd Best Practices Performance # Cache data loading @st.cache_data def load_data(): return pd.read_csv(\"data.csv\") # Cache resource-intensive computations @st.cache_resource def load_model(): return Model() Error Handling try: result = process_data() except Exception as e: st.error(f\"An error occurred: {str(e)}\") User Experience with st.spinner(\"Processing...\"): # Long running operation process_data() st.success(\"Done!\") \ud83c\udfaf Next Steps Explore Streamlit Cloud deployment Learn about custom components Study authentication and security Practice responsive design Master advanced visualizations \ud83d\udcda Resources Streamlit Documentation Streamlit Gallery VWC GitHub Python 3.10 Documentation \ud83d\udca1 Tips Use st.experimental_rerun() sparingly Keep state management simple Test locally before deployment Use caching for performance Follow Python best practices","title":"Streamlit Fundamentals"},{"location":"streamlit-fundamentals/#vets-who-code-streamlit-fundamentals","text":"","title":"Vets Who Code: Streamlit Fundamentals"},{"location":"streamlit-fundamentals/#building-interactive-web-applications-with-python","text":"","title":"Building Interactive Web Applications with Python"},{"location":"streamlit-fundamentals/#lesson-objectives","text":"After completing this lesson, you will be able to: Set up a Streamlit development environment Understand core Streamlit components and layouts Create interactive user interfaces Handle user input and state management Build data visualizations Deploy Streamlit applications","title":"\ud83c\udfaf Lesson Objectives"},{"location":"streamlit-fundamentals/#setup-instructions","text":"Ensure Python 3.10 is installed: python --version # Should show Python 3.10.x Create and activate a virtual environment: python -m venv vwc-streamlit source vwc-streamlit/bin/activate # Windows: vwc-streamlit\\Scripts\\activate Install required packages: pip install streamlit==1.31.0 pandas numpy","title":"\ud83d\udee0\ufe0f Setup Instructions"},{"location":"streamlit-fundamentals/#lesson-1-streamlit-basics","text":"Create a file named lesson1.py : import streamlit as st # Page configuration st.set_page_config( page_title=\"VWC Streamlit Lesson 1\", page_icon=\"\ud83c\udf96\ufe0f\", layout=\"wide\" ) # Basic text elements st.title(\"Welcome to Streamlit! \ud83d\ude80\") st.header(\"Let's learn the basics\") st.subheader(\"Text elements and markdown\") # Markdown support st.markdown(\"\"\" Here's what we can do with markdown: - **Bold text** - *Italic text* - `Code snippets` - [Links](https://vetswhocode.io) \"\"\") # Interactive elements if st.button(\"Click me!\"): st.write(\"Button was clicked!\") user_input = st.text_input(\"Enter your name\") if user_input: st.write(f\"Hello, {user_input}!\") # Run with: streamlit run lesson1.py","title":"\ud83d\udcda Lesson 1: Streamlit Basics"},{"location":"streamlit-fundamentals/#lesson-2-layouts-and-containers","text":"Create lesson2.py : import streamlit as st st.title(\"Layout in Streamlit\") # Columns col1, col2 = st.columns(2) with col1: st.header(\"Column 1\") st.write(\"This is the left column\") st.button(\"Left Button\") with col2: st.header(\"Column 2\") st.write(\"This is the right column\") st.button(\"Right Button\") # Sidebar with st.sidebar: st.header(\"Sidebar\") option = st.selectbox( \"Choose an option\", [\"Option 1\", \"Option 2\", \"Option 3\"] ) # Tabs tab1, tab2 = st.tabs([\"Tab 1\", \"Tab 2\"]) with tab1: st.write(\"This is tab 1\") with tab2: st.write(\"This is tab 2\") # Containers with st.container(): st.write(\"This is a container\") st.write(\"It helps organize content\")","title":"\ud83d\udcda Lesson 2: Layouts and Containers"},{"location":"streamlit-fundamentals/#lesson-3-state-management","text":"Create lesson3.py : import streamlit as st # Initialize session state if \"counter\" not in st.session_state: st.session_state.counter = 0 st.title(\"State Management in Streamlit\") # Display counter st.write(f\"Counter value: {st.session_state.counter}\") # Buttons to modify state if st.button(\"Increment\"): st.session_state.counter += 1 st.experimental_rerun() if st.button(\"Decrement\"): st.session_state.counter -= 1 st.experimental_rerun() # Form example with st.form(\"my_form\"): name = st.text_input(\"Name\") age = st.number_input(\"Age\", min_value=0, max_value=120) submitted = st.form_submit_button(\"Submit\") if submitted: st.write(f\"Name: {name}, Age: {age}\")","title":"\ud83d\udcda Lesson 3: State Management"},{"location":"streamlit-fundamentals/#lesson-4-chat-interface-components","text":"Create lesson4.py : import streamlit as st from datetime import datetime # Initialize chat history if \"messages\" not in st.session_state: st.session_state.messages = [] st.title(\"Chat Interface Components\") # Chat display for message in st.session_state.messages: with st.container(): st.write(f\"{message['role']}: {message['content']}\") st.caption(f\"Sent at {message['timestamp']}\") # Message input message = st.text_input(\"Type a message\") if st.button(\"Send\") and message: # Add message to history st.session_state.messages.append({ \"role\": \"user\", \"content\": message, \"timestamp\": datetime.now().strftime(\"%I:%M %p\") }) # Simulate response st.session_state.messages.append({ \"role\": \"assistant\", \"content\": f\"You said: {message}\", \"timestamp\": datetime.now().strftime(\"%I:%M %p\") }) st.experimental_rerun() # Clear chat button if st.button(\"Clear Chat\"): st.session_state.messages = [] st.experimental_rerun()","title":"\ud83d\udcda Lesson 4: Chat Interface Components"},{"location":"streamlit-fundamentals/#lesson-5-data-visualization","text":"Create lesson5.py : import streamlit as st import pandas as pd import numpy as np st.title(\"Data Visualization in Streamlit\") # Create sample data data = pd.DataFrame({ 'date': pd.date_range('2024-01-01', '2024-01-10'), 'values': np.random.randn(10).cumsum() }) # Line chart st.subheader(\"Line Chart\") st.line_chart(data.set_index('date')) # Bar chart st.subheader(\"Bar Chart\") st.bar_chart(data.set_index('date')) # Metrics col1, col2, col3 = st.columns(3) with col1: st.metric(\"Total\", f\"{data['values'].sum():.2f}\") with col2: st.metric(\"Average\", f\"{data['values'].mean():.2f}\") with col3: st.metric(\"Max\", f\"{data['values'].max():.2f}\")","title":"\ud83d\udcda Lesson 5: Data Visualization"},{"location":"streamlit-fundamentals/#practice-exercises","text":"Create a todo list application using session state Build a simple calculator with a form Create a data dashboard with multiple visualizations Implement a file uploader with preview Build a multi-page application using st.sidebar","title":"\ud83d\udd04 Practice Exercises"},{"location":"streamlit-fundamentals/#mini-projects","text":"AI Chat Interface Implement message history Add user input handling Create styled message bubbles Add typing indicators Data Dashboard Load and display data Add interactive filters Create multiple visualizations Implement data download","title":"\ud83d\ude80 Mini-Projects"},{"location":"streamlit-fundamentals/#best-practices","text":"Performance # Cache data loading @st.cache_data def load_data(): return pd.read_csv(\"data.csv\") # Cache resource-intensive computations @st.cache_resource def load_model(): return Model() Error Handling try: result = process_data() except Exception as e: st.error(f\"An error occurred: {str(e)}\") User Experience with st.spinner(\"Processing...\"): # Long running operation process_data() st.success(\"Done!\")","title":"\ud83d\udcdd Best Practices"},{"location":"streamlit-fundamentals/#next-steps","text":"Explore Streamlit Cloud deployment Learn about custom components Study authentication and security Practice responsive design Master advanced visualizations","title":"\ud83c\udfaf Next Steps"},{"location":"streamlit-fundamentals/#resources","text":"Streamlit Documentation Streamlit Gallery VWC GitHub Python 3.10 Documentation","title":"\ud83d\udcda Resources"},{"location":"streamlit-fundamentals/#tips","text":"Use st.experimental_rerun() sparingly Keep state management simple Test locally before deployment Use caching for performance Follow Python best practices","title":"\ud83d\udca1 Tips"},{"location":"system-design-patterns/","text":"VetsWhoCode: Strategic System Design Patterns \ud83c\udf96\ufe0f \"Like military logistics, system design requires planning for scale, resilience, and rapid response.\" - VetsWhoCode Overview This field manual covers large-scale system design patterns through a military perspective. Each pattern represents battle-tested approaches to building robust, scalable systems. Table of Contents Scalability Patterns Reliability Patterns Data Management Patterns Scalability Patterns Military Context Like expanding military operations from platoon to battalion level, scalability patterns enable systems to grow while maintaining operational effectiveness. 1. Load Balancer Pattern - Unit Distribution class LoadBalancer: \"\"\" Mission: Distribute incoming requests across multiple servers. Tactical Application: - Like distributing troops across multiple objectives - Prevents single point of failure - Maintains operational tempo under heavy load Strategy: - Round-robin distribution - Health monitoring - Automatic failover \"\"\" def __init__(self): self.servers = [] self.current_index = 0 def add_server(self, server): self.servers.append({ 'address': server, 'health': 100, 'active': True }) def get_next_server(self): # Round-robin selection of healthy servers available_servers = [s for s in self.servers if s['active']] if not available_servers: raise Exception(\"No servers available\") server = available_servers[self.current_index % len(available_servers)] self.current_index += 1 return server['address'] def health_check(self): # Simulate health checks like checking troops' readiness for server in self.servers: if server['health'] < 50: server['active'] = False # Field Implementation balancer = LoadBalancer() balancer.add_server(\"server-alpha\") balancer.add_server(\"server-bravo\") balancer.add_server(\"server-charlie\") 2. Database Sharding - Territory Division class DatabaseShard: \"\"\" Mission: Distribute data across multiple databases for improved performance. Tactical Application: - Like dividing territory into operational sectors - Each shard responsible for specific data range - Enables parallel operations \"\"\" def __init__(self, shard_key): self.shard_key = shard_key self.data = {} def write(self, key, value): self.data[key] = value def read(self, key): return self.data.get(key) class ShardManager: def __init__(self, num_shards): self.shards = [DatabaseShard(i) for i in range(num_shards)] def get_shard(self, key): # Determine shard based on key hash shard_id = hash(key) % len(self.shards) return self.shards[shard_id] def write_data(self, key, value): shard = self.get_shard(key) shard.write(key, value) def read_data(self, key): shard = self.get_shard(key) return shard.read(key) # Field Implementation shard_manager = ShardManager(3) # 3 operational sectors shard_manager.write_data(\"soldier_1\", \"Alpha Company\") shard_manager.write_data(\"soldier_2\", \"Bravo Company\") Reliability Patterns Military Context Like establishing defensive positions and fallback plans, reliability patterns ensure system resilience under adverse conditions. 1. Circuit Breaker - Tactical Retreat class CircuitBreaker: \"\"\" Mission: Prevent system failure by monitoring and stopping problematic operations. Tactical Application: - Like calling tactical retreat to prevent casualties - Monitors failure rates - Automatic system protection \"\"\" def __init__(self, failure_threshold): self.failure_threshold = failure_threshold self.failure_count = 0 self.state = \"CLOSED\" # CLOSED = operational, OPEN = stopped self.last_failure_time = None self.reset_timeout = 60 # seconds def execute(self, operation): if self.state == \"OPEN\": if self._should_reset(): self._reset() else: raise Exception(\"Circuit breaker is OPEN\") try: result = operation() self._success() return result except Exception as e: self._failure() raise e def _failure(self): self.failure_count += 1 if self.failure_count >= self.failure_threshold: self.state = \"OPEN\" self.last_failure_time = time.time() def _success(self): self.failure_count = 0 def _should_reset(self): return time.time() - self.last_failure_time > self.reset_timeout # Field Implementation circuit = CircuitBreaker(failure_threshold=5) def risky_operation(): # Simulate remote operation pass try: circuit.execute(risky_operation) except Exception: print(\"Falling back to safe mode\") 2. Bulkhead Pattern - Compartmentalization import threading from queue import Queue class Bulkhead: \"\"\" Mission: Isolate components to prevent cascade failures. Tactical Application: - Like compartmentalizing ship sections - Isolates failures to specific areas - Prevents total system failure \"\"\" def __init__(self, name, max_concurrent_calls): self.name = name self.semaphore = threading.Semaphore(max_concurrent_calls) self.queue = Queue() def execute(self, operation): if not self.semaphore.acquire(blocking=False): raise Exception(f\"Bulkhead {self.name} is full\") try: result = operation() return result finally: self.semaphore.release() # Field Implementation database_bulkhead = Bulkhead(\"Database\", max_concurrent_calls=10) api_bulkhead = Bulkhead(\"API\", max_concurrent_calls=20) Data Management Patterns Military Context Like managing military intelligence and logistics, data management patterns ensure efficient information flow and resource utilization. 1. CQRS - Operations and Intelligence Separation class CommandStack: \"\"\" Mission: Handle write operations separately from read operations. Tactical Application: - Like separating operations from intelligence - Optimized for specific tasks - Improved performance and scaling \"\"\" def __init__(self): self.events = [] def handle_command(self, command): # Process and validate command event = self._process_command(command) self.events.append(event) return event def _process_command(self, command): # Command processing logic return {\"type\": command.type, \"data\": command.data} class QueryStack: def __init__(self): self.read_model = {} def handle_query(self, query): # Return data from read-optimized model return self.read_model.get(query.key) # Field Implementation command_stack = CommandStack() query_stack = QueryStack() 2. API Gateway - Forward Operating Base class APIGateway: \"\"\" Mission: Provide centralized access point for multiple services. Tactical Application: - Like a Forward Operating Base - Central point of control - Resource coordination \"\"\" def __init__(self): self.services = {} self.auth_provider = None def register_service(self, name, service): self.services[name] = service def route_request(self, service_name, request): if not self._authenticate(request): raise Exception(\"Authentication failed\") service = self.services.get(service_name) if not service: raise Exception(f\"Service {service_name} not found\") return service.handle_request(request) def _authenticate(self, request): return self.auth_provider.verify(request.token) # Field Implementation gateway = APIGateway() gateway.register_service(\"logistics\", LogisticsService()) gateway.register_service(\"personnel\", PersonnelService()) Additional Resources Training Materials System Design Field Manual Scalability Best Practices Field Notes System design patterns are like strategic military planning Always plan for: Scalability (force multiplication) Reliability (defensive positions) Data Management (intelligence operations) Remember: Systems must be both robust and adaptable \"Building resilient systems with military precision\" - VetsWhoCode","title":"System Design Patterns"},{"location":"system-design-patterns/#vetswhocode-strategic-system-design-patterns","text":"\"Like military logistics, system design requires planning for scale, resilience, and rapid response.\" - VetsWhoCode","title":"VetsWhoCode: Strategic System Design Patterns \ud83c\udf96\ufe0f"},{"location":"system-design-patterns/#overview","text":"This field manual covers large-scale system design patterns through a military perspective. Each pattern represents battle-tested approaches to building robust, scalable systems.","title":"Overview"},{"location":"system-design-patterns/#table-of-contents","text":"Scalability Patterns Reliability Patterns Data Management Patterns","title":"Table of Contents"},{"location":"system-design-patterns/#scalability-patterns","text":"","title":"Scalability Patterns"},{"location":"system-design-patterns/#military-context","text":"Like expanding military operations from platoon to battalion level, scalability patterns enable systems to grow while maintaining operational effectiveness.","title":"Military Context"},{"location":"system-design-patterns/#1-load-balancer-pattern-unit-distribution","text":"class LoadBalancer: \"\"\" Mission: Distribute incoming requests across multiple servers. Tactical Application: - Like distributing troops across multiple objectives - Prevents single point of failure - Maintains operational tempo under heavy load Strategy: - Round-robin distribution - Health monitoring - Automatic failover \"\"\" def __init__(self): self.servers = [] self.current_index = 0 def add_server(self, server): self.servers.append({ 'address': server, 'health': 100, 'active': True }) def get_next_server(self): # Round-robin selection of healthy servers available_servers = [s for s in self.servers if s['active']] if not available_servers: raise Exception(\"No servers available\") server = available_servers[self.current_index % len(available_servers)] self.current_index += 1 return server['address'] def health_check(self): # Simulate health checks like checking troops' readiness for server in self.servers: if server['health'] < 50: server['active'] = False # Field Implementation balancer = LoadBalancer() balancer.add_server(\"server-alpha\") balancer.add_server(\"server-bravo\") balancer.add_server(\"server-charlie\")","title":"1. Load Balancer Pattern - Unit Distribution"},{"location":"system-design-patterns/#2-database-sharding-territory-division","text":"class DatabaseShard: \"\"\" Mission: Distribute data across multiple databases for improved performance. Tactical Application: - Like dividing territory into operational sectors - Each shard responsible for specific data range - Enables parallel operations \"\"\" def __init__(self, shard_key): self.shard_key = shard_key self.data = {} def write(self, key, value): self.data[key] = value def read(self, key): return self.data.get(key) class ShardManager: def __init__(self, num_shards): self.shards = [DatabaseShard(i) for i in range(num_shards)] def get_shard(self, key): # Determine shard based on key hash shard_id = hash(key) % len(self.shards) return self.shards[shard_id] def write_data(self, key, value): shard = self.get_shard(key) shard.write(key, value) def read_data(self, key): shard = self.get_shard(key) return shard.read(key) # Field Implementation shard_manager = ShardManager(3) # 3 operational sectors shard_manager.write_data(\"soldier_1\", \"Alpha Company\") shard_manager.write_data(\"soldier_2\", \"Bravo Company\")","title":"2. Database Sharding - Territory Division"},{"location":"system-design-patterns/#reliability-patterns","text":"","title":"Reliability Patterns"},{"location":"system-design-patterns/#military-context_1","text":"Like establishing defensive positions and fallback plans, reliability patterns ensure system resilience under adverse conditions.","title":"Military Context"},{"location":"system-design-patterns/#1-circuit-breaker-tactical-retreat","text":"class CircuitBreaker: \"\"\" Mission: Prevent system failure by monitoring and stopping problematic operations. Tactical Application: - Like calling tactical retreat to prevent casualties - Monitors failure rates - Automatic system protection \"\"\" def __init__(self, failure_threshold): self.failure_threshold = failure_threshold self.failure_count = 0 self.state = \"CLOSED\" # CLOSED = operational, OPEN = stopped self.last_failure_time = None self.reset_timeout = 60 # seconds def execute(self, operation): if self.state == \"OPEN\": if self._should_reset(): self._reset() else: raise Exception(\"Circuit breaker is OPEN\") try: result = operation() self._success() return result except Exception as e: self._failure() raise e def _failure(self): self.failure_count += 1 if self.failure_count >= self.failure_threshold: self.state = \"OPEN\" self.last_failure_time = time.time() def _success(self): self.failure_count = 0 def _should_reset(self): return time.time() - self.last_failure_time > self.reset_timeout # Field Implementation circuit = CircuitBreaker(failure_threshold=5) def risky_operation(): # Simulate remote operation pass try: circuit.execute(risky_operation) except Exception: print(\"Falling back to safe mode\")","title":"1. Circuit Breaker - Tactical Retreat"},{"location":"system-design-patterns/#2-bulkhead-pattern-compartmentalization","text":"import threading from queue import Queue class Bulkhead: \"\"\" Mission: Isolate components to prevent cascade failures. Tactical Application: - Like compartmentalizing ship sections - Isolates failures to specific areas - Prevents total system failure \"\"\" def __init__(self, name, max_concurrent_calls): self.name = name self.semaphore = threading.Semaphore(max_concurrent_calls) self.queue = Queue() def execute(self, operation): if not self.semaphore.acquire(blocking=False): raise Exception(f\"Bulkhead {self.name} is full\") try: result = operation() return result finally: self.semaphore.release() # Field Implementation database_bulkhead = Bulkhead(\"Database\", max_concurrent_calls=10) api_bulkhead = Bulkhead(\"API\", max_concurrent_calls=20)","title":"2. Bulkhead Pattern - Compartmentalization"},{"location":"system-design-patterns/#data-management-patterns","text":"","title":"Data Management Patterns"},{"location":"system-design-patterns/#military-context_2","text":"Like managing military intelligence and logistics, data management patterns ensure efficient information flow and resource utilization.","title":"Military Context"},{"location":"system-design-patterns/#1-cqrs-operations-and-intelligence-separation","text":"class CommandStack: \"\"\" Mission: Handle write operations separately from read operations. Tactical Application: - Like separating operations from intelligence - Optimized for specific tasks - Improved performance and scaling \"\"\" def __init__(self): self.events = [] def handle_command(self, command): # Process and validate command event = self._process_command(command) self.events.append(event) return event def _process_command(self, command): # Command processing logic return {\"type\": command.type, \"data\": command.data} class QueryStack: def __init__(self): self.read_model = {} def handle_query(self, query): # Return data from read-optimized model return self.read_model.get(query.key) # Field Implementation command_stack = CommandStack() query_stack = QueryStack()","title":"1. CQRS - Operations and Intelligence Separation"},{"location":"system-design-patterns/#2-api-gateway-forward-operating-base","text":"class APIGateway: \"\"\" Mission: Provide centralized access point for multiple services. Tactical Application: - Like a Forward Operating Base - Central point of control - Resource coordination \"\"\" def __init__(self): self.services = {} self.auth_provider = None def register_service(self, name, service): self.services[name] = service def route_request(self, service_name, request): if not self._authenticate(request): raise Exception(\"Authentication failed\") service = self.services.get(service_name) if not service: raise Exception(f\"Service {service_name} not found\") return service.handle_request(request) def _authenticate(self, request): return self.auth_provider.verify(request.token) # Field Implementation gateway = APIGateway() gateway.register_service(\"logistics\", LogisticsService()) gateway.register_service(\"personnel\", PersonnelService())","title":"2. API Gateway - Forward Operating Base"},{"location":"system-design-patterns/#additional-resources","text":"","title":"Additional Resources"},{"location":"system-design-patterns/#training-materials","text":"System Design Field Manual Scalability Best Practices","title":"Training Materials"},{"location":"system-design-patterns/#field-notes","text":"System design patterns are like strategic military planning Always plan for: Scalability (force multiplication) Reliability (defensive positions) Data Management (intelligence operations) Remember: Systems must be both robust and adaptable \"Building resilient systems with military precision\" - VetsWhoCode","title":"Field Notes"}]} \ No newline at end of file diff --git a/software-design-patterns/index.html b/software-design-patterns/index.html new file mode 100644 index 0000000..2d50f0a --- /dev/null +++ b/software-design-patterns/index.html @@ -0,0 +1,542 @@ + + + + + + + + Software Engineering Design Patterns - Vets Who Code SOPs + + + + + + + + + + + + + + +
    + + +
    + +
    +
    +
      +
    • + + + +
    • +
    • +
    +
    +
    +
    +
    + +

    VetsWhoCode: Strategic Design Patterns 🎖️

    +
    +

    "Good architecture, like good leadership, creates a foundation for success." - VetsWhoCode

    +
    +

    Overview

    +

    This field manual covers essential software design patterns through a military lens. Each pattern is presented with tactical analogies and practical Python implementations.

    +

    Table of Contents

    + +
    +

    Creational Patterns

    +

    Military Context

    +

    Like establishing different types of military installations, creational patterns define how we set up and organize our software assets. Each pattern serves a specific strategic purpose.

    +

    1. Singleton Pattern - Command Center

    +
    class CommandCenter:
    +    """
    +    Mission: Ensure only one command center exists for coordinating operations.
    +
    +    Tactical Application:
    +    - Central command and control
    +    - Unified communications hub
    +    - Resource management center
    +    """
    +    _instance = None
    +
    +    def __new__(cls):
    +        if cls._instance is None:
    +            cls._instance = super().__new__(cls)
    +            cls._instance.operations_log = []
    +            cls._instance.active_units = {}
    +        return cls._instance
    +
    +    def log_operation(self, operation):
    +        self.operations_log.append(operation)
    +
    +    def register_unit(self, unit_id, unit_type):
    +        self.active_units[unit_id] = unit_type
    +
    +# Field Test
    +command1 = CommandCenter()
    +command2 = CommandCenter()
    +print(f"Same command center: {command1 is command2}")  # True
    +
    +

    2. Factory Method - Equipment Factory

    +
    from abc import ABC, abstractmethod
    +
    +class Equipment(ABC):
    +    @abstractmethod
    +    def operate(self):
    +        pass
    +
    +class Rifle(Equipment):
    +    def operate(self):
    +        return "Rifle ready for operation"
    +
    +class Radio(Equipment):
    +    def operate(self):
    +        return "Radio established comms"
    +
    +class EquipmentFactory:
    +    """
    +    Mission: Standardize equipment creation process.
    +
    +    Tactical Application:
    +    - Standardized equipment procurement
    +    - Quality control
    +    - Inventory management
    +    """
    +    @staticmethod
    +    def create_equipment(equipment_type):
    +        if equipment_type == "rifle":
    +            return Rifle()
    +        elif equipment_type == "radio":
    +            return Radio()
    +        raise ValueError(f"Unknown equipment type: {equipment_type}")
    +
    +# Field Test
    +factory = EquipmentFactory()
    +rifle = factory.create_equipment("rifle")
    +radio = factory.create_equipment("radio")
    +
    +

    3. Builder Pattern - Mission Planner

    +
    class MissionPlan:
    +    def __init__(self):
    +        self.objectives = []
    +        self.resources = []
    +        self.timeline = None
    +        self.extraction_plan = None
    +
    +class MissionBuilder:
    +    """
    +    Mission: Construct complex mission plans step by step.
    +
    +    Tactical Application:
    +    - Detailed mission planning
    +    - Resource allocation
    +    - Contingency planning
    +    """
    +    def __init__(self):
    +        self.mission = MissionPlan()
    +
    +    def add_objective(self, objective):
    +        self.mission.objectives.append(objective)
    +        return self
    +
    +    def add_resource(self, resource):
    +        self.mission.resources.append(resource)
    +        return self
    +
    +    def set_timeline(self, timeline):
    +        self.mission.timeline = timeline
    +        return self
    +
    +    def set_extraction(self, extraction_plan):
    +        self.mission.extraction_plan = extraction_plan
    +        return self
    +
    +    def build(self):
    +        return self.mission
    +
    +# Field Test
    +mission = (MissionBuilder()
    +    .add_objective("Secure perimeter")
    +    .add_resource("Alpha Team")
    +    .set_timeline("H-Hour to H+6")
    +    .set_extraction("Helo pickup at LZ Bravo")
    +    .build())
    +
    +
    +

    Structural Patterns

    +

    Military Context

    +

    Like organizing units and establishing command relationships, structural patterns define how different components of the system work together.

    +

    1. Adapter Pattern - Communications Interface

    +
    class ModernRadio:
    +    def transmit_digital(self, message):
    +        return f"Digital transmission: {message}"
    +
    +class LegacyRadio:
    +    def send_analog(self, message):
    +        return f"Analog signal: {message}"
    +
    +class RadioAdapter:
    +    """
    +    Mission: Enable communication between modern and legacy systems.
    +
    +    Tactical Application:
    +    - Cross-platform communications
    +    - Legacy system integration
    +    - Interoperability assurance
    +    """
    +    def __init__(self, legacy_radio):
    +        self.legacy_radio = legacy_radio
    +
    +    def transmit_digital(self, message):
    +        analog_message = self.convert_to_analog(message)
    +        return self.legacy_radio.send_analog(analog_message)
    +
    +    def convert_to_analog(self, message):
    +        return f"Converted: {message}"
    +
    +# Field Test
    +modern = ModernRadio()
    +legacy = LegacyRadio()
    +adapter = RadioAdapter(legacy)
    +print(adapter.transmit_digital("Alpha moving to objective"))
    +
    +

    2. Decorator Pattern - Equipment Modifications

    +
    from abc import ABC, abstractmethod
    +
    +class Weapon(ABC):
    +    @abstractmethod
    +    def operate(self):
    +        pass
    +
    +class BaseRifle(Weapon):
    +    def operate(self):
    +        return "Standard rifle operations"
    +
    +class WeaponModification(Weapon):
    +    """
    +    Mission: Add modular capabilities to equipment.
    +
    +    Tactical Application:
    +    - Equipment customization
    +    - Mission-specific modifications
    +    - Capability enhancement
    +    """
    +    def __init__(self, weapon):
    +        self._weapon = weapon
    +
    +class ScopeDecorator(WeaponModification):
    +    def operate(self):
    +        return f"{self._weapon.operate()} + Enhanced targeting"
    +
    +class SuppressorDecorator(WeaponModification):
    +    def operate(self):
    +        return f"{self._weapon.operate()} + Noise reduction"
    +
    +# Field Test
    +rifle = BaseRifle()
    +scoped_rifle = ScopeDecorator(rifle)
    +tactical_rifle = SuppressorDecorator(scoped_rifle)
    +print(tactical_rifle.operate())
    +
    +
    +

    Behavioral Patterns

    +

    Military Context

    +

    Like standard operating procedures (SOPs), behavioral patterns define how different components communicate and operate together.

    +

    1. Observer Pattern - Alert System

    +
    from abc import ABC, abstractmethod
    +
    +class AlertSystem(ABC):
    +    @abstractmethod
    +    def update(self, message):
    +        pass
    +
    +class Unit(AlertSystem):
    +    def __init__(self, name):
    +        self.name = name
    +
    +    def update(self, message):
    +        print(f"{self.name} received alert: {message}")
    +
    +class CommandPost:
    +    """
    +    Mission: Coordinate and disseminate information to multiple units.
    +
    +    Tactical Application:
    +    - Alert dissemination
    +    - Unit coordination
    +    - Information broadcasting
    +    """
    +    def __init__(self):
    +        self._units = []
    +
    +    def attach(self, unit):
    +        self._units.append(unit)
    +
    +    def detach(self, unit):
    +        self._units.remove(unit)
    +
    +    def notify(self, message):
    +        for unit in self._units:
    +            unit.update(message)
    +
    +# Field Test
    +command_post = CommandPost()
    +alpha_team = Unit("Alpha Team")
    +bravo_team = Unit("Bravo Team")
    +
    +command_post.attach(alpha_team)
    +command_post.attach(bravo_team)
    +command_post.notify("Enemy contact at grid 123456")
    +
    +

    2. Strategy Pattern - Mission Tactics

    +
    from abc import ABC, abstractmethod
    +
    +class TacticalApproach(ABC):
    +    @abstractmethod
    +    def execute(self):
    +        pass
    +
    +class StealthApproach(TacticalApproach):
    +    def execute(self):
    +        return "Executing silent approach"
    +
    +class DirectAssault(TacticalApproach):
    +    def execute(self):
    +        return "Executing frontal assault"
    +
    +class MissionExecutor:
    +    """
    +    Mission: Adapt tactical approach based on situation.
    +
    +    Tactical Application:
    +    - Flexible mission execution
    +    - Adaptable tactics
    +    - Situational response
    +    """
    +    def __init__(self, strategy: TacticalApproach):
    +        self._strategy = strategy
    +
    +    def change_strategy(self, strategy: TacticalApproach):
    +        self._strategy = strategy
    +
    +    def execute_mission(self):
    +        return self._strategy.execute()
    +
    +# Field Test
    +mission = MissionExecutor(StealthApproach())
    +print(mission.execute_mission())
    +mission.change_strategy(DirectAssault())
    +print(mission.execute_mission())
    +
    +
    +

    Field Notes

    +
      +
    1. Design patterns are like battle-tested strategies - use them wisely
    2. +
    3. Each pattern solves specific tactical problems
    4. +
    5. Remember: Good architecture enables mission success
    6. +
    +
    +

    "Building robust systems with military precision" - VetsWhoCode

    + +
    +
    + +
    +
    + +
    + +
    + +
    + + + + « Previous + + + Next » + + +
    + + + + + + + + + diff --git a/streamlit-fundamentals/index.html b/streamlit-fundamentals/index.html index ea232b8..200b4ec 100644 --- a/streamlit-fundamentals/index.html +++ b/streamlit-fundamentals/index.html @@ -88,6 +88,18 @@
  • Advanced Python Operations
  • + + +
  • Patterns +
  • FastAPI diff --git a/system-design-patterns/index.html b/system-design-patterns/index.html new file mode 100644 index 0000000..da05d2c --- /dev/null +++ b/system-design-patterns/index.html @@ -0,0 +1,529 @@ + + + + + + + + System Design Patterns - Vets Who Code SOPs + + + + + + + + + + + + + + +
    + + +
    + +
    +
    +
      +
    • + + + +
    • +
    • +
    +
    +
    +
    +
    + +

    VetsWhoCode: Strategic System Design Patterns 🎖️

    +
    +

    "Like military logistics, system design requires planning for scale, resilience, and rapid response." - VetsWhoCode

    +
    +

    Overview

    +

    This field manual covers large-scale system design patterns through a military perspective. Each pattern represents battle-tested approaches to building robust, scalable systems.

    +

    Table of Contents

    + +
    +

    Scalability Patterns

    +

    Military Context

    +

    Like expanding military operations from platoon to battalion level, scalability patterns enable systems to grow while maintaining operational effectiveness.

    +

    1. Load Balancer Pattern - Unit Distribution

    +
    class LoadBalancer:
    +    """
    +    Mission: Distribute incoming requests across multiple servers.
    +
    +    Tactical Application:
    +    - Like distributing troops across multiple objectives
    +    - Prevents single point of failure
    +    - Maintains operational tempo under heavy load
    +
    +    Strategy:
    +    - Round-robin distribution
    +    - Health monitoring
    +    - Automatic failover
    +    """
    +    def __init__(self):
    +        self.servers = []
    +        self.current_index = 0
    +
    +    def add_server(self, server):
    +        self.servers.append({
    +            'address': server,
    +            'health': 100,
    +            'active': True
    +        })
    +
    +    def get_next_server(self):
    +        # Round-robin selection of healthy servers
    +        available_servers = [s for s in self.servers if s['active']]
    +        if not available_servers:
    +            raise Exception("No servers available")
    +
    +        server = available_servers[self.current_index % len(available_servers)]
    +        self.current_index += 1
    +        return server['address']
    +
    +    def health_check(self):
    +        # Simulate health checks like checking troops' readiness
    +        for server in self.servers:
    +            if server['health'] < 50:
    +                server['active'] = False
    +
    +# Field Implementation
    +balancer = LoadBalancer()
    +balancer.add_server("server-alpha")
    +balancer.add_server("server-bravo")
    +balancer.add_server("server-charlie")
    +
    +

    2. Database Sharding - Territory Division

    +
    class DatabaseShard:
    +    """
    +    Mission: Distribute data across multiple databases for improved performance.
    +
    +    Tactical Application:
    +    - Like dividing territory into operational sectors
    +    - Each shard responsible for specific data range
    +    - Enables parallel operations
    +    """
    +    def __init__(self, shard_key):
    +        self.shard_key = shard_key
    +        self.data = {}
    +
    +    def write(self, key, value):
    +        self.data[key] = value
    +
    +    def read(self, key):
    +        return self.data.get(key)
    +
    +class ShardManager:
    +    def __init__(self, num_shards):
    +        self.shards = [DatabaseShard(i) for i in range(num_shards)]
    +
    +    def get_shard(self, key):
    +        # Determine shard based on key hash
    +        shard_id = hash(key) % len(self.shards)
    +        return self.shards[shard_id]
    +
    +    def write_data(self, key, value):
    +        shard = self.get_shard(key)
    +        shard.write(key, value)
    +
    +    def read_data(self, key):
    +        shard = self.get_shard(key)
    +        return shard.read(key)
    +
    +# Field Implementation
    +shard_manager = ShardManager(3)  # 3 operational sectors
    +shard_manager.write_data("soldier_1", "Alpha Company")
    +shard_manager.write_data("soldier_2", "Bravo Company")
    +
    +
    +

    Reliability Patterns

    +

    Military Context

    +

    Like establishing defensive positions and fallback plans, reliability patterns ensure system resilience under adverse conditions.

    +

    1. Circuit Breaker - Tactical Retreat

    +
    class CircuitBreaker:
    +    """
    +    Mission: Prevent system failure by monitoring and stopping problematic operations.
    +
    +    Tactical Application:
    +    - Like calling tactical retreat to prevent casualties
    +    - Monitors failure rates
    +    - Automatic system protection
    +    """
    +    def __init__(self, failure_threshold):
    +        self.failure_threshold = failure_threshold
    +        self.failure_count = 0
    +        self.state = "CLOSED"  # CLOSED = operational, OPEN = stopped
    +        self.last_failure_time = None
    +        self.reset_timeout = 60  # seconds
    +
    +    def execute(self, operation):
    +        if self.state == "OPEN":
    +            if self._should_reset():
    +                self._reset()
    +            else:
    +                raise Exception("Circuit breaker is OPEN")
    +
    +        try:
    +            result = operation()
    +            self._success()
    +            return result
    +        except Exception as e:
    +            self._failure()
    +            raise e
    +
    +    def _failure(self):
    +        self.failure_count += 1
    +        if self.failure_count >= self.failure_threshold:
    +            self.state = "OPEN"
    +            self.last_failure_time = time.time()
    +
    +    def _success(self):
    +        self.failure_count = 0
    +
    +    def _should_reset(self):
    +        return time.time() - self.last_failure_time > self.reset_timeout
    +
    +# Field Implementation
    +circuit = CircuitBreaker(failure_threshold=5)
    +def risky_operation():
    +    # Simulate remote operation
    +    pass
    +
    +try:
    +    circuit.execute(risky_operation)
    +except Exception:
    +    print("Falling back to safe mode")
    +
    +

    2. Bulkhead Pattern - Compartmentalization

    +
    import threading
    +from queue import Queue
    +
    +class Bulkhead:
    +    """
    +    Mission: Isolate components to prevent cascade failures.
    +
    +    Tactical Application:
    +    - Like compartmentalizing ship sections
    +    - Isolates failures to specific areas
    +    - Prevents total system failure
    +    """
    +    def __init__(self, name, max_concurrent_calls):
    +        self.name = name
    +        self.semaphore = threading.Semaphore(max_concurrent_calls)
    +        self.queue = Queue()
    +
    +    def execute(self, operation):
    +        if not self.semaphore.acquire(blocking=False):
    +            raise Exception(f"Bulkhead {self.name} is full")
    +
    +        try:
    +            result = operation()
    +            return result
    +        finally:
    +            self.semaphore.release()
    +
    +# Field Implementation
    +database_bulkhead = Bulkhead("Database", max_concurrent_calls=10)
    +api_bulkhead = Bulkhead("API", max_concurrent_calls=20)
    +
    +
    +

    Data Management Patterns

    +

    Military Context

    +

    Like managing military intelligence and logistics, data management patterns ensure efficient information flow and resource utilization.

    +

    1. CQRS - Operations and Intelligence Separation

    +
    class CommandStack:
    +    """
    +    Mission: Handle write operations separately from read operations.
    +
    +    Tactical Application:
    +    - Like separating operations from intelligence
    +    - Optimized for specific tasks
    +    - Improved performance and scaling
    +    """
    +    def __init__(self):
    +        self.events = []
    +
    +    def handle_command(self, command):
    +        # Process and validate command
    +        event = self._process_command(command)
    +        self.events.append(event)
    +        return event
    +
    +    def _process_command(self, command):
    +        # Command processing logic
    +        return {"type": command.type, "data": command.data}
    +
    +class QueryStack:
    +    def __init__(self):
    +        self.read_model = {}
    +
    +    def handle_query(self, query):
    +        # Return data from read-optimized model
    +        return self.read_model.get(query.key)
    +
    +# Field Implementation
    +command_stack = CommandStack()
    +query_stack = QueryStack()
    +
    +

    2. API Gateway - Forward Operating Base

    +
    class APIGateway:
    +    """
    +    Mission: Provide centralized access point for multiple services.
    +
    +    Tactical Application:
    +    - Like a Forward Operating Base
    +    - Central point of control
    +    - Resource coordination
    +    """
    +    def __init__(self):
    +        self.services = {}
    +        self.auth_provider = None
    +
    +    def register_service(self, name, service):
    +        self.services[name] = service
    +
    +    def route_request(self, service_name, request):
    +        if not self._authenticate(request):
    +            raise Exception("Authentication failed")
    +
    +        service = self.services.get(service_name)
    +        if not service:
    +            raise Exception(f"Service {service_name} not found")
    +
    +        return service.handle_request(request)
    +
    +    def _authenticate(self, request):
    +        return self.auth_provider.verify(request.token)
    +
    +# Field Implementation
    +gateway = APIGateway()
    +gateway.register_service("logistics", LogisticsService())
    +gateway.register_service("personnel", PersonnelService())
    +
    +
    +

    Additional Resources

    +

    Training Materials

    + +

    Field Notes

    +
      +
    1. System design patterns are like strategic military planning
    2. +
    3. Always plan for:
    4. +
    5. Scalability (force multiplication)
    6. +
    7. Reliability (defensive positions)
    8. +
    9. Data Management (intelligence operations)
    10. +
    11. Remember: Systems must be both robust and adaptable
    12. +
    +
    +

    "Building resilient systems with military precision" - VetsWhoCode

    + +
    +
    + +
    +
    + +
    + +
    + +
    + + + + « Previous + + + Next » + + +
    + + + + + + + + +