system.py 2.0 KB

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