躺在沙灘上的小豬

          快樂的每一天

          #

          痛苦,gmail talk 不能保存全部歷史記錄。

          很遺憾,好多聊天記錄都沒有了,我需要那些東西,那些是我思考的過程,也是我和同事,朋友討論的過程。

          希望gmail talk下個版本能加上。

          posted @ 2005-09-20 15:59 martin xus| 編輯 收藏

          《dive into python》

          我喜歡這本書

          http://diveintopython.org/

          posted @ 2005-09-20 15:41 martin xus| 編輯 收藏

          菜單的生成。

          需要生成:
          http://www.softcomplex.com/products/tigra_menu_tree/ 

          最終生成的菜單:

           

          首先按需求定義了一個model.

          package com.jxlt.db.parse; 
          import java.io.Serializable; 
          
          public class TreeModel implements Serializable { 
                  private static final long serialVersionUID = 7896562831509010976L; 
          
                  private String code; 
                  private String title; 
                  private String url; 
                  private boolean leaf; 
                  private int level; 
          
                  /** 
                  * @return Returns the leaf. 
                  */ 
                  public boolean isLeaf() { 
                          return leaf; 
                  } 
          
                  /** 
                  * @param leaf 
                  *            The leaf to set. 
                  */ 
                  public void setLeaf(boolean leaf) { 
                          this.leaf = leaf; 
                  } 
          
                  /** 
                  * @return Returns the title. 
                  */ 
                  public String getTitle() { 
                          return title; 
                  } 
          
                  /** 
                  * @param title 
                  *            The title to set. 
                  */ 
                  public void setTitle(String title) { 
                          this.title = title; 
                  } 
          
                  /** 
                  * @return Returns the url. 
                  */ 
                  public String getUrl() { 
                          return url; 
                  } 
          
                  /** 
                  * @param url 
                  *            The url to set. 
                  */ 
                  public void setUrl(String url) { 
                          this.url = url; 
                  } 
          
                  /** 
                  * @return Returns the code. 
                  */ 
                  public String getCode() { 
                          return code; 
                  } 
          
                  /** 
                  * @param code 
                  *            The code to set. 
                  */ 
                  public void setCode(String code) { 
                          this.code = code; 
                  } 
          
                  /** 
                  * @return Returns the level. 
                  */ 
                  public int getLevel() { 
                          return level; 
                  } 
          
                  /** 
                  * @param level 
                  *            The level to set. 
                  */ 
                  public void setLevel(int level) { 
                          this.level = level; 
                  } 
          
          }

          獲取內容:

          package com.jxlt.db.parse; 
          
          import java.sql.Connection; 
          import java.sql.ResultSet; 
          import java.sql.SQLException; 
          import java.sql.Statement; 
          import java.util.ArrayList; 
          import java.util.List; 
          
          import com.jxlt.db.util.DataSourceUtils; 
          
          public class ParseTree { 
                  private static final String sql = "select t.bz_code code, 
                                                    t.bz_title itle, t.bz_content content "
                                           + "  from bz_czzs t " 
                                           + "  order by t.bz_code"; 
          
                  private static final String sql2 = "select t.bz_code code, 
                                                     t.bz_title title, 
                                                     t.bz_content content " 
                                                     + "  from bz_czzs t " 
                                           + " where substr(t.bz_code, 0, 3) = '002'" 
                                           + " order by t.bz_code"; 
          
                  public static List parse() { 
                          Connection conn = null; 
                          Statement st = null; 
                          ResultSet rs = null; 
                          List list = new ArrayList(); 
                          try { 
                                  conn = DataSourceUtils.getConnection(); 
                                  st = conn.createStatement(); 
          
                                  rs = st.executeQuery(sql2); 
                                  String code, title = ""; 
          
                                  while (rs.next()) { 
                                          code = rs.getString("code"); 
                                          title = rs.getString("title"); 
                 
                                          TreeModel model = new TreeModel(); 
                                          model.setCode(code); 
                                          model.setTitle(title); 
          
                                          model.setUrl(
                                           "m/content/" + code + ".html"); 
                                          model.setLeaf(false); 
                                          model.setLevel(
                                          code != null ? code.length() / 3 : 0); 
                                          list.add(model); 
                                  } 
          
                          } catch (SQLException e) { 
                                  e.printStackTrace(); 
                          } finally { 
                                  // DataSourceUtils.close(rs); 
                                  // DataSourceUtils.close(st); 
                                  DataSourceUtils.close(conn); 
                          } 
                          return list; 
                  } 
          }

          生成js文件

          package com.jxlt.db.parse; 
          
          import org.apache.log4j.Logger; 
          
          import java.util.List; 
          
          /** 
          * Generate the left tree menu 
          * 
          * @author martin.xus (martin.xus@gmail.com) 
          */ 
          public class GeneratorTree { 
                  private static Logger logger = Logger.getLogger(GeneratorTree.class); 
          
                  public static final String TREE_FILE = "D:\\workspace\\style\\test\\martin.tree.002.js"; 
          
                  /** 
                  * Generate the left tree menu 
                  * 
                  * @return String 
                  */ 
                  public static String generator() { 
                          StringBuffer buf = new StringBuffer().append(HEADER); 
                          List list = ParseTree.parse(); 
                          logger.debug("generating tree menu begin"); 
                          TreeModel model; 
                          TreeModel modelNext; 
                          int position; 
                          if (null != list && 0 < list.size()) { 
                                  for (int i = 0, length = list.size(); i < length - 1; i++) { 
                                          logger.debug("dealed with :" + i + " rows"); 
                                          StringBuffer _buf = new StringBuffer(); 
                                          model = (TreeModel) list.get(i); 
                                          modelNext = (TreeModel) list.get(i + 1); 
                                          _buf.append("['").append(model.getTitle()).append("','") 
                                                          .append(model.getUrl()).append("'"); 
          
                                          if (model.getLevel() > modelNext.getLevel()) { 
                                                  _buf.append(SUFFIX).append(COMMA); 
                                          } else if (model.getLevel() == modelNext.getLevel()) { 
                                                  _buf.append(SUFFIX).append(COMMA).append(PLACEKICK); 
                                          } else if (model.getLevel() < modelNext.getLevel()) { 
                                                  _buf.append(COMMA).append(PLACEKICK).append(SUFFIX); 
                                          } 
          
                                          position = buf.toString().indexOf(PLACEKICK); 
                                          if (position != -1) { 
                                                  buf.replace(position, position + 7, _buf.toString()); 
                                          } else { 
                                                  buf.insert(buf.length() - model.getLevel() - 4, "," 
                                                                  + _buf.toString()); 
                                          } 
          
                                          if (i == length - 2) { 
                                                  _buf.append("['").append(modelNext.getTitle()) 
                                                                  .append("','").append(modelNext.getUrl()).append( 
                                                                                  "'").append(SUFFIX).append(COMMA); 
                                          } 
                                  } 
                          } 
                          return buf.toString(); 
                  } 
          
                  private static final String SUFFIX = "]"; 
          
                  private static final String COMMA = ","; 
          
                  private static final String PLACEKICK = "$martin"; 
          
                  private static final String HEADER = "var TREE_ITEMS = [['索引','#'," 
                                  + PLACEKICK + "]];"; 
          }

          test 一下:

          logger.debug("writing file:" +
                             GeneratorTree.TREE_FILE); 
          FileWriter writer = 
                             new FileWriter(GeneratorTree.TREE_FILE); 
          writer.write(GeneratorTree.generator()); 
          writer.flush(); 
          writer.close(); 
          logger.debug("end");

          菜單js樣本
          一:

          var TREE_ITEMS = [
          	['index', '#',
          		['001', '#001',
          			
          			['001001', '#001001',
          				['001001001', '#001001001'],
          			],
          			
          			['001002', '#001002',
          				['001002001', '#001002001',
          					['001002002', '#001002002'],
          				],
          			],
          			
          			['001003', '#001001003',
          				['001003001', '#001003001',
          					['001003001001', '#001003001001'],
          					['001003001002', '#001003001001',
          						['001003001002001', '#001003001002001'],					
          					],
          				],
          			],
          		],
          		['002', '#002'],
          	]
          ];

          posted @ 2005-09-20 14:11 martin xus| 編輯 收藏

          python的強悍(二)

          按照需求,從新改寫了一下,而這些只是幾分鐘時間而已。

          import cx_Oracle
          from Template import *
          
          def parse():
              '''generate the content html'''
          
              sql = '''select t.bz_code code, t.bz_title title, t.bz_content content
                  from bz_czzs t 
                  order by t.bz_code'''
          
              connection = cx_Oracle.connect( 'etasadmin/etasadmin@zhongju' )
              cursor = connection.cursor()
              cursor.execute(sql)
              item=cursor.fetchone()
              i=1;
              print 'begin'
              while item:
                  i+=1
                  print 'parsing ',i,' item....'
                  writeContent(item[0],item[1],str(item[2]))
                  item=cursor.fetchone()
          
          def writeContent(code,title,content):
              filedir='D:\\m\\content\\'
              
              params = {'code':code,'title':title,'content':content} 
              t = Template('D:\\workspace\\style\\test\\template.xt',params)
              s = t.parse()
          
              out = open(filedir+code+".html",'w')
              out.write(s)
              out.flush()
              out.close()
              
          if __name__=='__main__':
              print 'parse..................'    
              parse()
              print 'end'

          posted @ 2005-09-20 13:42 martin xus| 編輯 收藏

          Martin Fowler:閉包

          Martin Fowler:閉包
          原著:Martin Fowler  http://martinfowler.com/bliki/Closures.html

          翻譯:huangpuzhuang.com>

          http://www.ruby-cn.org/

          另外一片文章總結了各種語言實現的本文中的例子。

          閉包(Closures)在各種語言中的例子

          2004/11/23

          本文地址:http://www.ruby-cn.org/articles/closures.html

              隨著人們對動態語言興趣的日益濃厚,越來越多的人都遇到了閉包(Closures )和或塊(Blocks)等概念。有著C/C++/Java/C#等語言背景的人因為這些語言本身沒有閉包這個概念,所以可能不太了解閉包。本文將簡單的介紹一下閉包的概念,那些有大量支持閉包語言編程經驗的人也許覺得本文不會太有意思。

              閉包的概念已經提出很長時間了。我第一次碰到這它是在smalltalk中,那時候還叫做塊(blocks)。Lisp語言中用的很多。Ruby中也有同樣的功能-這也是Ruby用戶喜歡Ruby的一個原因。

              本質上來說,一個閉包是一塊代碼,它們能作為參數傳遞給一個方法調用。我將通過一個簡單的例子來闡述這個觀點。假設我們有一個包含一些雇員對象的列表,然后我想列出職位為經理的員工,這樣的員工可以通過IsManager判斷。在C#里,我們可能會寫出下面類似的代碼:

            public static IList Managers(IList emps) {
              IList result = new ArrayList();
              foreach(Employee e in emps)
                if (e.IsManager) result.Add(e);
              return result;
            }
          

              在一種支持閉包的語言中,比如Ruby,我們可以這樣寫:

            def managers(emps)
          	return emps.select {|e| e.isManager}
            end
            

              select是Ruby中定義的集合結構中的一個方法,它接受一個block,也就是閉包,作為一個參數。在Ruby中,閉包寫在一對大括號中(不止這一種方法,另一種為do .. end)。如果這個塊也接受參數,你可以將這些參數放到兩個豎線之間。select方法循環迭代給定的數組,對每個元素執行給定的block,然后將每次執行block返回true的元素組成一個新的數組再返回。

              現在,如果你是C程序員你也許要想,通過函數指針也可以實現,如果你是JAVA程序員,你可能回想我可以用匿名內類來實現,而一個C#者則會想到代理(delegate)。這些機制和閉包類似,但是它們和閉包之間有兩個明顯得區別。

              第一個是形式上的不同(The first one is a formal difference)。閉包可以引用它定義時候可見的變量。看看下面的方法:

          def highPaid(emps)
          	threshold = 150
          	return emps.select {|e| e.salary > threshold}
          end
            

              注意select的block代碼中引用了在包含它的方法中的局部變量,而其它不支持真正閉包的語言使用其它方法達到類似功能的方法則不能這樣做。閉包還允許你做更有趣的事情,比如下面方法:

          def paidMore(amount)
          	return Proc.new {|e| e.salary > amount}
          end
          

              這個方法返回一個閉包,實際上它返回一個依賴于傳給它的參數的閉包。我可以用一個參數創建一個這樣的方法,然后再把它賦給另一個變量。

          highPaid = paidMore(150)
          

              變量 highPaid 包含了一段代碼(在Ruby中是一個Proc對象),這段代碼將判斷一個對象的salary屬性是否大于150。我們可以這樣使用這個方法:

          john = Employee.new
          john.salary = 200
          print highPaid.call(john)
            

                表達式highPaid.call(john)調用我之前定義的代碼,這時候此代碼中的amount已經在創建這方法的時候綁定為150。即使現在我執行print 的時候,150已經不在它的范圍內了,但是amount和150之間的綁定依然存在。

              所以,閉包的第一個關鍵點是閉包是一段代碼加上和定義它的環境之間的綁定(they are a block of code plus the bindings to the environment they came from)。這是閉包和函數指針等其它相似技術的不同點(java匿名內類可以訪問局部變量,但是只有當這些內類是final的時候才行)。

              第二個不同點不是定義形式的不同,但是也同樣重要。(The second difference is less of a defined formal difference, but is just as important, if not more so in practice)。支持閉包的語言允許你用很少的語法去定義一個閉包,盡管這點可能不是很重要的一點,但我相信這點是至關重要的-這是使得人們能很自然的使用閉包的關鍵點。看看Lisp,Smalltalk和Ruby,閉包遍布各處-比其它語言中類似的使用多很多。綁定局部變量是它的特點之一,但我想最大的原因是使用閉包的語法和符號非常簡單和清楚。

              一個很好的相關例子是從Smalltalk程序員到JAVA程序員,開始時很多人,包括我,試驗性的將在Smalltalk中使用閉包的地方在Java中使用匿名內類來實現。但結果使得代碼變得混亂難看,所以我們不得不放棄。

             我在Ruby經常使用閉包,但我不打算創建Proc對象,然后傳來傳去。大多數時間我用閉包來處理前面我提到的select等基于集合對象的方法。閉包另一個重要用途是'execute around method',比如處理一個文件:

          File.open(filename) {|f| doSomethingWithFile(f)}
          

             這里open方法打開一個文件,然后執行給定的block,然后關閉它。這樣處理非常方便,尤其是對事務(要求commit或者rollback),或者其它的你需要在處理結束時候作一些收尾處理的事情。我在我的xml文檔轉換中廣泛使用這個優點。

             閉包的這些用法顯然遠不如用Lisp語言的人遇到的多,即使我,在使用沒有閉包支持的語言的時候,也會想念這些東西。閉包就像一些你第一眼見到覺得不怎么樣的東西,但你很快就會喜歡上它們。

          其它語言例子

          Joe Walnes在blog中提供了 closures in the next version of C#。這個例子是靜態類型語言的,基于delegate,且需要delegate關鍵字。

          更新: Ivan Moore提供類類似的 Python 的例子

          更新: Vadim Nasardinov 讓我知道了來自Guy Steeleled的 closures in Java 這個有趣的珍聞。

           譯者注:如你想知道上面例子中文件對象是怎么自己關閉的,請看http://blog.csdn.net/ruby_cn/archive/2004/11/23/192588.aspx,希望可以找到答案。翻譯的不好,請多原諒。歡迎交流。括號之中的英語實在是不知如何很好翻譯,所以保留了下來。

          posted @ 2005-09-20 13:37 martin xus| 編輯 收藏

          僅列出標題
          共28頁: First 上一頁 20 21 22 23 24 25 26 27 28 下一頁 
          主站蜘蛛池模板: 营口市| 建湖县| 定西市| 墨脱县| 光泽县| 吉隆县| 安远县| 六盘水市| 文化| 织金县| 香格里拉县| 邳州市| 宝坻区| 阿合奇县| 新绛县| 吴堡县| 汶上县| 天祝| 孝感市| 垣曲县| 昌吉市| 扬州市| 黔西县| 沁源县| 望谟县| 新巴尔虎右旗| 元朗区| 柳江县| 白河县| 河北区| 利津县| 乐至县| 昔阳县| 武乡县| 怀来县| 杂多县| 易门县| 白朗县| 益阳市| 利川市| 新余市|