網際內容管理第六組

頁面編輯 << Previous Next >> 網際簡報

插入程式碼

CMSimfly 目前使用 Syntaxhighlighter 3.0.83:

 http://alexgorbatchev.com/SyntaxHighlighter/ 

進行頁面中的程式碼高亮顯示.

Java 程式碼

import java.util.Scanner;

public class Life {
    public static void show(boolean[][] grid){
        String s = "";
        for(boolean[] row : grid){
            for(boolean val : row)
                if(val)
                    s += "*";
                else
                    s += ".";
            s += "\n";
        }
        System.out.println(s);
    }
    
    public static boolean[][] gen(){
        boolean[][] grid = new boolean[10][10];
        for(int r = 0; r < 10; r++)
            for(int c = 0; c < 10; c++)
                if( Math.random() > 0.7 )
                    grid[r][c] = true;
        return grid;
    }
    
    public static void main(String[] args){
        boolean[][] world = gen();
        show(world);
        System.out.println();
        world = nextGen(world);
        show(world);
        Scanner s = new Scanner(System.in);
        while(s.nextLine().length() == 0){
            System.out.println();
            world = nextGen(world);
            show(world);
            
        }
    }
    
    public static boolean[][] nextGen(boolean[][] world){
        boolean[][] newWorld 
            = new boolean[world.length][world[0].length];
        int num;
        for(int r = 0; r < world.length; r++){
            for(int c = 0; c < world[0].length; c++){
                num = numNeighbors(world, r, c);
                if( occupiedNext(num, world[r][c]) )
                    newWorld[r][c] = true;
            }
        }
        return newWorld;
    }
    
    public static boolean occupiedNext(int numNeighbors, boolean occupied){
        if( occupied && (numNeighbors == 2 || numNeighbors == 3))
            return true;
        else if (!occupied && numNeighbors == 3)
            return true;
        else
            return false;
    }

    private static int numNeighbors(boolean[][] world, int row, int col) {
        int num = world[row][col] ? -1 : 0;
        for(int r = row - 1; r <= row + 1; r++)
            for(int c = col - 1; c <= col + 1; c++)
                if( inbounds(world, r, c) && world[r][c] )
                    num++;

        return num;
    }

    private static boolean inbounds(boolean[][] world, int r, int c) {
        return r >= 0 && r < world.length && c >= 0 &&
        c < world[0].length;
    }

}

Python 程式碼

def parse_content():
    """use bs4 and re module functions to parse content.htm"""
    #from pybean import Store, SQLiteWriter
    # if no content.db, create database file with cms table
    '''
    if not os.path.isfile(config_dir+"content.db"):
        library = Store(SQLiteWriter(config_dir+"content.db", frozen=False))
        cms = library.new("cms")
        cms.follow = 0
        cms.title = "head 1"
        cms.content = "content 1"
        cms.memo = "first memo"
        library.save(cms)
        library.commit()
    '''
    # if no content.htm, generate a head 1 and content 1 file
    if not os.path.isfile(config_dir+"content.htm"):
        # create content.htm if there is no content.htm
        File = open(config_dir + "content.htm", "w", encoding="utf-8")
        File.write("<h1>head 1</h1>content 1")
        File.close()
    subject = file_get_contents(config_dir+"content.htm")
    # deal with content without content
    if subject == "":
        # create content.htm if there is no content.htm
        File = open(config_dir + "content.htm", "w", encoding="utf-8")
        File.write("<h1>head 1</h1>content 1")
        File.close()
        subject = "<h1>head 1</h1>content 1"
    # initialize the return lists
    head_list = []
    level_list = []
    page_list = []
    # make the soup out of the html content
    soup = bs4.BeautifulSoup(subject, 'html.parser')
    # 嘗試解讀各種情況下的標題
    soup = _remove_h123_attrs(soup)
    # 改寫 content.htm 後重新取 subject
    with open(config_dir + "content.htm", "wb") as f:
        f.write(soup.encode("utf-8"))
    subject = file_get_contents(config_dir+"content.htm")
    # get all h1, h2, h3 tags into list
    htag= soup.find_all(['h1', 'h2', 'h3'])
    n = len(htag)
    # get the page content to split subject using each h tag
    temp_data = subject.split(str(htag[0]))
    if len(temp_data) > 2:
        subject = str(htag[0]).join(temp_data[1:])
    else:
        subject = temp_data[1]
    if n >1:
            # i from 1 to i-1
            for i in range(1, len(htag)):
                head_list.append(htag[i-1].text.strip())
                # use name attribute of h* tag to get h1, h2 or h3
                # the number of h1, h2 or h3 is the level of page menu
                level_list.append(htag[i-1].name[1])
                temp_data = subject.split(str(htag[i]))
                if len(temp_data) > 2:
                    subject = str(htag[i]).join(temp_data[1:])
                else:
                    subject = temp_data[1]
                # cut the other page content out of htag from 1 to i-1
                cut = temp_data[0]
                # add the page content
                page_list.append(cut)
    # last i
    # add the last page title
    head_list.append(htag[n-1].text.strip())
    # add the last level
    level_list.append(htag[n-1].name[1])
    temp_data = subject.split(str(htag[n-1]))
    # the last subject
    subject = temp_data[0]
    # cut the last page content out
    cut = temp_data[0]
    # the last page content
    page_list.append(cut)
    return head_list, level_list, page_list

