This repository has been archived by the owner on Nov 19, 2019. It is now read-only.
/
notebook.py
2164 lines (1690 loc) · 73.9 KB
/
notebook.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
# This file is part of the OLD Sage notebook and is NOT actively developed,
# maintained, or supported. As of Sage v4.1.2, all notebook development has
# moved to the separate Sage Notebook project:
#
# http://nb.sagemath.org/
#
# The new notebook is installed in Sage as an spkg (e.g., sagenb-0.3.spkg).
#
# Please visit the project's home page for more information, including directions on
# obtaining the latest source code. For notebook-related development and support,
# please consult the sage-notebook discussion group:
#
# http://groups.google.com/group/sage-notebook
"""
The Sage Notebook object
"""
#############################################################################
# Copyright (C) 2006, 2007 William Stein <wstein@gmail.com>
# Distributed under the terms of the GNU General Public License (GPL)
# The full text of the GPL is available at:
# http://www.gnu.org/licenses/
#############################################################################
import os
import shutil
import time
import bz2
import cPickle
# Sage libraries
from sage.structure.sage_object import SageObject, load
from sage.misc.misc import (alarm, cancel_alarm,
tmp_dir, pad_zeros, cputime)
from sage.misc.package import is_package_installed
from sage.version import version
# Sage Notebook
import css # style
import js # javascript
import worksheet # individual worksheets (which make up a notebook)
import config # internal configuration stuff (currently, just keycodes)
import keyboards # keyboard layouts
import server_conf # server configuration
import user_conf # user configuration
import user # users
from template import template
from cgi import escape
# latex macros
from sage.misc.latex_macros import sage_jsmath_macros
SYSTEMS = ['sage', 'gap', 'gp', 'jsmath', 'html', 'latex', 'maxima', 'python', 'r', 'sage', 'sh', 'singular', 'axiom (optional)', 'giac (optional)', 'kash (optional)', 'macaulay2 (optional)', 'magma (optional)', 'maple (optional)', 'mathematica (optional)', 'matlab (optional)', 'mupad (optional)', 'octave (optional)']
# We also record the system names without (optional) since they are
# used in some of the html menus, etc.
SYSTEM_NAMES = [v.split()[0] for v in SYSTEMS]
JSMATH = True
if is_package_installed("jsmath-image-fonts"):
JSMATH_IMAGE_FONTS = True
else:
JSMATH_IMAGE_FONTS = False
if is_package_installed("tinyMCE"):
JEDITABLE_TINYMCE = True
else:
JEDITABLE_TINYMCE = False
vbar = '<span class="vbar"></span>'
DOC_TIMEOUT = 120
class Notebook(SageObject):
def __init__(self,
dir,
system=None,
pretty_print=False,
show_debug = False,
address='localhost',
port=8000,
secure=True,
server_pool = []):
if isinstance(dir, basestring) and len(dir) > 0 and dir[-1] == "/":
dir = dir[:-1]
self.__dir = dir
self.__absdir = os.path.abspath(dir)
self.__server_pool = server_pool
self.set_system(system)
self.set_pretty_print(pretty_print)
self.__worksheets = {}
self.__filename = '%s/nb.sobj'%dir
self.__worksheet_dir = '%s/worksheets'%dir
self.__object_dir = '%s/objects'%dir
self.__makedirs()
self.__history = []
self.__history_count = 0
self.__server_log = [] #server log list
self.__show_debug = show_debug
self.__admins = []
self.__conf = server_conf.ServerConfiguration()
# Install this copy of the notebook in twist.py as *the*
# global notebook object used for computations. This is
# mainly to avoid circular references, etc. This also means
# only one notebook can actually be used at any point.
import sage.server.notebook.twist
sage.server.notebook.twist.notebook = self
# This must happen after twist.notebook is set.
self.save()
def _migrate_worksheets(self):
v = []
for key, W in self.__worksheets.iteritems():
if not '/' in W.filename():
v.append((key, W))
if len(v) > 0:
print "Migrating from old to new worksheet format"
D = self.directory()
## if os.path.exists('%s/worksheets'%D):
## import shutil
## target = '%s/../old_worksheets.tar.bz2'%D
## print "First archiving old worksheets and objects directory to '%s'"%target
## os.system('tar jcf "%s" "%s/worksheets" "%s/objects"'%(target, D, D))
## ws_tree = "%s/worksheets"%D
## print "Now removing ", ws_tree
## shutil.rmtree(ws_tree)
## obj_tree = "%s/objects"%D
## if os.path.exists(obj_tree):
## shutil.rmtree(obj_tree)
for key, W in v:
print W.name()
txt = W.edit_text()
N = self.create_new_worksheet(W.name(), 'pub')
N.edit_save(txt, ignore_ids=True)
del self.__worksheets[key]
print "Your old worksheets are all available by clicking the published link"
print "in the upper right corner."
print "If you want to save disk space, you could immediately remove"
print "the objects and worksheets directories in your Sage notebook, as"
print "they are no longer used. Do this now or never."
def delete(self):
"""
Delete all files related to this notebook.
This is used for doctesting mainly. This command is obviously
*VERY* dangerous to use on a notebook you actually care about.
You could easily lose all data.
EXAMPLES::
sage: tmp = tmp_dir()
sage: nb = sage.server.notebook.notebook.Notebook(tmp)
sage: sorted(os.listdir(tmp))
['backups', 'nb.sobj', 'objects', 'worksheets']
sage: nb.delete()
Now the directory is gone.
::
sage: os.listdir(tmp)
Traceback (most recent call last):
...
OSError: [Errno 2] No such file or directory: '...
"""
try:
dir = self.__absdir
except AttributeError:
dir = self.__dir
import shutil
# We ignore_errors because in rare parallel doctesting
# situations sometimes the directory gets cleaned up too
# quickly, etc.
shutil.rmtree(dir, ignore_errors=True)
def systems(self):
return SYSTEMS
def system_names(self):
return SYSTEM_NAMES
##########################################################
# Users
##########################################################
def create_default_users(self, passwd):
"""
Create the default users for a notebook.
INPUT:
- ``passwd`` - a string
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: list(sorted(nb.users().iteritems()))
[('_sage_', _sage_), ('admin', admin), ('guest', guest), ('pub', pub)]
sage: list(sorted(nb.passwords().iteritems()))
[('_sage_', 'aaQSqAReePlq6'), ('admin', 'aajfMKNH1hTm2'), ('guest', 'aaQSqAReePlq6'), ('pub', 'aaQSqAReePlq6')]
sage: nb.create_default_users('newpassword')
Creating default users.
WARNING: User 'pub' already exists -- and is now being replaced.
WARNING: User '_sage_' already exists -- and is now being replaced.
WARNING: User 'guest' already exists -- and is now being replaced.
WARNING: User 'admin' already exists -- and is now being replaced.
sage: list(sorted(nb.passwords().iteritems()))
[('_sage_', 'aaQSqAReePlq6'), ('admin', 'aajH86zjeUSDY'), ('guest', 'aaQSqAReePlq6'), ('pub', 'aaQSqAReePlq6')]
"""
print "Creating default users."
self.add_user('pub', '', '', account_type='user', force=True)
self.add_user('_sage_', '', '', account_type='user', force=True)
self.add_user('guest', '', '', account_type='guest', force=True)
self.add_user('admin', passwd, '', account_type='admin', force=True)
def user_exists(self, username):
"""
Return whether a user with the given ``username`` exists.
INPUT:
- ``username`` - a string
OUTPUT:
- a bool
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: nb.user_exists('admin')
True
sage: nb.user_exists('pub')
True
sage: nb.user_exists('mark')
False
sage: nb.user_exists('guest')
True
"""
return username in self.users()
def users(self):
"""
Return a dictionary of users in a notebook.
OUTPUT:
- a string:User instance dictionary
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: list(sorted(nb.users().iteritems()))
[('_sage_', _sage_), ('admin', admin), ('guest', guest), ('pub', pub)]
"""
try:
return self.__users
except AttributeError:
self.__users = {}
return self.__users
def user(self, username):
"""
Return an instance of the User class given the ``username`` of a user
in a notebook.
INPUT:
- ``username`` - a string
OUTPUT:
- an instance of User
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: nb.user('admin')
admin
sage: nb.user('admin')._User__email
''
sage: nb.user('admin')._User__password
'aajfMKNH1hTm2'
"""
if not isinstance(username, str) or '/' in username:
raise KeyError, "no user '%s'"%username
try:
return self.users()[username]
except KeyError:
if username in ['pub', '_sage_']:
self.add_user(username, '', '', account_type='user', force=True)
return self.users()[username]
elif username == 'admin':
self.add_user(username, '', '', account_type='admin', force=True)
return self.users()[username]
elif username == 'guest':
self.add_user('guest', '', '', account_type='guest', force=True)
return self.users()[username]
raise KeyError, "no user '%s'"%username
def create_user_with_same_password(self, user, other_user):
r"""
Change the password of ``user`` to that of ``other_user``.
INPUT:
- ``user`` - a string
- ``other_user`` - a string
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('bob', 'an**d', 'bob@gmail.com', force=True)
sage: nb.user('bob').password()
'aa4Q6Jbx/MiUs'
sage: nb.add_user('mary', 'ccd', 'mary@gmail.com', force=True)
sage: nb.user('mary').password()
'aaxr0gcWJMXKU'
sage: nb.create_user_with_same_password('bob', 'mary')
sage: nb.user('bob').password() == nb.user('mary').password()
True
"""
U = self.user(user)
O = self.user(other_user)
passwd = O.password()
U.set_hashed_password(passwd)
def user_is_admin(self, user):
"""
Return True if ``user`` is an admin.
INPUT:
- ``user`` - an instance of User
OUTPUT:
- a bool
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('Administrator', 'password', '', 'admin', True)
sage: nb.add_user('RegularUser', 'password', '', 'user', True)
sage: nb.user_is_admin('Administrator')
True
sage: nb.user_is_admin('RegularUser')
False
"""
return self.user(user).is_admin()
def user_is_guest(self, username):
"""
Return True if ``username`` is a guest.
INPUT:
- ``username`` - a string
OUTPUT:
- a bool
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: nb.user_is_guest('guest')
True
sage: nb.user_is_guest('admin')
False
"""
try:
return self.user(username).is_guest()
except KeyError:
return False
def user_list(self):
"""
Return a list of user objects.
OUTPUT:
- a list of User instances
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: sorted(nb.user_list(), key=lambda k: k.username())
[_sage_, admin, guest, pub]
"""
return list(self.users().itervalues())
def usernames(self):
"""
Return a list of usernames.
OUTPUT:
- a list of strings
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: sorted(nb.usernames())
['_sage_', 'admin', 'guest', 'pub']
"""
U = self.users()
return U.keys()
def valid_login_names(self):
"""
Return a list of users that can log in.
OUTPUT:
- a list of strings
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: nb.valid_login_names()
['admin']
sage: nb.add_user('Mark', 'password', '', force=True)
sage: nb.add_user('Sarah', 'password', '', force=True)
sage: nb.add_user('David', 'password', '', force=True)
sage: sorted(nb.valid_login_names())
['David', 'Mark', 'Sarah', 'admin']
"""
return [x for x in self.usernames() if not x in ['guest', '_sage_', 'pub']]
def default_user(self):
r"""
Return a default login name that the user will see when
confronted with the Sage notebook login page. Currently, this
returns 'admin' if that is the *only* user. Otherwise it
returns an empty string ('').
OUTPUT:
- a string - the default username.
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: nb.default_user()
'admin'
sage: nb.add_user('AnotherUser', 'password', '', force=True)
sage: nb.default_user()
''
"""
if self.valid_login_names() == ['admin']:
return 'admin'
else:
return ''
def set_accounts(self, value):
r"""
Set the attribute ``__accounts`` to ``value``.
INPUT:
- ``value`` - a bool
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.get_accounts()
False
sage: nb.set_accounts(True)
sage: nb.get_accounts()
True
sage: nb.set_accounts(False)
sage: nb.get_accounts()
False
"""
self.__accounts = value
def get_accounts(self):
r"""
Return ``__accounts``.
OUTPUT:
- a bool
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.get_accounts()
False
sage: nb.set_accounts(True)
sage: nb.get_accounts()
True
"""
try:
return self.__accounts
except AttributeError:
self.__accounts = False
return False
def add_user(self, username, password, email, account_type="user", force=False):
"""
Add a user with the given credentials.
INPUT:
- ``username`` - the username
- ``password`` - the password
- ``email`` - the email address
- ``account_type`` - one of 'user', 'admin', or 'guest'
- ``force`` - a bool (default: False)
If the method :meth:`get_accounts` returns False then user can
only be added if ``force`` is True.
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('Mark', 'password', '', force=True)
sage: nb.user('Mark')
Mark
sage: nb.add_user('Sarah', 'password', ")
Traceback (most recent call last):
ValueError: creating new accounts disabled.
sage: nb.set_accounts(True)
sage: nb.add_user('Sarah', 'password', ")
sage: nb.user('Sarah')
Sarah
"""
if not self.get_accounts() and not force:
raise ValueError, "creating new accounts disabled."
us = self.users()
if us.has_key(username):
print "WARNING: User '%s' already exists -- and is now being replaced."%username
U = user.User(username, password, email, account_type)
us[username] = U
def change_password(self, username, password):
"""
Change a user's password.
INPUT:
- ``username`` - a string, the username
- ``password`` - a string, the user's new password
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('Mark', 'password', '', force=True)
sage: nb.user('Mark').password()
'aajfMKNH1hTm2'
sage: nb.change_password('Mark', 'different_password')
sage: nb.user('Mark').password()
'aaTlXok5npQME'
"""
self.user(username).set_password(password)
def del_user(self, username):
"""
Delete the given user.
INPUT:
- ``username`` - a string
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('Mark', 'password', '', force=True)
sage: nb.user('Mark')
Mark
sage: nb.del_user('Mark')
sage: nb.user('Mark')
Traceback (most recent call last):
KeyError: "no user 'Mark'"
"""
us = self.users()
if us.has_key(username):
del us[username]
def passwords(self):
"""
Return a username:password dictionary.
OUTPUT:
- a string:string dictionary
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: nb.add_user('Mark', 'password', '', force=True)
sage: list(sorted(nb.passwords().iteritems()))
[('Mark', 'aajfMKNH1hTm2'), ('_sage_', 'aaQSqAReePlq6'), ('admin', 'aajfMKNH1hTm2'), ('guest', 'aaQSqAReePlq6'), ('pub', 'aaQSqAReePlq6')]
"""
return dict([(user.username(), user.password()) for user in self.user_list()])
def user_conf(self, username):
"""
Return a user's configuration object.
OUTPUT:
- an instance of Configuration.
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.create_default_users('password')
Creating default users.
sage: config = nb.user_conf('admin')
sage: config['max_history_length']
1000
sage: config['default_system']
'sage'
sage: config['autosave_interval']
3600
sage: config['default_pretty_print']
False
"""
return self.users()[username].conf()
##########################################################
# Publishing worksheets
##########################################################
def _initialize_worksheet(self, src, W):
r"""
Initialize a new worksheet from a source worksheet.
INPUT:
- ``src`` - a Worksheet instance; the source
- ``W`` - a new Worksheet instance; the target
"""
# Copy over images and other files
data = src.data_directory()
if os.path.exists(data):
shutil.copytree(data, W.directory() + '/data')
cells = src.cells_directory()
if os.path.exists(cells):
shutil.copytree(cells, W.directory() + '/cells')
W.edit_save(src.edit_text())
def publish_worksheet(self, worksheet, username):
r"""
Publish a user's worksheet. This creates a new worksheet in
the 'pub' directory with the same contents as ``worksheet``.
INPUT:
- ``worksheet`` - an instance of Worksheet
- ``username`` - a string
OUTPUT:
- a new or existing published instance of Worksheet
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('Mark','password','',force=True)
sage: W = nb.new_worksheet_with_title_from_text('First steps', owner='Mark')
sage: nb.worksheet_names()
['Mark/0']
sage: nb.publish_worksheet(nb.get_worksheet_with_filename('Mark/0'), 'Mark')
<BLANKLINE>
[Cell 0; in=, out=]
sage: sorted(nb.worksheet_names())
['Mark/0', 'pub/0']
"""
for X in self.__worksheets.itervalues():
if X.is_published() and X.worksheet_that_was_published() == worksheet:
# Update X based on worksheet instead of creating something new
# 1. delete cells and data directories
# 2. copy them over
# 3. update worksheet text
if os.path.exists(X.data_directory()):
shutil.rmtree(X.data_directory(), ignore_errors=True)
if os.path.exists(X.cells_directory()):
shutil.rmtree(X.cells_directory(), ignore_errors=True)
if os.path.exists(X.snapshot_directory()):
shutil.rmtree(X.snapshot_directory(), ignore_errors=True)
self._initialize_worksheet(worksheet, X)
X.set_worksheet_that_was_published(worksheet)
X.move_to_archive(username)
worksheet.set_published_version(X.filename())
X.record_edit(username)
return X
# Have to create a new worksheet
W = self.create_new_worksheet(worksheet.name(), 'pub')
self._initialize_worksheet(worksheet, W)
W.set_worksheet_that_was_published(worksheet)
W.move_to_archive(username)
worksheet.set_published_version(W.filename())
return W
##########################################################
# Moving, copying, creating, renaming, and listing worksheets
##########################################################
def scratch_worksheet(self):
try:
return self.__scratch_worksheet
except AttributeError:
W = self.create_new_worksheet('scratch', '_sage_', add_to_list=False)
self.__scratch_worksheet = W
return W
def create_new_worksheet(self, worksheet_name, username, docbrowser=False, add_to_list=True):
if username!='pub' and self.user_is_guest(username):
raise ValueError, "guests cannot create new worksheets"
filename = worksheet.worksheet_filename(worksheet_name, username)
if self.__worksheets.has_key(filename):
return self.__worksheets[filename]
i = 0
dir = self.worksheet_directory() + '/' + username
if os.path.exists(dir):
D = os.listdir(dir)
D.sort()
dirname = str(i)
while dirname in D:
i += 1
dirname = str(i)
else:
dirname = '0'
W = worksheet.Worksheet(worksheet_name, dirname, self.worksheet_directory(),
system = self.system(username),
owner=username,
docbrowser = docbrowser,
auto_publish = False)
if add_to_list:
self.__worksheets[W.filename()] = W
return W
def copy_worksheet(self, ws, owner):
W = self.create_new_worksheet('default', owner)
self._initialize_worksheet(ws, W)
name = "Copy of %s"%ws.name()
W.set_name(name)
return W
def delete_worksheet(self, filename):
"""
Delete the given worksheet and remove its name from the worksheet
list. Raise a KeyError, if it is missing.
INPUT:
- ``filename`` - a string
"""
if not (filename in self.__worksheets.keys()):
print self.__worksheets.keys()
raise KeyError, "Attempt to delete missing worksheet '%s'"%filename
W = self.__worksheets[filename]
W.quit()
shutil.rmtree(W.directory(), ignore_errors=True)
self.deleted_worksheets()[filename] = W
del self.__worksheets[filename]
def deleted_worksheets(self):
try:
return self.__deleted_worksheets
except AttributeError:
self.__deleted_worksheets = {}
return self.__deleted_worksheets
def empty_trash(self, username):
"""
Empty the trash for the given user.
INPUT:
- ``username`` - a string
This empties the trash for the given user and cleans up all files
associated with the worksheets that are in the trash.
EXAMPLES::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('sage','sage','sage@sagemath.org',force=True)
sage: W = nb.new_worksheet_with_title_from_text('Sage', owner='sage')
sage: W.move_to_trash('sage')
sage: nb.worksheet_names()
['sage/0']
sage: nb.empty_trash('sage')
sage: nb.worksheet_names()
[]
"""
X = self.get_worksheets_with_viewer(username)
X = [W for W in X if W.is_trashed(username)]
for W in X:
W.delete_user(username)
if W.owner() is None:
self.delete_worksheet(W.filename())
def worksheet_names(self):
"""
Return a list of all the names of worksheets in this notebook.
OUTPUT:
- a list of strings.
EXAMPLES:
We make a new notebook with two users and two worksheets,
then list their names::
sage: nb = sage.server.notebook.notebook.Notebook(tmp_dir())
sage: nb.add_user('sage','sage','sage@sagemath.org',force=True)
sage: W = nb.new_worksheet_with_title_from_text('Sage', owner='sage')
sage: nb.add_user('wstein','sage','wstein@sagemath.org',force=True)
sage: W2 = nb.new_worksheet_with_title_from_text('Elliptic Curves', owner='wstein')
sage: nb.worksheet_names()
['sage/0', 'wstein/0']
"""
W = self.__worksheets.keys()
W.sort()
return W
def migrate_old(self):
"""
Migrate all old worksheets, i.e., those with no owner, to
``/pub``. Currently, this always raises a
NotImplementedError.
"""
raise NotImplementedError
for w in self.__worksheets.itervalues():
if not '/' in w.filename():
print "Moving worksheet ", w.name()
w.set_owner('old')
self.rename_worksheet_filename(w, w.filename())
##########################################################
# Information about the pool of worksheet compute servers
##########################################################
def server_pool(self):
try:
return self.__server_pool
except AttributeError:
self.__server_pool = []
return []
def set_server_pool(self, servers):
self.__server_pool = servers
def get_ulimit(self):
try:
return self.__ulimit
except AttributeError:
self.__ulimit = ''
return ''
def set_ulimit(self, ulimit):
self.__ulimit = ulimit
def get_server(self):
P = self.server_pool()
if P is None or len(P) == 0:
return None
try:
self.__server_number = (self.__server_number + 1)%len(P)
i = self.__server_number
except AttributeError:
self.__server_number = 0
i = 0
return P[i]
##########################################################
# The default math software system for new worksheets for
# a given user or the whole notebook (if username is None).
##########################################################
# TODO -- only implemented for the notebook right now
def system(self, username=None):
return self.user(username).conf()['default_system']
def set_system(self, system):
self.__system = system
##########################################################
# The default typeset setting for new worksheets for
# a given user or the whole notebook (if username is None).
##########################################################
# TODO -- only implemented for the notebook right now
def pretty_print(self, username=None):
return self.user(username).conf()['default_pretty_print']
def set_pretty_print(self, pretty_print):
self.__pretty_print = pretty_print
##########################################################
# The default color scheme for the notebook.
##########################################################
def color(self):
try:
return self.__color
except AttributeError:
self.__color = 'default'
return self.__color
def set_color(self,color):
self.__color = color
##########################################################
# The directory the notebook runs in.
##########################################################
def set_directory(self, dir):
if dir == self.__dir:
return
if isinstance(dir, basestring) and len(dir) > 0 and dir[-1] == "/":
dir = dir[:-1]
self.__dir = dir
self.__filename = '%s/nb.sobj'%dir
self.__worksheet_dir = '%s/worksheets'%dir
self.__object_dir = '%s/objects'%dir
##########################################################
# The notebook history.
##########################################################
def user_history(self, username):
U = self.user(username)
return U.history_list()
def create_new_worksheet_from_history(self, name, username, maxlen=None):
W = self.create_new_worksheet(name, username)
W.edit_save('Log Worksheet\n' + self.user_history_text(username, maxlen=None))
return W
def user_history_text(self, username, maxlen=None):
H = self.user_history(username)
if maxlen:
H = H[-maxlen:]
return '\n\n'.join([L.strip() for L in H])
def add_to_user_history(self, entry, username):
H = self.user_history(username)
H.append(entry)
maxlen = self.user_conf(username)['max_history_length']
while len(H) > maxlen:
del H[0]
def add_to_history(self, input_text):
H = self.history()
H.append(input_text)
while len(H) > self.max_history_length():
del H[0]
def history_count_inc(self):
self.__history_count += 1
def history_count(self):
return self.__history_count
def history(self):
try:
s = self.__history
except AttributeError: