You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
6.0 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Glances.
  4. #
  5. # Copyright (C) 2018 Nicolargo <nicolas@nicolargo.com>
  6. #
  7. # Glances is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU Lesser General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Glances is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. # flake8: noqa
  20. # pylint: skip-file
  21. """Python 2/3 compatibility shims."""
  22. import operator
  23. import sys
  24. import unicodedata
  25. import types
  26. import subprocess
  27. from glances.logger import logger
  28. PY3 = sys.version_info[0] == 3
  29. if PY3:
  30. import queue
  31. from configparser import ConfigParser, NoOptionError, NoSectionError
  32. from statistics import mean
  33. from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport, Server
  34. from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
  35. from urllib.request import urlopen
  36. from urllib.error import HTTPError, URLError
  37. from urllib.parse import urlparse
  38. input = input
  39. range = range
  40. map = map
  41. text_type = str
  42. binary_type = bytes
  43. bool_type = bool
  44. long = int
  45. viewkeys = operator.methodcaller('keys')
  46. viewvalues = operator.methodcaller('values')
  47. viewitems = operator.methodcaller('items')
  48. def to_ascii(s):
  49. """Convert the bytes string to a ASCII string
  50. Usefull to remove accent (diacritics)"""
  51. if isinstance(s, binary_type):
  52. return s.decode()
  53. return s.encode('ascii', 'ignore').decode()
  54. def listitems(d):
  55. return list(d.items())
  56. def listkeys(d):
  57. return list(d.keys())
  58. def listvalues(d):
  59. return list(d.values())
  60. def iteritems(d):
  61. return iter(d.items())
  62. def iterkeys(d):
  63. return iter(d.keys())
  64. def itervalues(d):
  65. return iter(d.values())
  66. def u(s):
  67. if isinstance(s, text_type):
  68. return s
  69. return s.decode('utf-8', 'replace')
  70. def b(s):
  71. if isinstance(s, binary_type):
  72. return s
  73. return s.encode('utf-8')
  74. def nativestr(s):
  75. if isinstance(s, text_type):
  76. return s
  77. return s.decode('utf-8', 'replace')
  78. def system_exec(command):
  79. """Execute a system command and return the resul as a str"""
  80. try:
  81. res = subprocess.run(command.split(' '),
  82. stdout=subprocess.PIPE).stdout.decode('utf-8')
  83. except Exception as e:
  84. logger.debug('Can not evaluate command {} ({})'.format(command, e))
  85. res = ''
  86. return res.rstrip()
  87. else:
  88. import Queue as queue
  89. from itertools import imap as map
  90. from ConfigParser import SafeConfigParser as ConfigParser, NoOptionError, NoSectionError
  91. from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
  92. from xmlrpclib import Fault, ProtocolError, ServerProxy, Transport, Server
  93. from urllib2 import urlopen, HTTPError, URLError
  94. from urlparse import urlparse
  95. input = raw_input
  96. range = xrange
  97. ConfigParser.read_file = ConfigParser.readfp
  98. text_type = unicode
  99. binary_type = str
  100. bool_type = types.BooleanType
  101. long = long
  102. viewkeys = operator.methodcaller('viewkeys')
  103. viewvalues = operator.methodcaller('viewvalues')
  104. viewitems = operator.methodcaller('viewitems')
  105. def mean(numbers):
  106. return float(sum(numbers)) / max(len(numbers), 1)
  107. def to_ascii(s):
  108. """Convert the unicode 's' to a ASCII string
  109. Usefull to remove accent (diacritics)"""
  110. if isinstance(s, binary_type):
  111. return s
  112. return unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')
  113. def listitems(d):
  114. return d.items()
  115. def listkeys(d):
  116. return d.keys()
  117. def listvalues(d):
  118. return d.values()
  119. def iteritems(d):
  120. return d.iteritems()
  121. def iterkeys(d):
  122. return d.iterkeys()
  123. def itervalues(d):
  124. return d.itervalues()
  125. def u(s):
  126. if isinstance(s, text_type):
  127. return s
  128. return s.decode('utf-8')
  129. def b(s):
  130. if isinstance(s, binary_type):
  131. return s
  132. return s.encode('utf-8', 'replace')
  133. def nativestr(s):
  134. if isinstance(s, binary_type):
  135. return s
  136. return s.encode('utf-8', 'replace')
  137. def system_exec(command):
  138. """Execute a system command and return the resul as a str"""
  139. try:
  140. res = subprocess.check_output(command.split(' '))
  141. except Exception as e:
  142. logger.debug('Can not execute command {} ({})'.format(command, e))
  143. res = ''
  144. return res.rstrip()
  145. # Globals functions for both Python 2 and 3
  146. def subsample(data, sampling):
  147. """Compute a simple mean subsampling.
  148. Data should be a list of numerical itervalues
  149. Return a subsampled list of sampling lenght
  150. """
  151. if len(data) <= sampling:
  152. return data
  153. sampling_length = int(round(len(data) / float(sampling)))
  154. return [mean(data[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]
  155. def time_serie_subsample(data, sampling):
  156. """Compute a simple mean subsampling.
  157. Data should be a list of set (time, value)
  158. Return a subsampled list of sampling lenght
  159. """
  160. if len(data) <= sampling:
  161. return data
  162. t = [t[0] for t in data]
  163. v = [t[1] for t in data]
  164. sampling_length = int(round(len(data) / float(sampling)))
  165. t_subsampled = [t[s * sampling_length:(s + 1) * sampling_length][0] for s in range(0, sampling)]
  166. v_subsampled = [mean(v[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]
  167. return list(zip(t_subsampled, v_subsampled))