C或C++程式碼

請注意, 目前 CMSimfly 標題內文無法解讀 "/" 符號, 因此若本頁面的標題為  "C/C++程式碼", 則無法進行分頁.

/* Runge Kutta for a set of first order differential equations */
 
#include <stdio.h>
#include <math.h>
 
#define N 2 /* number of first order equations */
#define dist 0.1 /* stepsize in t*/
#define MAX 30.0 /* max for t */
 
FILE *output; /* internal filename */
FILE *output1; /* internal filename */
// 利用 pipe 呼叫 gnuplot 繪圖
FILE *pipe;
 
void runge4(double x, double y[], double step); /* Runge-Kutta function */
double f(double x, double y[], int i); /* function for derivatives */
 
void main(){
 
  double t, y[N];
  int j;
 
  output=fopen("osc.dat", "w"); /* external filename */
  output1=fopen("osc1.dat", "w"); /* external filename */
 
  y[0]=1.0; /* initial position */
  y[1]=0.0; /* initial velocity */
 
  //fprintf(output, "0\t%f\n", y[0]);
 
  for (j=1; j*dist<=MAX ;j++) /* time loop */{
 
    t=j*dist;
    runge4(t, y, dist);
    fprintf(output, "%f\t%f\n", t, y[0]);
    fprintf(output1, "%f\t%f\n", t, y[1]);
  }
 
  fclose(output);
  fclose(output1);
 
  pipe = popen("gnuplot -persist","w");
  //fprintf(pipe,"set term png enhanced font \"v:/fireflysung.ttf\" 18 \n");
  fprintf(pipe,"set term png enhanced font \"y:/wqy-microhei.ttc\" 18 \n");
  //fprintf(pipe,"set yrange [68:70]\n");
  fprintf(pipe,"set output \"test.png\"\n");
  fprintf(pipe, "plot \"osc.dat\" title \"位移\" with lines, \"osc1.dat\" title \"速度\" with lines\n");
  fprintf(pipe,"quit\n");

  fprintf(pipe,"quit\n");
  pclose(pipe);
}
 
void runge4(double x, double y[], double step){
 
  double h=step/2.0, /* the midpoint */
  t1[N], t2[N], t3[N], /* temporary storage arrays */
  k1[N], k2[N], k3[N],k4[N]; /* for Runge-Kutta */
  int i;
 
  for (i=0;i<N;i++){
 
    t1[i]=y[i]+0.5*(k1[i]=step*f(x,y,i));
  }
 
  for (i=0;i<N;i++){
 
    t2[i]=y[i]+0.5*(k2[i]=step*f(x+h, t1, i));
  }
 
  for (i=0;i<N;i++){
 
    t3[i]=y[i]+ (k3[i]=step*f(x+h, t2, i));
  }
 
  for (i=0;i<N;i++){
 
    k4[i]= step*f(x+step, t3, i);
  }
 
  for (i=0;i<N;i++){
 
    y[i]+=(k1[i]+2*k2[i]+2*k3[i]+k4[i])/6.0;
  }
}
 
