system.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import random
  2. import socket
  3. import time
  4. def check_port_available(port: int) -> bool:
  5. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  6. try:
  7. sock.bind(('localhost', port))
  8. return True
  9. except OSError:
  10. time.sleep(0.1) # Short delay to further reduce chance of collisions
  11. return False
  12. finally:
  13. sock.close()
  14. def find_available_tcp_port(min_port=30000, max_port=39999, max_attempts=10) -> int:
  15. """Find an available TCP port in a specified range.
  16. Args:
  17. min_port (int): The lower bound of the port range (default: 30000)
  18. max_port (int): The upper bound of the port range (default: 39999)
  19. max_attempts (int): Maximum number of attempts to find an available port (default: 10)
  20. Returns:
  21. int: An available port number, or -1 if none found after max_attempts
  22. """
  23. rng = random.SystemRandom()
  24. ports = list(range(min_port, max_port + 1))
  25. rng.shuffle(ports)
  26. for port in ports[:max_attempts]:
  27. if check_port_available(port):
  28. return port
  29. return -1
  30. def display_number_matrix(number: int) -> str | None:
  31. if not 0 <= number <= 999:
  32. return None
  33. # Define the matrix representation for each digit
  34. digits = {
  35. '0': ['###', '# #', '# #', '# #', '###'],
  36. '1': [' #', ' #', ' #', ' #', ' #'],
  37. '2': ['###', ' #', '###', '# ', '###'],
  38. '3': ['###', ' #', '###', ' #', '###'],
  39. '4': ['# #', '# #', '###', ' #', ' #'],
  40. '5': ['###', '# ', '###', ' #', '###'],
  41. '6': ['###', '# ', '###', '# #', '###'],
  42. '7': ['###', ' #', ' #', ' #', ' #'],
  43. '8': ['###', '# #', '###', '# #', '###'],
  44. '9': ['###', '# #', '###', ' #', '###'],
  45. }
  46. # alternatively, with leading zeros: num_str = f"{number:03d}"
  47. num_str = str(number) # Convert to string without padding
  48. result = []
  49. for row in range(5):
  50. line = ' '.join(digits[digit][row] for digit in num_str)
  51. result.append(line)
  52. matrix_display = '\n'.join(result)
  53. return f'\n{matrix_display}\n'