This repository has been archived by the owner on Jun 18, 2020. It is now read-only.
/
worksheet.py
4350 lines (3547 loc) · 138 KB
/
worksheet.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
r"""
A Worksheet
A worksheet is embedded in a web page that is served by the Sage
server. It is a linearly-ordered collections of numbered cells,
where a cell is a single input/output block.
The worksheet module is responsible for running calculations in a
worksheet, spawning Sage processes that do all of the actual work
and are controlled via pexpect, and reporting on results of
calculations. The state of the cells in a worksheet is stored on
the file system (not in the notebook pickle sobj).
AUTHORS:
- William Stein
"""
###########################################################################
# Copyright (C) 2006-2009 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
###########################################################################
# Import standard Python libraries that we will use below
import base64
import bz2
import calendar
import copy
import os
import re
import shutil
import string
import time
import traceback
import locale
# General sage library code
from sagenb.misc.misc import (cython, load, save,
alarm, cancel_alarm, verbose, DOT_SAGENB,
walltime, ignore_nonexistent_files,
set_restrictive_permissions,
set_permissive_permissions,
encoded_str, unicode_str)
from sagenb.misc.remote_file import get_remote_file
from sagenb.interfaces import (WorksheetProcess_ExpectImplementation,
WorksheetProcess_ReferenceImplementation,
WorksheetProcess_RemoteExpectImplementation)
import sagenb.misc.support as support
from sagenb.misc.format import relocate_future_imports
# Imports specifically relevant to the sage notebook
from cell import Cell, TextCell
from template import template, clean_name, prettify_time_ago
from flask.ext.babel import gettext, lazy_gettext
_ = gettext
# Set some constants that will be used for regular expressions below.
whitespace = re.compile('\s') # Match any whitespace character
non_whitespace = re.compile('\S')
# The file to which the Sage code that will be evaluated is written.
CODE_PY = "___code___.py"
# Constants that control the behavior of the worksheet.
INTERRUPT_TRIES = 3 # number of times to send control-c to
# subprocess before giving up
INITIAL_NUM_CELLS = 1 # number of empty cells in new worksheets
WARN_THRESHOLD = 100 # The number of seconds, so if there was no
# activity on this worksheet for this many
# seconds, then editing is considered safe.
# Used when multiple people are editing the
# same worksheet.
# The strings used to synchronized the compute subprocesses.
# WARNING: If you make any changes to this, be sure to change the
# error line below that looks like this:
# cmd += 'print "\\x01r\\x01e%s"'%self.synchro()
SC = '\x01'
SAGE_BEGIN = SC + 'b'
SAGE_END = SC + 'e'
SAGE_ERROR = SC + 'r'
# Integers that define which folder this worksheet is in relative to a
# given user.
ARCHIVED = 0
ACTIVE = 1
TRASH = 2
all_worksheet_processes = []
def update_worksheets():
"""
Iterate through and "update" all the worksheets. This is needed
for things like wall timeouts.
"""
for S in all_worksheet_processes:
S.update()
import notebook as _notebook
def worksheet_filename(name, owner):
"""
Return the relative directory name of this worksheet with given
name and owner.
INPUT:
- ``name`` - string, which may have spaces and funny
characters, which are replaced by underscores.
- ``owner`` - string, with no spaces or funny
characters
OUTPUT: string
EXAMPLES::
sage: sagenb.notebook.worksheet.worksheet_filename('Example worksheet 3', 'sage10')
'sage10/Example_worksheet_3'
sage: sagenb.notebook.worksheet.worksheet_filename('Example#%&! work\\sheet 3', 'sage10')
'sage10/Example_____work_sheet_3'
"""
return os.path.join(owner, clean_name(name))
def Worksheet_from_basic(obj, notebook_worksheet_directory):
"""
INPUT:
- ``obj`` -- a dictionary (a basic Python objet) from which a
worksheet can be reconstructed.
- ``notebook_worksheet_directory`` - string; the directory in
which the notebook object that contains this worksheet
stores worksheets, i.e., nb.worksheet_directory().
OUTPUT:
- a worksheet
EXAMPLES::
sage: import sagenb.notebook.worksheet
sage: W = sagenb.notebook.worksheet.Worksheet('test', 0, tmp_dir(), system='gap', owner='sageuser', pretty_print=True, auto_publish=True)
sage: _=W.new_cell_after(0); B = W.basic()
sage: W0 = sagenb.notebook.worksheet.Worksheet_from_basic(B, tmp_dir())
sage: W0.basic() == B
True
"""
W = Worksheet()
W.reconstruct_from_basic(obj, notebook_worksheet_directory)
return W
class Worksheet(object):
def __init__(self, name=None, id_number=None,
notebook_worksheet_directory=None, system=None,
owner=None, pretty_print=False,
auto_publish=False, create_directories=True):
ur"""
Create and initialize a new worksheet.
INPUT:
- ``name`` - string; the name of this worksheet
- ``id_number`` - Integer; name of the directory in which the
worksheet's data is stored
- ``notebook_worksheet_directory`` - string; the
directory in which the notebook object that contains this worksheet
stores worksheets, i.e., nb.worksheet_directory().
- ``system`` - string; 'sage', 'gp', 'singular', etc.
- the math software system in which all code is evaluated by
default
- ``owner`` - string; username of the owner of this
worksheet
- ``pretty_print`` - bool (default: False); whether
all output is pretty printed by default.
- ``create_directories`` -- bool (default: True): if True,
creates various files and directories where data will be
stored. This option is here only for the
migrate_old_notebook method in notebook.py
EXAMPLES: We test the constructor via an indirect doctest::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: import sagenb.notebook.misc
sage: sagenb.notebook.misc.notebook = nb
sage: W = nb.create_new_worksheet('Test with unicode ěščřžýáíéďĎ', 'admin')
sage: W
admin/0: [Cell 1: in=, out=]
"""
if name is None:
# A fresh worksheet
self.clear()
return
# Record the basic properties of the worksheet
self.__system = system
self.__pretty_print = pretty_print
self.__owner = owner
self.__viewers = []
self.__collaborators = []
self.__autopublish = auto_publish
self.__saved_by_info = {}
# state sequence number, used for sync
self.__state_number = 0
# Initialize the cell id counter.
self.__next_id = 0
self.set_name(name)
# set the directory in which the worksheet files will be stored.
# We also add the hash of the name, since the cleaned name loses info, e.g.,
# it could be all _'s if all characters are funny.
self.__id_number = int(id_number)
filename = os.path.join(owner, str(id_number))
self.__filename = filename
self.__dir = os.path.join(notebook_worksheet_directory, str(id_number))
if create_directories:
self.create_directories()
self.clear()
def increase_state_number(self):
if self.is_published() or self.docbrowser():
return
try:
self.__state_number += 1
except AttributeError:
self.__state_number = 0
def state_number(self):
if self.is_published() or self.docbrowser():
return 0
try:
return self.__state_number
except AttributeError:
self.__state_number = 0
return 0
def create_directories(self):
# creating directories should be a function of the storage backend, not here
if not os.path.exists(self.__dir):
os.makedirs(self.__dir)
set_restrictive_permissions(self.__dir, allow_execute=True)
set_restrictive_permissions(self.snapshot_directory())
set_restrictive_permissions(self.cells_directory())
def id_number(self):
"""
Return the id number of this worksheet, which is an integer.
EXAMPLES::
sage: from sagenb.notebook.worksheet import Worksheet
sage: W = Worksheet('test', 2, tmp_dir(), owner='sageuser')
sage: W.id_number()
2
sage: type(W.id_number())
<type 'int'>
"""
try:
return self.__id_number
except AttributeError:
self.__id_number = int(os.path.split(self.__filename)[1])
return self.__id_number
def basic(self):
"""
Output a dictionary of basic Python objects that defines the
configuration of this worksheet, except the actual cells and
the data files in the DATA directory and images and other data
in the individual cell directories.
EXAMPLES::
sage: import sagenb.notebook.worksheet
sage: W = sagenb.notebook.worksheet.Worksheet('test', 0, tmp_dir(), owner='sage')
sage: sorted((W.basic().items()))
[('auto_publish', False), ('collaborators', []), ('id_number', 0), ('last_change', ('sage', ...)), ('name', u'test'), ('owner', 'sage'), ('pretty_print', False), ('published_id_number', None), ('ratings', []), ('saved_by_info', {}), ('system', None), ('tags', {'sage': [1]}), ('viewers', []), ('worksheet_that_was_published', ('sage', 0))]
"""
try:
published_id_number = int(os.path.split(self.__published_version)[1])
except AttributeError:
published_id_number = None
try:
ws_pub = self.__worksheet_came_from
except AttributeError:
ws_pub = (self.owner(), self.id_number())
try:
saved_by_info = self.__saved_by_info
except AttributeError:
saved_by_info = {}
d = {#############
# basic identification
'name': unicode(self.name()),
'id_number': int(self.id_number()),
#############
# default type of computation system that evaluates cells
'system': self.system(),
#############
# permission: who can look at the worksheet
'owner': self.owner(),
'viewers': self.viewers(),
'collaborators': self.collaborators(),
#############
# publishing worksheets (am I published?); auto-publish me?
# If this worksheet is published, then the published_id_number
# is the id of the published version of this worksheet. Otherwise,
# it is None.
'published_id_number': published_id_number,
# If this is a published worksheet, then ws_pub
# is a 2-tuple ('username', id_number) of a non-published
# worksheet. Otherwise ws_pub is None.
'worksheet_that_was_published': ws_pub,
# Whether or not this worksheet should automatically be
# republished when changed.
'auto_publish': self.is_auto_publish(),
# Appearance: e.g., whether to pretty print this
# worksheet by default
'pretty_print': self.pretty_print(),
# what other users think of this worksheet: list of
# triples
# (username, rating, comment)
'ratings': self.ratings(),
#???
'saved_by_info':saved_by_info,
# dictionary mapping usernames to list of tags that
# reflect what the tages are for that user. A tag can be
# an integer:
# 0,1,2 (=ARCHIVED,ACTIVE,TRASH),
# or a string (not yet supported).
# This is used for now to fill in the __user_views.
'tags': self.tags(),
# information about when this worksheet was last changed,
# and by whom:
# last_change = ('username', time.time())
'last_change': self.last_change(),
}
return d
def reconstruct_from_basic(self, obj, notebook_worksheet_directory=None):
"""
Reconstruct as much of the worksheet's configuration as
possible from the properties that happen to be set in the
basic dictionary obj.
INPUT:
- ``obj`` -- a dictionary of basic Python objects
- ``notebook_worksheet_directory`` -- must be given if
``id_number`` is a key of obj; otherwise not.
EXAMPLES::
sage: import sagenb.notebook.worksheet
sage: W = sagenb.notebook.worksheet.Worksheet('test', 0, tmp_dir(), system='gap', owner='sageuser', pretty_print=True, auto_publish=True)
sage: W.new_cell_after(0)
Cell 1: in=, out=
sage: b = W.basic()
sage: W0 = sagenb.notebook.worksheet.Worksheet()
sage: W0.reconstruct_from_basic(b, tmp_dir())
sage: W0.basic() == W.basic()
True
"""
try:
del self.__cells
except AttributeError:
pass
for key, value in obj.iteritems():
if key == 'name':
if repr(value) == '<_LazyString broken>':
value = ''
self.set_name(value)
elif key == 'id_number':
self.__id_number = value
if 'owner' in obj:
owner = obj['owner']
self.__owner = owner
filename = os.path.join(owner, str(value))
self.__filename = filename
self.__dir = os.path.join(notebook_worksheet_directory, str(value))
elif key in ['system', 'owner', 'viewers', 'collaborators',
'pretty_print', 'ratings']:
# ugly
setattr(self, '_Worksheet__' + key, value)
elif key == 'auto_publish':
self.__autopublish = value
elif key == 'tags':
self.set_tags(value)
elif key == 'last_change':
self.set_last_change(value[0], value[1])
elif key == 'published_id_number' and value is not None:
self.set_published_version('pub/%s' % value)
elif key == 'worksheet_that_was_published':
self.set_worksheet_that_was_published(value)
self.create_directories()
def __cmp__(self, other):
"""
We compare two worksheets.
INPUT:
- ``self, other`` - worksheets
OUTPUT:
- ``-1,0,1`` - comparison is on the underlying
file names.
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W2 = nb.create_new_worksheet('test2', 'admin')
sage: W1 = nb.create_new_worksheet('test1', 'admin')
sage: cmp(W1, W2)
1
sage: cmp(W2, W1)
-1
"""
try:
return cmp(self.filename(), other.filename())
except AttributeError:
return cmp(type(self), type(other))
def __repr__(self):
r"""
Return string representation of this worksheet, which is simply the
string representation of the underlying list of cells.
OUTPUT: string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: W.__repr__()
'admin/0: [Cell 1: in=, out=]'
sage: W.edit_save('{{{\n2+3\n///\n5\n}}}\n{{{id=10|\n2+8\n///\n10\n}}}')
sage: W.__repr__()
'admin/0: [Cell 0: in=2+3, out=\n5, Cell 10: in=2+8, out=\n10]'
"""
return '%s/%s: %s' % (self.owner(), self.id_number(), self.cell_list())
def __len__(self):
r"""
Return the number of cells in this worksheet.
OUTPUT: int
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: len(W)
1
sage: W.edit_save('{{{\n2+3\n///\n5\n}}}\n{{{id=10|\n2+8\n///\n10\n}}}')
sage: len(W)
2
"""
return len(self.cell_list())
def worksheet_html_filename(self):
"""
Return path to the underlying plane text file that defines the
worksheet.
"""
return os.path.join(self.__dir, 'worksheet.html')
def download_name(self):
"""
Return the download name of this worksheet.
"""
return os.path.split(self.name())[-1]
def docbrowser(self):
"""
Return True if this is a docbrowser worksheet.
OUTPUT: bool
EXAMPLES: We first create a standard worksheet for which docbrowser
is of course False::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: nb.user_manager().add_user('_sage_', 'password', '', force=True)
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: W.docbrowser()
False
We create a worksheet for which docbrowser is True::
sage: W = nb.create_new_worksheet('doc_browser_0', '_sage_')
sage: W.docbrowser()
True
"""
return self.owner() == '_sage_'
##########################################################
# Basic properties
##########################################################
def collaborators(self):
"""
Return a (reference to the) list of the collaborators who can also
view and modify this worksheet.
OUTPUT: list
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: C = W.collaborators(); C
[]
sage: C.append('sage')
sage: W.collaborators()
['sage']
"""
try:
return self.__collaborators
except AttributeError:
self.__collaborators = []
return self.__collaborators
def collaborator_names(self, max=None):
"""
Returns a string of the non-owner collaborators on this worksheet.
INPUT:
- ``max`` - an integer. If this is specified, then
only max number of collaborators are shown.
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: C = W.collaborators(); C
[]
sage: C.append('sage')
sage: C.append('wstein')
sage: W.collaborator_names()
'sage, wstein'
sage: W.collaborator_names(max=1)
'sage, ...'
"""
collaborators = [x for x in self.collaborators() if x != self.owner()]
if max is not None and len(collaborators) > max:
collaborators = collaborators[:max] + ['...']
return ", ".join(collaborators)
def set_collaborators(self, v):
"""
Set the list of collaborators to those listed in the list v of
strings.
INPUT:
- ``v`` - a list of strings
EXAMPLES::
sage: nb = sagenb.notebook.notebook.load_notebook(tmp_dir()+'.sagenb')
sage: nb.user_manager().add_user('sage','sage','sage@sagemath.org',force=True)
sage: nb.user_manager().add_user('hilbert','sage','sage@sagemath.org',force=True)
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: W.set_collaborators(['sage', 'admin', 'hilbert', 'sage'])
Note that repeats are not added multiple times and admin - the
owner - isn't added::
sage: W.collaborators()
['hilbert', 'sage']
"""
users = self.notebook().user_manager().users()
owner = self.owner()
collaborators = set([u for u in v if u in users and u != owner])
self.__collaborators = sorted(collaborators)
def viewers(self):
"""
Return list of viewers of this worksheet.
OUTPUT:
- ``list`` - of string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: nb.user_manager().add_user('sage','sage','sage@sagemath.org',force=True)
sage: nb.user_manager().add_user('hilbert','sage','sage@sagemath.org',force=True)
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: W.add_viewer('hilbert')
sage: W.viewers()
['hilbert']
sage: W.add_viewer('sage')
sage: W.viewers()
['hilbert', 'sage']
"""
try:
return self.__viewers
except AttributeError:
self.__viewers = []
return self.__viewers
def viewer_names(self, max=None):
"""
Returns a string of the non-owner viewers on this worksheet.
INPUT:
- ``max`` - an integer. If this is specified, then
only max number of viewers are shown.
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: C = W.viewers(); C
[]
sage: C.append('sage')
sage: C.append('wstein')
sage: W.viewer_names()
'sage, wstein'
sage: W.viewer_names(max=1)
'sage, ...'
"""
viewers = [x for x in self.viewers() if x != self.owner()]
if max is not None and len(viewers) > max:
viewers = viewers[:max] + ['...']
return ", ".join(viewers)
def delete_notebook_specific_data(self):
"""
Delete data from this worksheet this is specific to a certain
notebook. This means deleting the attached files, collaborators,
and viewers.
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: nb.user_manager().add_user('hilbert','sage','sage@sagemath.org',force=True)
sage: W = nb.create_new_worksheet('test1', 'admin')
sage: W.add_viewer('hilbert')
sage: W.delete_notebook_specific_data()
sage: W.viewers()
[]
sage: W.add_collaborator('hilbert')
sage: W.collaborators()
['admin', 'hilbert']
sage: W.delete_notebook_specific_data()
sage: W.collaborators()
['admin']
"""
self.__attached = {}
self.__collaborators = [self.owner()]
self.__viewers = []
def name(self, username=None):
ur"""
Return the name of this worksheet.
OUTPUT: string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.name()
u'A Test Worksheet'
sage: W = nb.create_new_worksheet('ěščřžýáíéďĎ', 'admin')
sage: W.name()
u'\u011b\u0161\u010d\u0159\u017e\xfd\xe1\xed\xe9\u010f\u010e'
"""
try:
return self.__name
except AttributeError:
self.__name = gettext("Untitled")
return self.__name
def set_name(self, name):
"""
Set the name of this worksheet.
INPUT:
- ``name`` - string
EXAMPLES: We create a worksheet and change the name::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.set_name('A renamed worksheet')
sage: W.name()
u'A renamed worksheet'
"""
if len(name.strip()) == 0:
name = gettext('Untitled')
name = unicode_str(name)
self.__name = name
def set_filename_without_owner(self, nm):
r"""
Set this worksheet filename (actually directory) by getting the
owner from the pre-stored owner via ``self.owner()``.
INPUT:
- ``nm`` - string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.load_notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.filename()
'admin/0'
sage: W.set_filename_without_owner('5')
sage: W.filename()
'admin/5'
"""
filename = os.path.join(self.owner(), nm)
self.set_filename(filename)
def set_filename(self, filename):
"""
Set the worksheet filename (actually directory).
INPUT:
- ``filename`` - string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.load_notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.filename()
'admin/0'
sage: W.set_filename('admin/10')
sage: W.filename()
'admin/10'
"""
old_filename = self.__filename
self.__filename = filename
self.__dir = os.path.join(self.notebook()._dir, filename)
self.notebook().change_worksheet_key(old_filename, filename)
def filename(self):
"""
Return the filename (really directory) where the files associated
to this worksheet are stored.
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.filename()
'admin/0'
sage: os.path.isdir(os.path.join(nb._dir, 'home', W.filename()))
True
"""
return self.__filename
def filename_without_owner(self):
"""
Return the part of the worksheet filename after the last /, i.e.,
without any information about the owner of this worksheet.
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.filename_without_owner()
'0'
sage: W.filename()
'admin/0'
"""
return os.path.split(self.__filename)[-1]
def directory(self):
"""
Return the full path to the directory where this worksheet is
stored.
OUTPUT: string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.directory()
'.../home/admin/0'
"""
return self.__dir
def data_directory(self):
"""
Return path to directory where worksheet data is stored.
OUTPUT: string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.data_directory()
'.../home/admin/0/data'
"""
d = os.path.join(self.directory(), 'data')
if not os.path.exists(d):
os.makedirs(d)
return d
def attached_data_files(self):
"""
Return a list of the file names of files in the worksheet data
directory.
OUTPUT: list of strings
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.attached_data_files()
[]
sage: open('%s/foo.data'%W.data_directory(),'w').close()
sage: W.attached_data_files()
['foo.data']
"""
D = self.data_directory()
if not os.path.exists(D):
return []
return os.listdir(D)
def cells_directory(self):
"""
Return the directory in which the cells of this worksheet are
evaluated.
OUTPUT: string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.cells_directory()
'.../home/admin/0/cells'
"""
path = os.path.join(self.directory(), 'cells')
if not os.path.exists(path):
os.makedirs(path)
return path
def notebook(self):
"""
Return the notebook that contains this worksheet.
OUTPUT: a Notebook object.
.. note::
This really returns the Notebook object that is set as a
global variable of the misc module. This is done *even*
in the Flask version of the notebook as it is set in
func:`sagenb.notebook.notebook.load_notebook`.
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.notebook()
<...sagenb.notebook.notebook.Notebook...>
sage: W.notebook() is sagenb.notebook.misc.notebook
True
"""
if not hasattr(self, '_notebook'):
import misc
self._notebook = misc.notebook
return self._notebook
def save(self, conf_only=False):
self.notebook().save_worksheet(self, conf_only=conf_only)
def system(self):
"""
Return the math software system in which by default all input to
the notebook is evaluated.
OUTPUT: string
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.system()
'sage'
sage: W.set_system('mathematica')
sage: W.system()
'mathematica'
"""
try:
return self.__system
except AttributeError:
self.__system = 'sage'
return 'sage'
def system_index(self):
"""
Return the index of the current system into the Notebook's
list of systems. If the current system isn't in the list,
then change to the default system. This can happen if, e.g.,
the list changes, e.g., when changing from a notebook with
Sage installed to running a server from the same directory
without Sage installed. We might as well support this.
OUTPUT: integer
"""
S = self.system()
names = self.notebook().system_names()
if S not in names:
S = names[0]
self.set_system(S)
return 0
else:
return names.index(S)
def set_system(self, system='sage'):
"""
Set the math software system in which input is evaluated by
default.
INPUT:
- ``system`` - string (default: 'sage')
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.set_system('magma')
sage: W.system()
'magma'
"""
self.__system = system.strip()
def pretty_print(self):
"""
Return True if output should be pretty printed by default.
OUTPUT:
- ``bool`` - True of False
EXAMPLES::
sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir()+'.sagenb')
sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
sage: W.pretty_print()
False
sage: W.set_pretty_print('true')
sage: W.pretty_print()
True
sage: W.quit()
sage: nb.delete()
"""
try:
return self.__pretty_print
except AttributeError:
self.__pretty_print = False
return self.__pretty_print
def set_pretty_print(self, check='false'):
"""
Set whether or not output should be pretty printed by default.