double f(double x, double y[], int i){
 
  if (i==0)
    x=y[1]; /* derivative of first equation */
  if (i==1)
    x=-y[0]-0.5*y[1];
  return x;
}

Lua 程式碼

-- 導入 js 模組
js = require("js")
-- 取得 window
window = js.global
-- 猜小於或等於 n 的整數
big = 100
-- 計算猜測次數, 配合 while 至少會猜一次
num = 1
-- 利用 window:prompt 方法回應取得使用者所猜的整數
guess = window:prompt("請猜一個介於 1 到 "..big.." 的整數")
-- 利用數學模組的 random 函數以亂數產生答案
answer = math.random(big)
output = ""
-- 若沒猜對, 一直猜到對為止
while answer ~= tonumber(guess) do
    if answer > tonumber(guess) then
        output = "猜第 "..num.." 次, guess="..guess..", answer="..answer.." - too small"
        print(output)
    else
        output = "猜第 "..num.." 次, guess="..guess..", answer="..answer.." - too big"
        print(output)
    end 
    guess = window:prompt(output..", 請猜一個介於 1 到 "..big.." 的整數")
    num = num + 1
end
print("總共猜了 "..num.." 次, answer=guess="..answer.." - correct")
    

Javascript 程式碼

STLViewer = function(stlpath, plotarea) {

	var mycanvas = document.getElementById(plotarea);
	var viewer = new JSC3D.Viewer(mycanvas)
	var theScene = new JSC3D.Scene;
	////Initialize with a default file:
	//var stlpath = "../../../assets/2013-10-23/stl/box.STL"
	//var stlpath = "../../../assets/2013-10-23/stl/taj.stl"
	viewer.setParameter('SceneUrl', stlpath);
    viewer.setParameter('InitRotationX', 20);
	viewer.setParameter('InitRotationY', 20);
	viewer.setParameter('InitRotationZ', 0);
	viewer.setParameter('ModelColor', '#CAA618');
	viewer.setParameter('BackgroundColor1', '#FFFFFF');
	viewer.setParameter('BackgroundColor2', '#383840');
	viewer.init();
	viewer.update();
	////init done
	var canvas_drop = document.getElementById('canvas-drop')
	/*var dropzone = document.getElementById('dropzone')
	dropzone.addEventListener('dragover', handleDragOver, false);
	dropzone.addEventListener('drop', handleFileSelect, false); */
	canvas_drop.addEventListener('dragover', handleDragOver, false);
	canvas_drop.addEventListener('drop', handleFileSelect, false);

////Drag and drop logic:
	function handleFileSelect(evt) {
	    evt.stopPropagation();
	    evt.preventDefault();
	    var files = evt.dataTransfer.files;
	    console.log(evt)
	    console.log(files)
	    preview_stl(files[0])
	  }

	  function handleDragOver(evt) {
	    evt.stopPropagation();
	    evt.preventDefault();
	    evt.dataTransfer.dropEffect = 'copy';
	  }

////jsc3d logic
	var handle_file_select = function(e) {
		e.stopPropagation()
		e.preventDefault()
		var f = e.target.files[0]
		preview_stl(f)
	}

	function preview_stl(f) {
		var reader = new FileReader()
		var ext = f.name.split(".")[1]

		function setup_viewer() {
			viewer.setParameter('InitRotationX', 20);
			viewer.setParameter('InitRotationY', 20);
			viewer.setParameter('InitRotationZ', 0);
			viewer.setParameter('ModelColor', '#CAA618');
			viewer.setParameter('BackgroundColor1', '#FFFFFF');
			viewer.setParameter('BackgroundColor2', '#383840');
			viewer.setParameter('RenderMode', "flat");
		}
		setup_viewer()

		reader.onload = (function(file) {
			return function(e) {
				theScene = new JSC3D.Scene
		    	stl_loader = new JSC3D.StlLoader()
		    	stl_loader.parseStl(theScene, e.target.result)
		      	//viewer.init()
		      	viewer.replaceScene(theScene)
		      	viewer.update()
		      	console.log("file reader onload")
			}
		})(f)

		if (ext.toLowerCase() != "stl") {
			alert("That doesn't appear to be an STL file.");
		} else {
			reader.readAsBinaryString(f)
		}
	}
}

