PageRenderTime 26ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/mne/externals/tqdm/_tqdm/utils.py

https://github.com/slew/mne-python
Python | 345 lines | 310 code | 22 blank | 13 comment | 31 complexity | baa74742e0535071f81fd310d1d4a019 MD5 | raw file
  1. from functools import wraps
  2. import os
  3. from platform import system as _curos
  4. import re
  5. import subprocess
  6. CUR_OS = _curos()
  7. IS_WIN = CUR_OS in ['Windows', 'cli']
  8. IS_NIX = (not IS_WIN) and any(
  9. CUR_OS.startswith(i) for i in
  10. ['CYGWIN', 'MSYS', 'Linux', 'Darwin', 'SunOS',
  11. 'FreeBSD', 'NetBSD', 'OpenBSD'])
  12. RE_ANSI = re.compile(r"\x1b\[[;\d]*[A-Za-z]")
  13. # Py2/3 compat. Empty conditional to avoid coverage
  14. if True: # pragma: no cover
  15. try:
  16. _range = xrange
  17. except NameError:
  18. _range = range
  19. try:
  20. _unich = unichr
  21. except NameError:
  22. _unich = chr
  23. try:
  24. _unicode = unicode
  25. except NameError:
  26. _unicode = str
  27. try:
  28. if IS_WIN:
  29. import colorama
  30. else:
  31. raise ImportError
  32. except ImportError:
  33. colorama = None
  34. else:
  35. try:
  36. colorama.init(strip=False)
  37. except TypeError:
  38. colorama.init()
  39. try:
  40. from weakref import WeakSet
  41. except ImportError:
  42. WeakSet = set
  43. try:
  44. _basestring = basestring
  45. except NameError:
  46. _basestring = str
  47. try: # py>=2.7,>=3.1
  48. from collections import OrderedDict as _OrderedDict
  49. except ImportError:
  50. try: # older Python versions with backported ordereddict lib
  51. from ordereddict import OrderedDict as _OrderedDict
  52. except ImportError: # older Python versions without ordereddict lib
  53. # Py2.6,3.0 compat, from PEP 372
  54. from collections import MutableMapping
  55. class _OrderedDict(dict, MutableMapping):
  56. # Methods with direct access to underlying attributes
  57. def __init__(self, *args, **kwds):
  58. if len(args) > 1:
  59. raise TypeError('expected at 1 argument, got %d',
  60. len(args))
  61. if not hasattr(self, '_keys'):
  62. self._keys = []
  63. self.update(*args, **kwds)
  64. def clear(self):
  65. del self._keys[:]
  66. dict.clear(self)
  67. def __setitem__(self, key, value):
  68. if key not in self:
  69. self._keys.append(key)
  70. dict.__setitem__(self, key, value)
  71. def __delitem__(self, key):
  72. dict.__delitem__(self, key)
  73. self._keys.remove(key)
  74. def __iter__(self):
  75. return iter(self._keys)
  76. def __reversed__(self):
  77. return reversed(self._keys)
  78. def popitem(self):
  79. if not self:
  80. raise KeyError
  81. key = self._keys.pop()
  82. value = dict.pop(self, key)
  83. return key, value
  84. def __reduce__(self):
  85. items = [[k, self[k]] for k in self]
  86. inst_dict = vars(self).copy()
  87. inst_dict.pop('_keys', None)
  88. return self.__class__, (items,), inst_dict
  89. # Methods with indirect access via the above methods
  90. setdefault = MutableMapping.setdefault
  91. update = MutableMapping.update
  92. pop = MutableMapping.pop
  93. keys = MutableMapping.keys
  94. values = MutableMapping.values
  95. items = MutableMapping.items
  96. def __repr__(self):
  97. pairs = ', '.join(map('%r: %r'.__mod__, self.items()))
  98. return '%s({%s})' % (self.__class__.__name__, pairs)
  99. def copy(self):
  100. return self.__class__(self)
  101. @classmethod
  102. def fromkeys(cls, iterable, value=None):
  103. d = cls()
  104. for key in iterable:
  105. d[key] = value
  106. return d
  107. class FormatReplace(object):
  108. """
  109. >>> a = FormatReplace('something')
  110. >>> "{:5d}".format(a)
  111. 'something'
  112. """
  113. def __init__(self, replace=''):
  114. self.replace = replace
  115. self.format_called = 0
  116. def __format__(self, _):
  117. self.format_called += 1
  118. return self.replace
  119. class Comparable(object):
  120. """Assumes child has self._comparable attr/@property"""
  121. def __lt__(self, other):
  122. return self._comparable < other._comparable
  123. def __le__(self, other):
  124. return (self < other) or (self == other)
  125. def __eq__(self, other):
  126. return self._comparable == other._comparable
  127. def __ne__(self, other):
  128. return not self == other
  129. def __gt__(self, other):
  130. return not self <= other
  131. def __ge__(self, other):
  132. return not self < other
  133. class ObjectWrapper(object):
  134. def __getattr__(self, name):
  135. return getattr(self._wrapped, name)
  136. def __setattr__(self, name, value):
  137. return setattr(self._wrapped, name, value)
  138. def wrapper_getattr(self, name):
  139. """Actual `self.getattr` rather than self._wrapped.getattr"""
  140. try:
  141. return object.__getattr__(self, name)
  142. except AttributeError: # py2
  143. return getattr(self, name)
  144. def wrapper_setattr(self, name, value):
  145. """Actual `self.setattr` rather than self._wrapped.setattr"""
  146. return object.__setattr__(self, name, value)
  147. def __init__(self, wrapped):
  148. """
  149. Thin wrapper around a given object
  150. """
  151. self.wrapper_setattr('_wrapped', wrapped)
  152. class SimpleTextIOWrapper(ObjectWrapper):
  153. """
  154. Change only `.write()` of the wrapped object by encoding the passed
  155. value and passing the result to the wrapped object's `.write()` method.
  156. """
  157. # pylint: disable=too-few-public-methods
  158. def __init__(self, wrapped, encoding):
  159. super(SimpleTextIOWrapper, self).__init__(wrapped)
  160. self.wrapper_setattr('encoding', encoding)
  161. def write(self, s):
  162. """
  163. Encode `s` and pass to the wrapped object's `.write()` method.
  164. """
  165. return self._wrapped.write(s.encode(self.wrapper_getattr('encoding')))
  166. class CallbackIOWrapper(ObjectWrapper):
  167. def __init__(self, callback, stream, method="read"):
  168. """
  169. Wrap a given `file`-like object's `read()` or `write()` to report
  170. lengths to the given `callback`
  171. """
  172. super(CallbackIOWrapper, self).__init__(stream)
  173. func = getattr(stream, method)
  174. if method == "write":
  175. @wraps(func)
  176. def write(data, *args, **kwargs):
  177. res = func(data, *args, **kwargs)
  178. callback(len(data))
  179. return res
  180. self.wrapper_setattr('write', write)
  181. elif method == "read":
  182. @wraps(func)
  183. def read(*args, **kwargs):
  184. data = func(*args, **kwargs)
  185. callback(len(data))
  186. return data
  187. self.wrapper_setattr('read', read)
  188. else:
  189. raise KeyError("Can only wrap read/write methods")
  190. def _is_utf(encoding):
  191. try:
  192. u'\u2588\u2589'.encode(encoding)
  193. except UnicodeEncodeError: # pragma: no cover
  194. return False
  195. except Exception: # pragma: no cover
  196. try:
  197. return encoding.lower().startswith('utf-') or ('U8' == encoding)
  198. except:
  199. return False
  200. else:
  201. return True
  202. def _supports_unicode(fp):
  203. try:
  204. return _is_utf(fp.encoding)
  205. except AttributeError:
  206. return False
  207. def _is_ascii(s):
  208. if isinstance(s, str):
  209. for c in s:
  210. if ord(c) > 255:
  211. return False
  212. return True
  213. return _supports_unicode(s)
  214. def _environ_cols_wrapper(): # pragma: no cover
  215. """
  216. Return a function which gets width and height of console
  217. (linux,osx,windows,cygwin).
  218. """
  219. _environ_cols = None
  220. if IS_WIN:
  221. _environ_cols = _environ_cols_windows
  222. if _environ_cols is None:
  223. _environ_cols = _environ_cols_tput
  224. if IS_NIX:
  225. _environ_cols = _environ_cols_linux
  226. return _environ_cols
  227. def _environ_cols_windows(fp): # pragma: no cover
  228. try:
  229. from ctypes import windll, create_string_buffer
  230. import struct
  231. from sys import stdin, stdout
  232. io_handle = -12 # assume stderr
  233. if fp == stdin:
  234. io_handle = -10
  235. elif fp == stdout:
  236. io_handle = -11
  237. h = windll.kernel32.GetStdHandle(io_handle)
  238. csbi = create_string_buffer(22)
  239. res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
  240. if res:
  241. (_bufx, _bufy, _curx, _cury, _wattr, left, _top, right, _bottom,
  242. _maxx, _maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
  243. # nlines = bottom - top + 1
  244. return right - left # +1
  245. except:
  246. pass
  247. return None
  248. def _environ_cols_tput(*_): # pragma: no cover
  249. """cygwin xterm (windows)"""
  250. try:
  251. import shlex
  252. cols = int(subprocess.check_call(shlex.split('tput cols')))
  253. # rows = int(subprocess.check_call(shlex.split('tput lines')))
  254. return cols
  255. except:
  256. pass
  257. return None
  258. def _environ_cols_linux(fp): # pragma: no cover
  259. try:
  260. from termios import TIOCGWINSZ
  261. from fcntl import ioctl
  262. from array import array
  263. except ImportError:
  264. return None
  265. else:
  266. try:
  267. return array('h', ioctl(fp, TIOCGWINSZ, '\0' * 8))[1]
  268. except:
  269. try:
  270. return int(os.environ["COLUMNS"]) - 1
  271. except KeyError:
  272. return None
  273. def _term_move_up(): # pragma: no cover
  274. return '' if (os.name == 'nt') and (colorama is None) else '\x1b[A'
  275. try:
  276. # TODO consider using wcswidth third-party package for 0-width characters
  277. from unicodedata import east_asian_width
  278. except ImportError:
  279. _text_width = len
  280. else:
  281. def _text_width(s):
  282. return sum(
  283. 2 if east_asian_width(ch) in 'FW' else 1 for ch in _unicode(s))