Skip to content

Commit

Permalink
style: Standardize quotation marks and formatting across multiple fil…
Browse files Browse the repository at this point in the history
…es; remove dangling file
  • Loading branch information
AhmedNassar7 committed Feb 19, 2025
1 parent e014057 commit d941911
Show file tree
Hide file tree
Showing 22 changed files with 277 additions and 709 deletions.
43 changes: 0 additions & 43 deletions .pre-commit-config.yaml

This file was deleted.

53 changes: 24 additions & 29 deletions apps/stations/admin.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
# apps/stations/admin.py

from venv import logger

import markupsafe
from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Count
import markupsafe
from django.utils.html import format_html

from metro import settings
from .models import Line, Station, LineStation
from apps.stations.management.commands.populate_metro_data import Command as MetroDataCommand
from metro import settings

from .models import Line, LineStation, Station

# Get constants from MetroDataCommand
LINE_OPERATIONS = MetroDataCommand.LINE_OPERATIONS
Expand Down Expand Up @@ -75,11 +77,7 @@ def get_operational_hours(self, obj):

def get_interchanges(self, obj):
"""Display interchange stations"""
interchanges = (
Station.objects.filter(lines=obj)
.annotate(line_count=Count("lines"))
.filter(line_count__gt=1)
)
interchanges = Station.objects.filter(lines=obj).annotate(line_count=Count("lines")).filter(line_count__gt=1)
return ", ".join([station.name for station in interchanges])

get_interchanges.short_description = "Interchanges"
Expand Down Expand Up @@ -111,26 +109,23 @@ class StationAdmin(admin.ModelAdmin):
def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super().get_search_results(request, queryset, search_term)

if 'autocomplete' in request.path:
queryset = queryset.prefetch_related('lines')
if "autocomplete" in request.path:
queryset = queryset.prefetch_related("lines")

return queryset, use_distinct

def format_json(self, obj):
return {
'id': obj.id,
'text': obj.name,
'lines': ', '.join(line.name for line in obj.lines.all())
}
return {"id": obj.id, "text": obj.name, "lines": ", ".join(line.name for line in obj.lines.all())}

def formatted_name(self, obj):
"""Display station name with its lines"""
lines = ', '.join(line.name for line in obj.lines.all())
lines = ", ".join(line.name for line in obj.lines.all())
return f"{obj.name} ({lines})"

def is_interchange_display(self, obj):
"""Display interchange status"""
return obj.lines.count() > 1

is_interchange_display.boolean = True
is_interchange_display.short_description = "Interchange"

Expand All @@ -151,8 +146,7 @@ def is_interchange_status(self, obj):
# Use Django's built-in boolean icon method
return markupsafe(
'<img src="{}" alt="{}" style="width:16px; height:16px;">'.format(
f'/static/admin/img/icon-{"yes" if is_interchange else "no"}.svg',
'Yes' if is_interchange else 'No'
f'/static/admin/img/icon-{"yes" if is_interchange else "no"}.svg', "Yes" if is_interchange else "No"
)
)
except Exception as e:
Expand All @@ -167,17 +161,20 @@ def get_coordinates(self, obj):
"""Display coordinates with link to map"""
try:
# Check if coordinates exist and are valid
if (obj.latitude is not None and obj.longitude is not None and isinstance(obj.latitude, (int, float)) and isinstance(obj.longitude, (int, float))):

if (
obj.latitude is not None
and obj.longitude is not None
and isinstance(obj.latitude, (int, float))
and isinstance(obj.longitude, (int, float))
):
# Safely convert to float and round
lat = round(float(obj.latitude), 6)
lon = round(float(obj.longitude), 6)

# Validate coordinate ranges
if -90 <= lat <= 90 and -180 <= lon <= 180:
return format_html(
'<a href="https://www.google.com/maps?q={},{}" target="_blank">{}, {}</a>',
lat, lon, lat, lon
'<a href="https://www.google.com/maps?q={},{}" target="_blank">{}, {}</a>', lat, lon, lat, lon
)