Html 原始碼

<html>
   <head>
      <meta http-equiv="content-type" content="text/html;charset=utf-8">
      <title>CMSimfly</title>
      <link rel="stylesheet" type="text/css" href="/static/cmsimply.css">
   </head>
   <body>
      <div class='container'>
      <nav>
         <ul id='css3menu1' class='topmenu'>
            <li><a href='/get_page/簡介'>簡介</a>
            <li><a href='/get_page/目錄結構'>目錄結構</a>
            <li>
               <a href='/get_page/頁面編輯'>頁面編輯</a>
               <ul>
                  <li>
                     <a href='/get_page/插入程式碼'>插入程式碼</a>
                     <ul>
                        <li><a href='/get_page/Java 程式碼'>Java 程式碼</a>
                        <li><a href='/get_page/Python 程式碼'>Python 程式碼</a>
                        <li><a href='/get_page/C或C++程式碼'>C或C++程式碼</a>
                        <li><a href='/get_page/Lua 程式碼'>Lua 程式碼</a>
                        <li><a href='/get_page/Javascript 程式碼'>Javascript 程式碼</a>
                        <li><a href='/get_page/Html 原始碼'>Html 原始碼</a></li>
                        </li>
                     </ul>
               </ul>
            <li><a href='/get_page/網際簡報'>網際簡報</a>
            <li><a href='/get_page/網誌編輯'>網誌編輯</a>
            <li><a href='/get_page/已知錯誤'>已知錯誤</a></li>
         </ul>
      </nav>
      <section>
         <form method='post' action='/ssavePage'>
         <textarea class='simply-editor' name='page_content' cols='50' rows='15'><h3>Html 原始碼</h3></textarea>
         <input type='hidden' name='page_order' value='9'>
         <input type='submit' value='save'>
         <input type=button onClick="location.href='/get_page/Html 原始碼'" value='viewpage'>
         </form>
      </section>
   </body>
</html>
COPY TO CLIPBOARD	

正齒輪繪圖程式碼

<!-- 導入 Brython 標準程式庫 -->
<script src="./../static/brython.js"></script>
<script src="./../static/brython_stdlib.js"></script>
<p></p>
<!-- 啟動 Brython -->
<script>
window.onload=function(){
// 設定 data/py 為共用程式路徑
brython({debug:1, pythonpath:['./../data/py']});
}
</script>
<p><canvas height="600" id="onegear" width="800"></canvas></p>
<!-- 以下製作 button-->
<div height="20" id="onegear_div" width="800"></div>
<p><input id="n" type="text" value="22"><br> <button id="button">Set Number of Gears</button></p>
<!-- 以下實際利用  Brython 繪圖-->
<script type="text/python3">
from browser import document as doc
import math
# deg 為角度轉為徑度的轉換因子
deg = math.pi/180.
# 定義 Spur 類別
class Spur(object):
    def __init__(self, ctx):
        self.ctx = ctx
  
    def create_line(self, x1, y1, x2, y2, width=3, fill="red"):
        self.ctx.beginPath()
        self.ctx.lineWidth = width
        self.ctx.moveTo(x1, y1)
        self.ctx.lineTo(x2, y2)
        self.ctx.strokeStyle = fill
        self.ctx.stroke()
  
    # 定義一個繪正齒輪的繪圖函式
    # midx 為齒輪圓心 x 座標
    # midy 為齒輪圓心 y 座標
    # rp 為節圓半徑, n 為齒數
    # pa 為壓力角 (deg)
    # rot 為旋轉角 (deg)
    # 已經針對 n 大於等於 52 齒時的繪圖錯誤修正, 因為 base circle 與齒根圓大小必須進行判斷
    def Gear(self, midx, midy, rp, n=20, pa=20, color="black"):
        # 齒輪漸開線分成 15 線段繪製
        imax = 15
        # 在輸入的畫布上繪製直線, 由圓心到節圓 y 軸頂點畫一直線
        self.create_line(midx, midy, midx, midy-rp)
        # a 為模數 (代表公制中齒的大小), 模數為節圓直徑(稱為節徑)除以齒數
        # 模數也就是齒冠大小
        a=2*rp/n
        # d 為齒根大小, 為模數的 1.157 或 1.25倍, 這裡採 1.25 倍
        d=2.5*rp/n
        # ra 為齒輪的外圍半徑
        ra=rp+a
        # rb 則為齒輪的基圓半徑
        # 基圓為漸開線長齒之基準圓
        rb=rp*math.cos(pa*deg)
        # rd 為齒根圓半徑
        rd=rp-d
        # 當 rd 大於 rb 時, 漸開線並非畫至 rb, 而是 rd
        # dr 則為基圓到齒頂圓半徑分成 imax 段後的每段半徑增量大小
        # 將圓弧分成 imax 段來繪製漸開線
        # 當 rd 大於 rb 時, 漸開線並非畫至 rb, 而是 rd
        if rd>rb:
            dr = (ra-rd)/imax
        else:
            dr=(ra-rb)/imax
        # tan(pa*deg)-pa*deg 為漸開線函數
        sigma=math.pi/(2*n)+math.tan(pa*deg)-pa*deg
        for j in range(n):
            ang=-2.*j*math.pi/n+sigma
            ang2=2.*j*math.pi/n+sigma
            lxd=midx+rd*math.sin(ang2-2.*math.pi/n)
            lyd=midy-rd*math.cos(ang2-2.*math.pi/n)
            for i in range(imax+1):
                # 當 rd 大於 rb 時, 漸開線並非畫至 rb, 而是 rd
                if rd>rb:
                    r=rd+i*dr
                else:
                    r=rb+i*dr
                theta=math.sqrt((r*r)/(rb*rb)-1.)
                alpha=theta-math.atan(theta)
                xpt=r*math.sin(alpha-ang)
                ypt=r*math.cos(alpha-ang)
                xd=rd*math.sin(-ang)
                yd=rd*math.cos(-ang)
                # i=0 時, 繪線起點由齒根圓上的點, 作為起點
                if(i==0):
                    last_x = midx+xd
                    last_y = midy-yd
                # 由左側齒根圓作為起點, 除第一點 (xd,yd) 齒根圓上的起點外, 其餘的 (xpt,ypt)則為漸開線上的分段點
                self.create_line((midx+xpt),(midy-ypt),(last_x),(last_y),fill=color)
                # 最後一點, 則為齒頂圓
                if(i==imax):
                    lfx=midx+xpt
                    lfy=midy-ypt
                last_x = midx+xpt
                last_y = midy-ypt
            # the line from last end of dedendum point to the recent
            # end of dedendum point
            # lxd 為齒根圓上的左側 x 座標, lyd 則為 y 座標
            # 下列為齒根圓上用來近似圓弧的直線
            self.create_line((lxd),(lyd),(midx+xd),(midy-yd),fill=color)
            for i in range(imax+1):
                # 當 rd 大於 rb 時, 漸開線並非畫至 rb, 而是 rd
                if rd>rb:
                    r=rd+i*dr
                else:
                    r=rb+i*dr
                theta=math.sqrt((r*r)/(rb*rb)-1.)
                alpha=theta-math.atan(theta)
                xpt=r*math.sin(ang2-alpha)
                ypt=r*math.cos(ang2-alpha)
                xd=rd*math.sin(ang2)
                yd=rd*math.cos(ang2)
                # i=0 時, 繪線起點由齒根圓上的點, 作為起點
                if(i==0):
                    last_x = midx+xd
                    last_y = midy-yd
                # 由右側齒根圓作為起點, 除第一點 (xd,yd) 齒根圓上的起點外, 其餘的 (xpt,ypt)則為漸開線上的分段點
                self.create_line((midx+xpt),(midy-ypt),(last_x),(last_y),fill=color)
                # 最後一點, 則為齒頂圓
                if(i==imax):
                    rfx=midx+xpt
                    rfy=midy-ypt
                last_x = midx+xpt
                last_y = midy-ypt
            # lfx 為齒頂圓上的左側 x 座標, lfy 則為 y 座標
            # 下列為齒頂圓上用來近似圓弧的直線
            self.create_line(lfx,lfy,rfx,rfy,fill=color)
canvas = doc['onegear']
ctx = canvas.getContext("2d")
  
# 以 button 驅動的事件函式
def setgearnumber(e):
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    x = (canvas.width)/2
    y = (canvas.height)/2
    if doc["n"].value.isdigit():
        n1 = int(doc["n"].value)
    else:
        n1= 25
    # 設定齒輪參數
    x = (canvas.width)/2
    y = (canvas.height)/2
    r = 0.6*(canvas.height/2)
    pa = 20
    # 繪出齒輪
    Spur(ctx).Gear(x, y, r, n1, pa, "blue")
#判定 button
setgearnumber(True)
doc['button'].bind('click',setgearnumber)
</script>

國旗繪圖程式碼

<!-- for Brython -->
<script src="./../static/brython.js"></script>
<script src="./../static/brython_stdlib.js"></script>
<!-- 啟動 brython() -->
<p>
<script>
window.onload=function(){
brython(1);
}
</script>
</p>
<!-- 以下利用 Brython 程式執行繪圖 -->
<p><canvas height="400" id="taiwan_flag" width="600"></canvas></p>
<p>
<script type="text/python3">
# 導入 doc
from browser import document as doc
import math
  
# 準備繪圖畫布
canvas = doc["taiwan_flag"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 canvas.height 單位光點
# ctx.setTransform(1, 0, 0, -1, 0, canvas.height)
# 以下採用 canvas 原始座標繪圖
flag_w = canvas.width
flag_h = canvas.height
circle_x = flag_w/4
circle_y = flag_h/4
# 先畫滿地紅
ctx.fillStyle='rgb(255, 0, 0)'
ctx.fillRect(0,0,flag_w,flag_h)
# 再畫青天
ctx.fillStyle='rgb(0, 0, 150)'
ctx.fillRect(0,0,flag_w/2,flag_h/2)
# 畫十二道光芒白日
ctx.beginPath()
star_radius = flag_w/8
angle = 0
for i in range(24):
    angle += 5*math.pi*2/12
    toX = circle_x + math.cos(angle)*star_radius
    toY = circle_y + math.sin(angle)*star_radius
    # 只有 i 為 0 時移動到 toX, toY, 其餘都進行 lineTo
    if (i):
        ctx.lineTo(toX, toY)
    else:
        ctx.moveTo(toX, toY)
ctx.closePath()
# 將填色設為白色
ctx.fillStyle = '#fff'
ctx.fill()
# 白日:藍圈
ctx.beginPath()
ctx.arc(circle_x, circle_y, flag_w*17/240, 0, math.pi*2, True)
ctx.closePath()
# 填色設為藍色
ctx.fillStyle = 'rgb(0, 0, 149)'
ctx.fill()
# 白日:白心
ctx.beginPath()
ctx.arc(circle_x, circle_y, flag_w/16, 0, math.pi*2, True)
ctx.closePath()
# 填色設為白色
ctx.fillStyle = '#fff'
ctx.fill()
</script>


頁面編輯 << Previous Next >> 網際簡報