1
0

utils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import datetime
  2. import os
  3. def cached_property(f):
  4. """
  5. returns a cached property that is calculated by function f
  6. http://code.activestate.com/recipes/576563-cached-property/
  7. """
  8. def get(self):
  9. try:
  10. return self._property_cache[f]
  11. except AttributeError:
  12. self._property_cache = {}
  13. x = self._property_cache[f] = f(self)
  14. return x
  15. except KeyError:
  16. x = self._property_cache[f] = f(self)
  17. return x
  18. return property(get)
  19. def yesno(prompt, default=None):
  20. """
  21. Prompt the user for a yes or no.
  22. Can optionally specify a default value, which will only be
  23. used if they enter a blank line.
  24. Unrecognised input (anything other than "y", "n", "yes",
  25. "no" or "") will return None.
  26. """
  27. answer = raw_input(prompt).strip().lower()
  28. if answer == "y" or answer == "yes":
  29. return True
  30. elif answer == "n" or answer == "no":
  31. return False
  32. elif answer == "":
  33. return default
  34. else:
  35. return None
  36. # http://stackoverflow.com/a/5164027
  37. def prettydate(d):
  38. diff = datetime.datetime.utcnow() - d
  39. s = diff.seconds
  40. if diff.days > 7 or diff.days < 0:
  41. return d.strftime('%d %b %y')
  42. elif diff.days == 1:
  43. return '1 day ago'
  44. elif diff.days > 1:
  45. return '{0} days ago'.format(diff.days)
  46. elif s <= 1:
  47. return 'just now'
  48. elif s < 60:
  49. return '{0} seconds ago'.format(s)
  50. elif s < 120:
  51. return '1 minute ago'
  52. elif s < 3600:
  53. return '{0} minutes ago'.format(s/60)
  54. elif s < 7200:
  55. return '1 hour ago'
  56. else:
  57. return '{0} hours ago'.format(s/3600)
  58. def mkdir(path, permissions=0700):
  59. if not os.path.exists(path):
  60. os.mkdir(path)
  61. os.chmod(path, permissions)
  62. return path