Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagecell
Path: blob/master/misc.py
447 views
1
"""
2
Misc functions / classes
3
"""
4
from binascii import b2a_base64
5
from contextlib import contextmanager
6
from datetime import datetime
7
import os
8
import shutil
9
import stat
10
import sys
11
12
13
class Config(object):
14
"""
15
Config file wrapper / handler class
16
17
This is designed to make loading and working with an
18
importable configuration file with options relevant to
19
multiple classes more convenient.
20
21
Rather than re-importing a configuration module whenever
22
a specific is attribute is needed, a Config object can
23
be instantiated by some base application and the relevant
24
attributes can be passed to whatever classes / functions
25
are needed.
26
27
This class tracks both the default and user-specified
28
configuration files
29
"""
30
def __init__(self):
31
import config_default
32
33
self.config = None
34
self.config_default = config_default
35
36
try:
37
import config
38
self.config = config
39
except ImportError:
40
pass
41
42
def get(self, attr):
43
"""
44
Get a config attribute. If the attribute is defined
45
in the user-specified file, that is used, otherwise
46
the default config file attribute is used if
47
possible. If the attribute is a dictionary, the items
48
in config and default_config will be merged.
49
50
:arg attr str: the name of the attribute to get
51
:returns: the value of the named attribute, or
52
None if the attribute does not exist.
53
"""
54
result = self.get_default(attr)
55
if self.config is not None:
56
try:
57
val = getattr(self.config, attr)
58
if isinstance(val, dict):
59
result.update(val)
60
else:
61
result = val
62
except AttributeError:
63
pass
64
return result
65
66
def get_default(self, attr):
67
"""
68
Get a config attribute from the default config file.
69
70
:arg attr str: the name of the attribute toget
71
:returns: the value of the named attribute, or
72
None if the attribute does not exist.
73
"""
74
config_val = None
75
76
try:
77
config_val = getattr(self.config_default, attr)
78
except AttributeError:
79
pass
80
81
return config_val
82
83
def set(self, attr, value):
84
"""
85
Set a config attribute
86
87
:arg attr str: the name of the attribute to set
88
:arg value: an arbitrary value to set the named
89
attribute to
90
"""
91
setattr(self.config, attr, value)
92
93
def get_attrs(self):
94
"""
95
Get a list of all the config object's attributes
96
97
This isn't very useful right now, since it includes
98
__<attr>__ attributes and the like.
99
100
:returns: a list of all attributes belonging to
101
the imported config module.
102
:rtype: list
103
"""
104
return dir(self.config)
105
106
107
@contextmanager
108
def session_metadata(metadata):
109
# flush any messages waiting in buffers
110
sys.stdout.flush()
111
sys.stderr.flush()
112
113
session = sys.stdout.session
114
old_metadata = session.metadata
115
new_metadata = old_metadata.copy()
116
new_metadata.update(metadata)
117
session.metadata = new_metadata
118
yield
119
sys.stdout.flush()
120
sys.stderr.flush()
121
session.metadata = old_metadata
122
123
def display_file(path, mimetype=None):
124
path = os.path.relpath(path)
125
if path.startswith("../"):
126
shutil.copy(path, ".")
127
path = os.path.basename(path)
128
os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | stat.S_IRGRP)
129
if mimetype is None:
130
mimetype = 'application/x-file'
131
mt = os.path.getmtime(path)
132
display_message({
133
'text/plain': '%s file' % mimetype,
134
mimetype: path + '?m=%s' % mt})
135
sys._sage_.sent_files[path] = mt
136
137
def display_html(s):
138
display_message({'text/plain': 'html', 'text/html': s})
139
140
def display_message(data, metadata=None):
141
sys.stdout.session.send(sys.stdout.pub_thread,
142
'display_data',
143
content={'data': data, 'source': 'sagecell'},
144
parent=sys.stdout.parent_header,
145
metadata=metadata)
146
147
def stream_message(stream, data, metadata=None):
148
sys.stdout.session.send(sys.stdout.pub_thread,
149
'stream',
150
content={'name': stream, 'data': data},
151
parent=sys.stdout.parent_header,
152
metadata=metadata)
153
154
def reset_kernel_timeout(timeout):
155
sys.stdout.session.send(sys.stdout.pub_thread,
156
'kernel_timeout',
157
content={'timeout': float(timeout)},
158
parent=sys.stdout.parent_header)
159
160
def javascript(code):
161
sys._sage_.display_message({'application/javascript': code, 'text/plain': 'javascript code'})
162
163
164
def sage_json(obj):
165
# Similar to json_default in jupyter_client/jsonutil.py
166
import sage.all
167
if isinstance(obj, datetime):
168
return obj.isoformat()
169
if isinstance(obj, sage.rings.integer.Integer):
170
return int(obj)
171
if isinstance(obj, (
172
sage.rings.real_mpfr.RealLiteral,
173
sage.rings.real_mpfr.RealNumber,
174
sage.rings.real_double.RealDoubleElement)):
175
return float(obj)
176
if isinstance(obj, bytes):
177
return b2a_base64(obj).decode('ascii')
178
raise TypeError(
179
"Object of type %s with value of %s is not JSON serializable"
180
% (type(obj), repr(obj)))
181
182