You're browsing snippets anonymously. Log in or create an account to save and manage your own snippets.
Public Snippets
Showing
15 snippets
Create safe filename string
def safe_filename(s: str, replacement: str = "_") -> str:
"""
Convert a string to a safe filename by replacing unsafe characters.
Args:
s (str): The input string to be conver...
By
xtream1101
•
•
Updated
2025-10-15 14:35
Bulk download and extract zip files from urls
#!/bin/bash
# Configuration variables - modify these as needed
URLS_FILE="/path/to/urls.txt" # Path to file containing list of ZIP URLs
TARGET_DIR="/path/to/target/directory" # ...
By
xtream1101
•
•
Updated
2025-08-05 13:35
Django Query Stats per request
# stats.py
import time
from django.db import connection
from loguru import logger
class StatsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
...
By
xtream1101
•
•
Updated
2025-05-11 00:04
Reset default python log handlers
import logging
formatter = logging.Formatter('FOO: %(message)s')
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# This is the key line that removes the double logging
...
By
xtream1101
•
•
Updated
2025-03-04 18:33
Check if a server has strictsni enabled
curl -v -k https://1.2.3.4
By
xtream1101
•
•
Updated
2025-02-28 14:13
Firefox hide tab bar
/* Source file https://github.com/MrOtherGuy/firefox-csshacks/tree/master/chrome/hide_tabs_toolbar_v2.css made available under Mozilla Public License v. 2.0
See the above repository for updates as we...
By
xtream1101
•
•
Updated
2025-02-27 21:45
Get domain cert details in cli
DOMAIN=yourdomain.tld
echo | openssl s_client -showcerts -servername $DOMAIN -connect $DOMAIN:443 2>/dev/null | openssl x509 -inform pem -noout -text
By
xtream1101
•
•
Updated
2025-02-12 19:48
List mounted drives
df -h --output=target,size,used,avail,pcent,source | grep -e Mounted -e $1 | awk 'NR<2{print $0;next}{print $0| "sort"}'
By
xtream1101
•
•
Updated
2025-02-08 22:44
Django graphene mutation input validation
import graphene
class ScratchpadMutation(graphene.relay.ClientIDMutation):
class Input:
created_by = graphene.String(required=True)
foobar = graphene.String()
test = g...
By
xtream1101
•
•
Updated
2025-02-06 14:13
Try, try again - Multiple try/except blocks in a flat format
data = {'some_key': 'key value'}
key_data = None
for _ in range(1):
try:
key_data = data['someKey']
except Exception: pass
else: break # It worked
try:
key_d...
By
xtream1101
•
•
Updated
2025-02-06 13:43
Multi key sort on a list of dicts
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'London'},
{'name': 'Charlie', 'age': 20, 'city': 'New York'}
]
# Sort by 'city' first,...
By
xtream1101
•
•
Updated
2025-02-06 13:27
Convert image to dxf file
inkscape --export-type=dxf my-image.svg
By
xtream1101
•
•
Updated
2025-02-06 05:18
Clean up empty dirs
# List/print empty dirs (does not delete)
find /mnt/my-data/ -type d -empty -print
# Delete empty dirs
find /mnt/my-data/ -type d -empty -delete
By
xtream1101
•
•
Updated
2025-02-06 05:15
Bash command test
# Access individual arguments
echo "The first argument is: $1"
echo "The second argument is: $2"
# Access all arguments
echo "All arguments: $@"
# Access the number of arguments
echo "Number...
By
xtream1101
•
•
Updated
2025-02-06 05:13
Showing
15 snippets
Snippet
def safe_filename(s: str, replacement: str = "_") -> str:
"""
Convert a string to a safe filename by replacing unsafe characters.
Args:
s (str): The input string to be converted.
replacement (str): The character to replace unsafe characters with. Default is "_".
Returns:
str: A safe filename string.
"""
keep_chars = (" ", ".", "_", "-")
safe_name = "".join(c if c.isalnum() or c in keep_chars else replacement for c in s)
safe_name = safe_name.strip().strip(".")
return safe_name
if __name__ == "__main__":
test_cases_safe_filename = [
("example<file>name.txt", "example_file_name.txt"),
("unsafe:/\\|?*name.doc", "unsafe______name.doc"),
("normal_filename.pdf", "normal_filename.pdf"),
(" leading and trailing spaces ", "leading and trailing spaces"),
("file.name.with.many.dots...", "file.name.with.many.dots"),
("control\x00char\x1fname", "control_char_name"),
]
# Test safe_filename function
print("Testing safe_filename function:")
for input_str, expected_output in test_cases_safe_filename:
result = safe_filename(input_str)
assert result == expected_output, (
f"Failed for input '{input_str}': got '{result}', expected '{expected_output}'"
)
print("\nAll tests passed!")
By
xtream1101
•
•
Updated
2025-10-15 14:35