-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
113 lines (96 loc) · 2.74 KB
/
common.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# import sys
# import signal
# from contextlib import contextmanager
#
# class Color: #pylint: disable=W0232
# GRAY=30
# RED=31
# GREEN=32
# YELLOW=33
# BLUE=34
# MAGENTA=35
# CYAN=36
# WHITE=37
# CRIMSON=38
#
# def colorize(num, string, bold=False, highlight = False):
# assert isinstance(num, int)
# attr = []
# if highlight: num += 10
# attr.append(str(num))
# if bold: attr.append('1')
# return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
#
# def colorprint(colorcode, text, o=sys.stdout, bold=False):
# o.write(colorize(colorcode, text, bold=bold))
#
# def warn(msg):
# print (colorize(Color.YELLOW, msg))
#
# def error(msg):
# print (colorize(Color.RED, msg))
#
# # http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python
# class TimeoutException(Exception): pass
# @contextmanager
# def time_limit(seconds):
# def signal_handler(signum, frame):
# raise TimeoutException(colorize(Color.RED, " *** Timed out!", highlight=True))
# signal.signal(signal.SIGALRM, signal_handler)
# signal.alarm(seconds)
# try:
# yield
# finally:
# signal.alarm(0)
"windows"
import sys
import signal
from contextlib import contextmanager
import threading
import _thread
from sys import platform
class Color: # pylint: disable=W0232
GRAY = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
CRIMSON = 38
def colorize(num, string, bold=False, highlight=False):
assert isinstance(num, int)
attr = []
if highlight: num += 10
attr.append(str(num))
if bold: attr.append('1')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
def colorprint(colorcode, text, o=sys.stdout, bold=False):
o.write(colorize(colorcode, text, bold=bold))
def warn(msg):
print(colorize(Color.YELLOW, msg))
def error(msg):
print(colorize(Color.RED, msg))
# http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python
class TimeoutException(Exception): pass
@contextmanager
def time_limit(seconds):
if platform != 'win32':
def signal_handler(signum, frame):
raise TimeoutException(colorize(Color.RED, " *** Timed out!", highlight=True))
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
else:
timer = threading.Timer(seconds, lambda: _thread.interrupt_main())
timer.start()
try:
yield
except KeyboardInterrupt:
raise TimeoutException(colorize(Color.RED, " *** Timed out!", highlight=True))
finally:
timer.cancel()