utilities.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 rgb2int(rgb):
  31. """Convert a given rgb value to an integer
  32. :type rgb: list|tuple
  33. :rtype: int
  34. """
  35. is_tuple = isinstance(rgb, tuple)
  36. rgb = list(rgb) if is_tuple else rgb
  37. colour = (int(rgb[0]*255) << 16) + (int(rgb[1]*255) << 8) + int(rgb[2]*255)
  38. return colour