[formatting] reformat using "black -t py34"
getting rid of thinking about consistent formatting...
This commit is contained in:
parent
fa98bcbdd1
commit
30c1f712a6
119 changed files with 3961 additions and 3495 deletions
|
@ -20,4 +20,5 @@ def merge(target, *args):
|
|||
target[key] = copy.deepcopy(value)
|
||||
return target
|
||||
|
||||
|
||||
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
||||
|
|
17
util/cli.py
17
util/cli.py
|
@ -3,22 +3,29 @@ import shlex
|
|||
import subprocess
|
||||
import logging
|
||||
|
||||
|
||||
def execute(cmd, wait=True, ignore_errors=False, include_stderr=False, env=None):
|
||||
args = shlex.split(cmd)
|
||||
logging.debug(cmd)
|
||||
try:
|
||||
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if include_stderr else subprocess.PIPE, env=env)
|
||||
proc = subprocess.Popen(
|
||||
args,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT if include_stderr else subprocess.PIPE,
|
||||
env=env,
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
raise RuntimeError('{} not found'.format(cmd))
|
||||
raise RuntimeError("{} not found".format(cmd))
|
||||
|
||||
if wait:
|
||||
out, _ = proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
err = '{} exited with code {}'.format(cmd, proc.returncode)
|
||||
err = "{} exited with code {}".format(cmd, proc.returncode)
|
||||
if ignore_errors:
|
||||
return err
|
||||
raise RuntimeError(err)
|
||||
return out.decode('utf-8')
|
||||
return ''
|
||||
return out.decode("utf-8")
|
||||
return ""
|
||||
|
||||
|
||||
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
||||
|
|
|
@ -1,12 +1,14 @@
|
|||
import re
|
||||
|
||||
|
||||
def asbool(val):
|
||||
if val is None:
|
||||
return False
|
||||
if isinstance(val, bool):
|
||||
return val
|
||||
val = str(val).strip().lower()
|
||||
return val in ('t', 'true', 'y', 'yes', 'on', '1')
|
||||
return val in ("t", "true", "y", "yes", "on", "1")
|
||||
|
||||
|
||||
def asint(val, minimum=None, maximum=None):
|
||||
if val is None:
|
||||
|
@ -16,28 +18,33 @@ def asint(val, minimum=None, maximum=None):
|
|||
val = max(val, minimum if minimum else val)
|
||||
return val
|
||||
|
||||
|
||||
def aslist(val):
|
||||
if val is None:
|
||||
return []
|
||||
if isinstance(val, list):
|
||||
return val
|
||||
return str(val).replace(' ', '').split(',')
|
||||
return str(val).replace(" ", "").split(",")
|
||||
|
||||
__UNITS = {
|
||||
'metric': 'C', 'kelvin': 'K', 'imperial': 'F',
|
||||
'default': 'C'
|
||||
}
|
||||
def astemperature(value, unit='metric'):
|
||||
return u'{}°{}'.format(int(value), __UNITS.get(unit, __UNITS['default']))
|
||||
|
||||
def byte(val, fmt='{:.2f}'):
|
||||
for unit in ['', 'Ki', 'Mi', 'Gi']:
|
||||
__UNITS = {"metric": "C", "kelvin": "K", "imperial": "F", "default": "C"}
|
||||
|
||||
|
||||
def astemperature(value, unit="metric"):
|
||||
return "{}°{}".format(int(value), __UNITS.get(unit, __UNITS["default"]))
|
||||
|
||||
|
||||
def byte(val, fmt="{:.2f}"):
|
||||
for unit in ["", "Ki", "Mi", "Gi"]:
|
||||
if val < 1024.0:
|
||||
return '{}{}B'.format(fmt, unit).format(val)
|
||||
return "{}{}B".format(fmt, unit).format(val)
|
||||
val /= 1024.0
|
||||
return '{}GiB'.format(fmt).format(val*1024.0)
|
||||
return "{}GiB".format(fmt).format(val * 1024.0)
|
||||
|
||||
|
||||
__seconds_pattern = re.compile("(([\d\.?]+)h)?(([\d\.]+)m)?([\d\.]+)?s?")
|
||||
|
||||
|
||||
__seconds_pattern = re.compile('(([\d\.?]+)h)?(([\d\.]+)m)?([\d\.]+)?s?')
|
||||
def seconds(duration):
|
||||
if isinstance(duration, int) or isinstance(duration, float):
|
||||
return float(duration)
|
||||
|
@ -45,29 +52,31 @@ def seconds(duration):
|
|||
matches = __seconds_pattern.match(duration)
|
||||
result = 0.0
|
||||
if matches.group(2):
|
||||
result += float(matches.group(2))*3600 # hours
|
||||
result += float(matches.group(2)) * 3600 # hours
|
||||
if matches.group(4):
|
||||
result += float(matches.group(4))*60 # minutes
|
||||
result += float(matches.group(4)) * 60 # minutes
|
||||
if matches.group(5):
|
||||
result += float(matches.group(5)) # seconds
|
||||
result += float(matches.group(5)) # seconds
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def duration(duration, compact=False, unit=False):
|
||||
duration = int(duration)
|
||||
if duration < 0:
|
||||
return 'n/a'
|
||||
return "n/a"
|
||||
minutes, seconds = divmod(duration, 60)
|
||||
hours, minutes = divmod(minutes, 60)
|
||||
suf = 'm'
|
||||
res = '{:02d}:{:02d}'.format(minutes, seconds)
|
||||
suf = "m"
|
||||
res = "{:02d}:{:02d}".format(minutes, seconds)
|
||||
if hours > 0:
|
||||
if compact:
|
||||
res = '{:02d}:{:02d}'.format(hours, minutes)
|
||||
res = "{:02d}:{:02d}".format(hours, minutes)
|
||||
else:
|
||||
res = '{:02d}:{}'.format(hours, res)
|
||||
suf = 'h'
|
||||
res = "{:02d}:{}".format(hours, res)
|
||||
suf = "h"
|
||||
|
||||
return "{}{}".format(res, suf if unit else "")
|
||||
|
||||
return '{}{}'.format(res, suf if unit else '')
|
||||
|
||||
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
||||
|
|
102
util/graph.py
102
util/graph.py
|
@ -1,7 +1,9 @@
|
|||
MAX_PERCENTS = 100.
|
||||
MAX_PERCENTS = 100.0
|
||||
|
||||
|
||||
class Bar(object):
|
||||
"""superclass"""
|
||||
|
||||
bars = None
|
||||
|
||||
def __init__(self, value):
|
||||
|
@ -12,17 +14,19 @@ class Bar(object):
|
|||
"""
|
||||
self.value = value
|
||||
|
||||
|
||||
class HBar(Bar):
|
||||
"""horizontal bar (1 char)"""
|
||||
|
||||
bars = [
|
||||
u"\u2581",
|
||||
u"\u2582",
|
||||
u"\u2583",
|
||||
u"\u2584",
|
||||
u"\u2585",
|
||||
u"\u2586",
|
||||
u"\u2587",
|
||||
u"\u2588"
|
||||
"\u2581",
|
||||
"\u2582",
|
||||
"\u2583",
|
||||
"\u2584",
|
||||
"\u2585",
|
||||
"\u2586",
|
||||
"\u2587",
|
||||
"\u2588",
|
||||
]
|
||||
|
||||
def __init__(self, value):
|
||||
|
@ -47,6 +51,7 @@ class HBar(Bar):
|
|||
return self.bars[i]
|
||||
return self.bars[-1]
|
||||
|
||||
|
||||
def hbar(value):
|
||||
"""wrapper function"""
|
||||
return HBar(value).get_char()
|
||||
|
@ -54,15 +59,16 @@ def hbar(value):
|
|||
|
||||
class VBar(Bar):
|
||||
"""vertical bar (can be more than 1 char)"""
|
||||
|
||||
bars = [
|
||||
u"\u258f",
|
||||
u"\u258e",
|
||||
u"\u258d",
|
||||
u"\u258c",
|
||||
u"\u258b",
|
||||
u"\u258a",
|
||||
u"\u2589",
|
||||
u"\u2588"
|
||||
"\u258f",
|
||||
"\u258e",
|
||||
"\u258d",
|
||||
"\u258c",
|
||||
"\u258b",
|
||||
"\u258a",
|
||||
"\u2589",
|
||||
"\u2588",
|
||||
]
|
||||
|
||||
def __init__(self, value, width=1):
|
||||
|
@ -108,38 +114,41 @@ def vbar(value, width):
|
|||
"""wrapper function"""
|
||||
return VBar(value, width).get_chars()
|
||||
|
||||
|
||||
class BrailleGraph(object):
|
||||
"""
|
||||
graph using Braille chars
|
||||
scaled to passed values
|
||||
"""
|
||||
|
||||
chars = {
|
||||
(0, 0): u" ",
|
||||
(1, 0): u"\u2840",
|
||||
(2, 0): u"\u2844",
|
||||
(3, 0): u"\u2846",
|
||||
(4, 0): u"\u2847",
|
||||
(0, 1): u"\u2880",
|
||||
(0, 2): u"\u28a0",
|
||||
(0, 3): u"\u28b0",
|
||||
(0, 4): u"\u28b8",
|
||||
(1, 1): u"\u28c0",
|
||||
(2, 1): u"\u28c4",
|
||||
(3, 1): u"\u28c6",
|
||||
(4, 1): u"\u28c7",
|
||||
(1, 2): u"\u28e0",
|
||||
(2, 2): u"\u28e4",
|
||||
(3, 2): u"\u28e6",
|
||||
(4, 2): u"\u28e7",
|
||||
(1, 3): u"\u28f0",
|
||||
(2, 3): u"\u28f4",
|
||||
(3, 3): u"\u28f6",
|
||||
(4, 3): u"\u28f7",
|
||||
(1, 4): u"\u28f8",
|
||||
(2, 4): u"\u28fc",
|
||||
(3, 4): u"\u28fe",
|
||||
(4, 4): u"\u28ff"
|
||||
(0, 0): " ",
|
||||
(1, 0): "\u2840",
|
||||
(2, 0): "\u2844",
|
||||
(3, 0): "\u2846",
|
||||
(4, 0): "\u2847",
|
||||
(0, 1): "\u2880",
|
||||
(0, 2): "\u28a0",
|
||||
(0, 3): "\u28b0",
|
||||
(0, 4): "\u28b8",
|
||||
(1, 1): "\u28c0",
|
||||
(2, 1): "\u28c4",
|
||||
(3, 1): "\u28c6",
|
||||
(4, 1): "\u28c7",
|
||||
(1, 2): "\u28e0",
|
||||
(2, 2): "\u28e4",
|
||||
(3, 2): "\u28e6",
|
||||
(4, 2): "\u28e7",
|
||||
(1, 3): "\u28f0",
|
||||
(2, 3): "\u28f4",
|
||||
(3, 3): "\u28f6",
|
||||
(4, 3): "\u28f7",
|
||||
(1, 4): "\u28f8",
|
||||
(2, 4): "\u28fc",
|
||||
(3, 4): "\u28fe",
|
||||
(4, 4): "\u28ff",
|
||||
}
|
||||
|
||||
def __init__(self, values):
|
||||
"""
|
||||
Args:
|
||||
|
@ -152,8 +161,7 @@ class BrailleGraph(object):
|
|||
if len(self.values) % 2 == 1:
|
||||
self.values.append(0)
|
||||
self.steps = self.get_steps()
|
||||
self.parts = [tuple(self.steps[i:i+2])
|
||||
for i in range(len(self.steps))[::2]]
|
||||
self.parts = [tuple(self.steps[i : i + 2]) for i in range(len(self.steps))[::2]]
|
||||
|
||||
@staticmethod
|
||||
def get_height(value, unit):
|
||||
|
@ -166,7 +174,7 @@ class BrailleGraph(object):
|
|||
|
||||
unit (number): unit
|
||||
"""
|
||||
if value < unit / 10.:
|
||||
if value < unit / 10.0:
|
||||
return 0
|
||||
elif value <= unit:
|
||||
return 1
|
||||
|
@ -184,7 +192,7 @@ class BrailleGraph(object):
|
|||
Return: list
|
||||
"""
|
||||
maxval = max(self.values)
|
||||
unit = maxval / 4.
|
||||
unit = maxval / 4.0
|
||||
if unit == 0:
|
||||
return [0] * len(self.values)
|
||||
stepslist = []
|
||||
|
@ -203,8 +211,10 @@ class BrailleGraph(object):
|
|||
chars.append(BrailleGraph.chars[part])
|
||||
return "".join(chars)
|
||||
|
||||
|
||||
def braille(values):
|
||||
"""wrapper function"""
|
||||
return BrailleGraph(values).get_chars()
|
||||
|
||||
|
||||
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
||||
|
|
|
@ -7,30 +7,32 @@ __data = {}
|
|||
__next = 0
|
||||
|
||||
__sources = [
|
||||
{
|
||||
'url': 'http://free.ipwhois.io/json/',
|
||||
'mapping': {
|
||||
'latitude': 'latitude',
|
||||
'longitude': 'longitude',
|
||||
'country': 'country',
|
||||
'ip': 'public_ip',
|
||||
}
|
||||
{
|
||||
"url": "http://free.ipwhois.io/json/",
|
||||
"mapping": {
|
||||
"latitude": "latitude",
|
||||
"longitude": "longitude",
|
||||
"country": "country",
|
||||
"ip": "public_ip",
|
||||
},
|
||||
{
|
||||
'url': 'http://ipapi.co/json',
|
||||
'mapping': {
|
||||
'latitude': 'latitude',
|
||||
'longitude': 'longitude',
|
||||
'country_name': 'country',
|
||||
'ip': 'public_ip',
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"url": "http://ipapi.co/json",
|
||||
"mapping": {
|
||||
"latitude": "latitude",
|
||||
"longitude": "longitude",
|
||||
"country_name": "country",
|
||||
"ip": "public_ip",
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def __expired():
|
||||
global __next
|
||||
return __next <= time.time()
|
||||
|
||||
|
||||
def __load():
|
||||
global __data
|
||||
global __next
|
||||
|
@ -38,14 +40,15 @@ def __load():
|
|||
__data = {}
|
||||
for src in __sources:
|
||||
try:
|
||||
tmp = json.loads(urllib.request.urlopen(src['url']).read())
|
||||
for k, v in src['mapping'].items():
|
||||
tmp = json.loads(urllib.request.urlopen(src["url"]).read())
|
||||
for k, v in src["mapping"].items():
|
||||
__data[v] = tmp.get(k, None)
|
||||
__next = time.time() + 60*60*12 # update once every 12h
|
||||
__next = time.time() + 60 * 60 * 12 # update once every 12h
|
||||
return
|
||||
except Exception as e:
|
||||
pass
|
||||
__next = time.time() + 60*30 # error - try again every 30m
|
||||
__next = time.time() + 60 * 30 # error - try again every 30m
|
||||
|
||||
|
||||
def __get(name, default=None):
|
||||
global __data
|
||||
|
@ -53,17 +56,22 @@ def __get(name, default=None):
|
|||
__load()
|
||||
return __data.get(name, default)
|
||||
|
||||
|
||||
def reset():
|
||||
global __next
|
||||
__next = 0
|
||||
|
||||
|
||||
def coordinates():
|
||||
return __get('latitude'), __get('longitude')
|
||||
return __get("latitude"), __get("longitude")
|
||||
|
||||
|
||||
def country():
|
||||
return __get('country')
|
||||
return __get("country")
|
||||
|
||||
|
||||
def public_ip():
|
||||
return __get('public_ip')
|
||||
return __get("public_ip")
|
||||
|
||||
|
||||
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
||||
|
|
|
@ -10,6 +10,7 @@ except ImportError:
|
|||
|
||||
import functools
|
||||
|
||||
|
||||
class menu(object):
|
||||
def __init__(self, parent=None, leave=True):
|
||||
if not parent:
|
||||
|
@ -42,13 +43,16 @@ class menu(object):
|
|||
self._menu.add_cascade(label=menuitem, menu=submenu.menu())
|
||||
|
||||
def add_menuitem(self, menuitem, callback):
|
||||
self._menu.add_command(label=menuitem, command=functools.partial(self._on_click, callback))
|
||||
self._menu.add_command(
|
||||
label=menuitem, command=functools.partial(self._on_click, callback)
|
||||
)
|
||||
|
||||
def show(self, event, offset_x=0, offset_y=0):
|
||||
try:
|
||||
self._menu.tk_popup(event['x'] + offset_x, event['y'] + offset_y)
|
||||
self._menu.tk_popup(event["x"] + offset_x, event["y"] + offset_y)
|
||||
finally:
|
||||
self._menu.grab_release()
|
||||
self._root.mainloop()
|
||||
|
||||
|
||||
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
||||
|
|
|
@ -5,23 +5,26 @@ store interface by deriving from the Store class in
|
|||
this module
|
||||
"""
|
||||
|
||||
|
||||
class Store(object):
|
||||
"""Interface for storing and retrieving simple values"""
|
||||
|
||||
def __init__(self):
|
||||
super(Store, self).__init__()
|
||||
self._data = {}
|
||||
|
||||
def set(self, key, value):
|
||||
"""Set 'key' to 'value', overwriting 'key' if it exists already"""
|
||||
self._data[key] = { 'value': value, 'used': False }
|
||||
self._data[key] = {"value": value, "used": False}
|
||||
|
||||
def unused_keys(self):
|
||||
return [ key for key, value in self._data.items() if value['used'] == False ]
|
||||
return [key for key, value in self._data.items() if value["used"] == False]
|
||||
|
||||
def get(self, key, default=None):
|
||||
"""Return the current value of 'key', or 'default' if 'key' is not set"""
|
||||
if key in self._data:
|
||||
self._data[key]['used'] = True
|
||||
return self._data.get(key, { 'value': default })['value']
|
||||
self._data[key]["used"] = True
|
||||
return self._data.get(key, {"value": default})["value"]
|
||||
|
||||
|
||||
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue