utilities.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import uuid
  2. import hashlib
  3. from .. import constants
  4. ROUND = constants.DEFAULT_PRECISION
  5. def bit_mask(flags):
  6. """Generate a bit mask.
  7. :type flags: dict
  8. :return: int
  9. """
  10. bit = 0
  11. true = lambda x, y: (x | (1 << y))
  12. false = lambda x, y: (x & (~(1 << y)))
  13. for mask, position in constants.MASK.items():
  14. func = true if flags.get(mask) else false
  15. bit = func(bit, position)
  16. return bit
  17. def hash(value):
  18. """Generate a hash from a given value
  19. :param value:
  20. :rtype: str
  21. """
  22. hash_ = hashlib.md5()
  23. hash_.update(repr(value).encode('utf8'))
  24. return hash_.hexdigest()
  25. def id():
  26. """Generate a random UUID
  27. :rtype: str
  28. """
  29. return str(uuid.uuid4()).upper()
  30. def id_from_name(name):
  31. """Generate a UUID using a name as the namespace
  32. :type name: str
  33. :rtype: str
  34. """
  35. return str(uuid.uuid3(uuid.NAMESPACE_DNS, name)).upper()
  36. def rgb2int(rgb):
  37. """Convert a given rgb value to an integer
  38. :type rgb: list|tuple
  39. :rtype: int
  40. """
  41. is_tuple = isinstance(rgb, tuple)
  42. rgb = list(rgb) if is_tuple else rgb
  43. colour = (int(rgb[0]*255) << 16) + (int(rgb[1]*255) << 8) + int(rgb[2]*255)
  44. return colour