/
editor.html~
275 lines (227 loc) · 8.65 KB
/
editor.html~
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
<!-- 導入 FileSaver 與 filereader -->
<script type="text/javascript" src="./ace/FileSaver.min.js"></script>
<script type="text/javascript" src="./ace/filereader.js"></script>
<!-- 導入 Brython 標準程式庫 -->
<!-- <script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/master/www/src/brython_dist.js">
</script> -->
<!-- 為了讓 import script1 可以正確運行, 停留在 Brython 3.2.9 版 -->
<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/3.2.9/www/src/brython_dist.js">
</script>
<!-- 啟動 Brython -->
<script>
window.onload=function(){
brython(1);
}
</script>
<!-- 以下執行 Brython 程式 -->
列出 2017 Spring 協同產品設計實習課程日期之 Python 程式碼如下:
<pre class="brush: python">
<div id="cal2"></div>
<script type="text/python3">
from browser import document, html
import calendar
import locale
cal2 = document["cal2"]
def getClassdate(year=2017, startM=2, startD=20, w=0, note=""):
# w=0 表示課程排在星期一
# startM 表示開學月份, startD 表示開學日
# note 為課程初始告示
# default calendar MONDAY is the first day of the week
# 每學期共有 18 週
totalW = 18
count = 0
# output = "2017 Spring 2bCD (三) 08:10-12:00 各週上課日期: "
output = note + html.BR()
# 若必須全年搜尋則 7 改為 12, 但是因為只有 18 週, 因此邏輯要修改讓程式較快結束
for month in range(startM, 7):
monthArray = calendar.monthcalendar(2017, month)
for week in range(len(monthArray)):
weekArray = monthArray[week]
# 只需要列出星期 (w+1)
if weekArray[w] != 0:
if month == startM:
if weekArray[startM] > startD:
count += 1
if count <= totalW:
if month == 3 and weekArray[w] == 31:
output += "w"+str(count)+"-"+ str(month)+ "/" + str(weekArray[w]) + "(放假), "
else:
output += "w"+str(count)+"-"+ str(month)+ "/" + str(weekArray[w]) + ", "
else:
count += 1
if count <= totalW:
if month == 3 and weekArray[w] == 31:
output += "w"+str(count)+"-"+ str(month)+ "/" + str(weekArray[w]) + "(放假), "
else:
output += "w"+str(count)+"-"+ str(month)+ "/" + str(weekArray[w]) + ", "
cal2 <= output
# 2b 協同產品設計實習 (三 w=2)
getClassdate(year=2017, startM=2, startD=20, w=2, note="2017 Spring 2bCD (三) 08:10-12:00 各週上課日期: ")
cal2 <= html.BR() + html.BR()
# 2a 協同產品設計實習 (四 w=3)
getClassdate(year=2017, startM=2, startD=20, w=3, note="2017 Spring 2aCD (四) 08:10-12:00 各週上課日期: ")
cal2 <= html.BR() + html.BR()
# 1a 網際內容管理 (五 w=4)
getClassdate(year=2017, startM=2, startD=20, w=4, note="2017 Spring 1aWCM (五) 13:20-16:10 各週上課日期: ")
cal2 <= html.BR() + html.BR()
# VE1a 網際內容管理 (五 w=4)
getClassdate(year=2017, startM=2, startD=20, w=4, note="2017 Spring VE1aCP (五) 18:30-20:00 各週上課日期: ")
cal2 <= html.BR() + html.BR()
</script>
</pre>
### 利用伺服器執行 Python3 程式
Jupyterhub: <a href="https://8888.kmol.info:9443">https://8888.kmol.info:9443</a>
### 利用以下的編輯器執行 Python3 程式
在 Firefox 中, 以 Preferences - General - Downloads 選擇"Always ask me where to save files"
在 Chrome 中, 以 Settings - Advanced - Downloads 選擇 Ask where to save each file before downloading
<script src="./ace/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="./ace/ext-language_tools.js" type="text/javascript" charset="utf-8"></script>
<script src="./ace/mode-python3.js" type="text/javascript" charset="utf-8"></script>
<script src="./ace/snippets/python.js" type="text/javascript" charset="utf-8"></script>
<!-- 請注意, 這裡使用 Javascript 將 localStorage["py_src"] 中存在近端瀏覽器的程式碼, 由使用者決定存檔名稱-->
<script type="text/javascript">
function doSave(){
var blob = new Blob([localStorage["py_src"]], {type: "text/plain;charset=utf-8"});
filename = document.getElementById('filename').value
saveAs(blob, filename+".py");
}
</script>
<script type="text/python3" id="script1">
import sys
import time
import traceback
import javascript
from browser import document as doc, window, alert
has_ace = True
try:
editor = window.ace.edit("editor")
session = editor.getSession()
session.setMode("ace/mode/python")
editor.setOptions({
'enableLiveAutocompletion': True,
'enableSnippets': True,
'highlightActiveLine': False,
'highlightSelectedWord': True
})
except:
from browser import html
editor = html.TEXTAREA(rows=20, cols=70)
doc["editor"] <= editor
def get_value(): return editor.value
def set_value(x):editor.value = x
editor.getValue = get_value
editor.setValue = set_value
has_ace = False
if hasattr(window, 'localStorage'):
from browser.local_storage import storage
else:
storage = None
def reset_src():
if storage is not None and "py_src" in storage:
editor.setValue(storage["py_src"])
else:
editor.setValue('for i in range(10):\n\tprint(i)')
editor.scrollToRow(0)
editor.gotoLine(0)
def reset_src_area():
if storage and "py_src" in storage:
editor.value = storage["py_src"]
else:
editor.value = 'for i in range(10):\n\tprint(i)'
class cOutput:
def __init__(self,target):
self.target = doc[target]
def write(self,data):
self.target.value += str(data)
#if "console" in doc:
sys.stdout = cOutput("console")
sys.stderr = cOutput("console")
def to_str(xx):
return str(xx)
info = sys.implementation.version
doc['version'].text = 'Brython %s.%s.%s' % (info.major, info.minor, info.micro)
output = ''
def show_console(ev):
doc["console"].value = output
doc["console"].cols = 60
doc["console"].rows = 10
# load a Python script
def load_script(evt):
_name = evt.target.value + '?foo=%s' % time.time()
editor.setValue(open(_name).read())
# run a script, in global namespace if in_globals is True
def run(*args):
global output
doc["console"].value = ''
src = editor.getValue()
if storage is not None:
storage["py_src"] = src
t0 = time.perf_counter()
try:
#ns = {'__name__':'__main__'}
ns = {'__name__':'editor'}
exec(src, ns)
state = 1
except Exception as exc:
traceback.print_exc(file=sys.stderr)
state = 0
output = doc["console"].value
print('<completed in %6.2f ms>' % ((time.perf_counter() - t0) * 1000.0))
return state
if has_ace:
reset_src()
else:
reset_src_area()
def clear_console(ev):
doc["console"].value = ""
doc['run'].bind('click',run)
doc['show_console'].bind('click',show_console)
doc['clear_console'].bind('click',clear_console)
</script>
<div id="version"></div>
<div id="editor" style="width:600px;height:300px;"></div>
<!-- 以下的表單與按鈕與前面的 Javascript doSave 函式以及 FileSaver.min.js 互相配合 -->
<form>
<label>Filename: <input type="text" id="filename" placeholder="input file name"/>.py</label>
<input type="submit" value="Save" onclick="doSave();"/>
</form>
<button id="run">Run</button>
<button id="show_console">Output</button>
<button id="clear_console">清除</button>
<div style="width:100%;height:100%;">
<textarea id="console" autocomplete="off"></textarea>
</div>
<div id="common"></div>
<script type="text/python3">
from browser import document as doc
import script1
def ex1(ev):
script1.editor.setValue('''#ex1 簡單的 for 迴圈範例
for i in range(10):
print(i)
''')
script1.editor.scrollToRow(0)
script1.editor.gotoLine(0)
doc['ex1'].bind('click',ex1)
</script><a id="ex1">ex1</a>-for 迴圈
<script type="text/python3">
from browser import document as doc
import script1
def ex2(ev):
script1.editor.setValue('''#溫度轉換程式
from browser import document as doc
# 因為此函式與滑鼠互動, 需要 event 當作輸入
def convTemp():
mystring = ""
cdegree = input("請輸入攝氏溫度:")
fdegree = float(cdegree)*9/5 + 32
output_string = "攝氏 " + str(cdegree) + "度=華氏 " + str(fdegree) + "度"
# 利用 print() 將轉換結果送到 console 區
print(output_string)
#直接呼叫 convTemp() 執行
convTemp()
''')
script1.editor.scrollToRow(0)
script1.editor.gotoLine(0)
doc['ex2'].bind('click',ex2)
</script><a id="ex2">ex2</a>-溫度換算