logger.warning(f"Invalid coordinates for station {obj.name}: Lat {obj.latitude}, Lon {obj.longitude}")
Expand Down Expand Up @@ -205,6 +202,7 @@ def get_connections(self, obj):
if settings.DEBUG:
print(f"Error in get_connections: {e}")
return "Error"

get_connections.short_description = "Connections"


Expand All @@ -226,9 +224,7 @@ class LineStationAdmin(admin.ModelAdmin):
def get_next_station(self, obj):
"""Display next station in sequence"""
try:
next_station = LineStation.objects.filter(
line=obj.line, order=obj.order + 1
).first()
next_station = LineStation.objects.filter(line=obj.line, order=obj.order + 1).first()
return next_station.station.name if next_station else "-"
except Exception as e:
if settings.DEBUG:
Expand All @@ -238,9 +234,7 @@ def get_next_station(self, obj):
def get_distance_to_next(self, obj):
"""Display distance to next station"""
try:
next_station = LineStation.objects.filter(
line=obj.line, order=obj.order + 1
).first()
next_station = LineStation.objects.filter(line=obj.line, order=obj.order + 1).first()
if next_station:
distance = obj.station.distance_to(next_station.station)
return f"{distance / 1000:.2f} km"
Expand All @@ -249,4 +243,5 @@ def get_distance_to_next(self, obj):
if settings.DEBUG:
print(f"Error in get_distance_to_next: {e}")
return "Error"

get_distance_to_next.short_description = "Distance to Next"
9 changes: 5 additions & 4 deletions apps/trains/api/filters.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# apps/trains/api/filters.py

from django_filters import rest_framework as filters

from ..models import Train


class TrainFilter(filters.FilterSet):
line = filters.CharFilter(field_name='line__name', lookup_expr='icontains')
status = filters.CharFilter(field_name='status')
has_ac = filters.BooleanFilter(field_name='has_air_conditioning')
line = filters.CharFilter(field_name="line__name", lookup_expr="icontains")
status = filters.CharFilter(field_name="status")
has_ac = filters.BooleanFilter(field_name="has_air_conditioning")

class Meta:
model = Train
fields = ['line', 'status', 'has_ac']
fields = ["line", "status", "has_ac"]
2 changes: 1 addition & 1 deletion apps/trains/api/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@

class TrainPagination(PageNumberPagination):
page_size = 20
page_size_query_param = 'page_size'
page_size_query_param = "page_size"
max_page_size = 100
4 changes: 2 additions & 2 deletions apps/trains/api/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

class IsTrainOperator(permissions.BasePermission):
def has_permission(self, request, view):
return request.user and request.user.has_perm('trains.can_operate_train')
return request.user and request.user.has_perm("trains.can_operate_train")


class IsScheduleManager(permissions.BasePermission):
def has_permission(self, request, view):
return request.user and request.user.has_perm('trains.can_manage_schedules')
return request.user and request.user.has_perm("trains.can_manage_schedules")
4 changes: 3 additions & 1 deletion apps/trains/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
from django.shortcuts import get_object_or_404
from django.utils import timezone
from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import status, status as drf_status, viewsets
from rest_framework import status
from rest_framework import status as drf_status
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
Expand Down
131 changes: 64 additions & 67 deletions apps/trains/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,103 +3,100 @@

# Line configurations with actual station counts
LINE_CONFIG = {
'LINE_1': {
'has_ac_percentage': 50,
'total_trains': 30,
'speed_limit': 80,
'station_stop_time': 120,
'total_stations': 35,
'color_code': '#FF0000',
'directions': [
('HELWAN', 'Helwan'),
('MARG', 'El-Marg'),
]
"LINE_1": {
"has_ac_percentage": 50,
"total_trains": 30,
"speed_limit": 80,
"station_stop_time": 120,
"total_stations": 35,
"color_code": "#FF0000",
"directions": [
("HELWAN", "Helwan"),
("MARG", "El-Marg"),
],
},
'LINE_2': {
'has_ac_percentage': 50,
'total_trains': 20,
'speed_limit': 80,
'station_stop_time': 120,
'total_stations': 20,
'color_code': '#0000FF',
'directions': [
('SHOBRA', 'Shobra El Kheima'),
('MONIB', 'El-Monib'),
]
"LINE_2": {
"has_ac_percentage": 50,
"total_trains": 20,
"speed_limit": 80,
"station_stop_time": 120,
"total_stations": 20,
"color_code": "#0000FF",
"directions": [
("SHOBRA", "Shobra El Kheima"),
("MONIB", "El-Monib"),
],
},
"LINE_3": {
"has_ac_percentage": 100,
"total_trains": 25,
"speed_limit": 100,
"station_stop_time": 120,
"total_stations": 34,
"color_code": "#00FF00",
"directions": [
("ADLY", "Adly Mansour"),
("KIT_KAT", "Kit Kat"),
],
},
'LINE_3': {
'has_ac_percentage': 100,
'total_trains': 25,
'speed_limit': 100,
'station_stop_time': 120,
'total_stations': 34,
'color_code': '#00FF00',
'directions': [
('ADLY', 'Adly Mansour'),
('KIT_KAT', 'Kit Kat'),
]
}
}

# Train status choices
TRAIN_STATUS_CHOICES = [
('IN_SERVICE', 'In Service'),
('DELAYED', 'Delayed'),
('MAINTENANCE', 'Under Maintenance'),
('OUT_OF_SERVICE', 'Out of Service'),
("IN_SERVICE", "In Service"),
("DELAYED", "Delayed"),
("MAINTENANCE", "Under Maintenance"),
("OUT_OF_SERVICE", "Out of Service"),
]

DIRECTION_CHOICES = [
('NORTHBOUND', 'Northbound'),
('SOUTHBOUND', 'Southbound'),
("NORTHBOUND", "Northbound"),
("SOUTHBOUND", "Southbound"),
]

# Train types
TRAIN_TYPES = [
('AC', 'Air Conditioned'),
('NON_AC', 'Non Air Conditioned')
]
TRAIN_TYPES = [("AC", "Air Conditioned"), ("NON_AC", "Non Air Conditioned")]

# Crowd levels with realistic thresholds
CROWD_LEVELS = {
'EMPTY': (0, 20),
'LIGHT': (21, 40),
'MODERATE': (41, 60),
'CROWDED': (61, 80),
'PACKED': (81, 100),
"EMPTY": (0, 20),
"LIGHT": (21, 40),
"MODERATE": (41, 60),
"CROWDED": (61, 80),
"PACKED": (81, 100),
}

# Car capacity based on actual metro cars
CAR_CAPACITY = {
'SEATED': 40,
'STANDING': 140,
'TOTAL': 180,
'CRUSH': 220,
"SEATED": 40,
"STANDING": 140,
"TOTAL": 180,
"CRUSH": 220,
}

# Time windows for peak hours
PEAK_HOURS = {
'MORNING': {
'start': '07:00',
'end': '10:00',
"MORNING": {
"start": "07:00",
"end": "10:00",
},
"EVENING": {
"start": "16:00",
"end": "19:00",
},
'EVENING': {
'start': '16:00',
'end': '19:00',
}
}

# Average speeds
AVERAGE_SPEEDS = {
'NORMAL': 60,
'PEAK': 45,
'OFF_PEAK': 70,
"NORMAL": 60,
"PEAK": 45,
"OFF_PEAK": 70,
}

# Station dwell times
DWELL_TIMES = {
'NORMAL': 30,
'INTERCHANGE': 45,
'TERMINAL': 60,
'PEAK_FACTOR': 1.5,
"NORMAL": 30,
"INTERCHANGE": 45,
"TERMINAL": 60,
"PEAK_FACTOR": 1.5,
}
Loading

0 comments on commit d941911

Please sign in to comment.