image

  • フォト Amazonギフト券
    ※この時計の時刻は、閲覧しているパソコンのものであり、必ずしも正確な時間とは限りません

検索

最近のトラックバック

無料ブログはココログ

パソコン・インターネット

2012-10-13

xslx を coffeescript で読み書きする

githug に xlsx.js という javascript で EXCEL (xslx 形式) を読み書きするスクリプトがあるのを知った。
これを coffeescirpt に変換してみた。(js2coffee で)
また、オリジナルのリポジトリーには、すぐに動作させられる例がなかったので、サンプルのスクリプトも
追加した。

https://github.com/katoy/node-xlsx

このxslsx.js は、 xml ファイルを read したり、生成している。
文字やセルの細かな属性は扱えない。(だからこそ単純なスクリプトで済んでいる)

現状で扱えるのは、シート枚数。シート名、セル中の文字と数字 だけ。
日付け、時間、カンタンな計算式, 罫線 を扱うぐらいまでの拡張なら、なんとかなりそうな気がする。

apache poi をつかわずに Exls を扱えるのは身軽で良い。

サンプルコードで生成した xlsx を OpenOffice for MAC で開いた様子:
20121013xslx

2012-09-01

uwsc を coffeescript 風の記述から生成する (その2)

coffeescript 風書式 -> uwsc コード生成で、
  * 配列の宣言、 function 定義のパラメータでの配列宣言、
  * 関数定義のパラメータの var 宣言, default 値
をサポートした。
See  https://github.com/katoy/coffee-script-for-uwsc

例:
$ cat array_def.coffee
dim ary_1 = [1,2,3]
dim ary_2[3] = [1,2,3]
dim ary_3[3]

PRINT ary_2[i] for i in [0 ... Length(ary_3.length)]
ReSize(ary_1, Length(ary_1) * 2 )

dim ary_23[2][2]
dim matrix2[2][2] = [ [1, 2], [3, 4] ]
size = 3
dim matrix3[size][size] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

PRINT matrix[i][j] for j in [0...size] for i in [0...size]

func = (x[]) ->
  PRINT x[0]

func2 = (x[][]) ->
  PRINT x[0][0]

$ ../bin/uwscscript -p array_def.coffee
// Generated by UwscScript 0.1.0
dim i, j, size
DIM ary_1 = [1, 2, 3]
DIM ary_2[3] = [1, 2, 3]
DIM ary_3[3]
For i = 0 To Length(ary_3.length) - 1
  PRINT ary_2[i]
Next
ReSize(ary_1, Length(ary_1) * 2)
DIM ary_23[2][2]
DIM matrix2[2][2] = [[1, 2], [3, 4]]
size = 3
DIM matrix3[size][size] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
For i = 0 To size - 1
  For j = 0 To size - 1
    PRINT matrix[i][j]
  Next
Next
Procedure func(x[])
  PRINT x[0]
Fend
Procedure func2(x[][])
  PRINT x[0][0]
Fend

$ cat function_2.coffee
func_1 = (x, y, z) ->
  PRINT x + y + z

func_1 = (x, var y, z = 1) ->
  PRINT x + y

func_3 = (x[]) ->
  PRINT x[0]

func_4 = (x[][]) ->
  PRINT x[0][0]

$ ../bin/uwscscript -p function_2.coffee
// Generated by UwscScript 0.1.0
Procedure func_1(x, y, z)
  PRINT x + y + z
Fend
Procedure func_1(x, var y, z = 1)
  PRINT x + y
Fend
Procedure func_3(x[])
  PRINT x[0]
Fend
Procedure func_4(x[][])
  PRINT x[0][0]
Fend

次は文字列定数中の \ の扱いを処理する予定。

2012-08-15

uwsc を coffeescript 風の記述から生成する

uwsc スクリプトを coffeescript 風の記述から変換するプログラムを試作してみた。
  https://github.com/katoy/coffee-script-for-uwsc

次のように変換できている。
// 自宅に winows 環境がないんで、Mac で実行。生成した uwsc スクリプトが uwsc で実行可能か試してはいない。

$ cat comment2.coffee
x = 10
y = 0
while x > 0
  x = x - 1
  y = y + 1

until x < 10
  x = x + 1

loop
  break if x > 0
  x = x - 1

x = x + 1 while x < 10
x = x - 1 until x < 0
ntsitm231047:test_uwsc youichikato$ cat comment2.coffee
class Base
  @set_count = (val)->
    ### xxx ###
    RESULT = val
    ### yyy ###
    RESULT = count + 1

class Base2
  @set_count = (val)->
    ###
      xxx
    ###
    RESULT = val
    if val is 0
      ###
        yyy
      ###
      RESULT = count + 1

$ ../bin/uwsscript -p comment2.coffee
class Base
  @set_count = (val)->
    ### xxx ###
    RESULT = val
    ### yyy ###
    RESULT = count + 1

class Base2
  @set_count = (val)->
    ###
      xxx
    ###
    RESULT = val
    if val is 0
      ###
        yyy
      ###
      RESULT = count + 1
ntsitm231047:test_uwsc youichikato$ ../bin/uwscscript -p comment2
// Generated by UwscScript 0.1.0

Class Base

  Function set_count(val)
    // xxx
    RESULT = val
    // yyy
    RESULT = count + 1
  Fend

Endclass

Class Base2

  Function set_count(val)
    //  xxx
    RESULT = val
    If (val = 0)
      //  yyy
      RESULT = count + 1
    Endif
  Fend

Endclass

coffeescript のコードをベースに、コード生成部を javascript でなくて、uwsc を生成するようにしている。

2012-02-18

json データを treegid で表示する例

json データを treegid で表示する例を以下に置いた。
  https://gist.github.com/1856467

web 上にも json データを treegid で表示するサンプルはいくつかある。

- http://www.trirand.com/blog/?page_id=393/treegrid/json-and-xml-treegrid-complete-sample-solved/
> jQuery Grid PluginJSON and XML Treegrid complete sample (SOLVED) | TreeGrid | » Forum

- http://stackoverflow.com/questions/6788727/jqgrid-tree-grid-with-local-data
> javascript - jqGrid tree grid with local data - Stack Overflow

treegrid 表示のポイント:
 grid には 次の設定をする。
     treeGrid: true,
     treeGridModel: 'adjacency' 
     ExpandColumn: '...'
  json データの cell データの末尾に次の項目を追加する。
      level           階層 (0,1, ...)
      parent       親の Cell の id
      isLeaf        bool 値
      expanded   bool 値
      loaded        bool 値

2012-01-15

coffeescript で epub の表示を。

2

先週 epub の目次情報の解析はできるようになった。
今週は、画面左の目次の項目をクリックして、画面右に本文を表示できるようにした。
https://github.com/katoy/fileupload

2011-12-30

coffeescript +jasmine-node の例

coffeescript +jasmine-node で クラスの実装、テストをしていく環境を構築してみた。
github に上げてある。
   https://github.com/katoy/triangle

node は 0.6.6 をつかっている。
俺の環境では coffee -c -w がエラー発生するので、cake で *.coffee -> *.js に compiel する
タスクを書いた。

ここで作成したクラスは
  3辺の長さを与えたら、三角形の形状を判定 (正三角形、二等辺三角形、一般、三角形にならない)
するだけのものだ。
テストケースの設計はせずに 入力範囲空間の一部分 ([0..4]x[0..4]x[0..4])を網羅してテストしている。

こんな単純な関数でも、もして作業でテストしたら、バグが入っても捕捉することは困難だろう。
自動テスト環境を構築しておけば、一瞬で挙動の変化の発生有無をチェックすることが可能だ。

小さな web アプリを coffeescript + mongodb で作成すること計画している。
これは そのための準備体操である。

同等の機能のクラスを2通りで実装してある。
しかし、片方のクラスは、内部で整数の数値演算でオーバーフローが起こるような記述になっている。
そして、テストではオーバーフローが起こる状況をキャッチできている。

$ cake spec
NG
Started
...F....

Triangle_bad:最大 - 1
  it x
  overflow! a + b = 200, b + c = 200, c + a = 200

Finished in 0.04 seconds
8 tests, 1517 assertions, 1 failure

2011-12-25

socket.io の examples/chat/app.js も coffeescript にしてみた。

socket.io の examples/chat/app.js
    https://github.com/LearnBoost/socket.io/tree/master/examples/chat
も coffeescript にしてみた。

このサンプルでは stylus をつかっている。
stylus は便利そうだ。
  - http://kyosuke.tumblr.com/post/14003234226/stylus
  > Kyosuke hamalog (Sass と LESS 以外の選択肢 Stylus)

apl.coffeescript の中身を示す。

$ cat app.coffee
express = require 'express'
stylus = require 'stylus'
nib = require 'nib'
sio = require 'socket.io'

app = express.createServer()
app.configure ->
  compile = (str, path) ->
    stylus(str).set('filename', path).use nib()

  app.use stylus.middleware(
    src: __dirname + '/public'
    compile: compile
  )
  app.use express.static(__dirname + '/public')
  app.set 'views', __dirname + '/views'
  app.set 'view engine', 'jade'

app.get '/', (req, res) ->
  res.render 'index', layout: false

app.listen 300, ->
  addr = app.address()
  console.log "   app listening on http://#{addr.address}:#{addr.port}"

io = sio.listen(app)
nicknames = {}

io.sockets.on 'connection', (socket) ->
  socket.on 'user message', (msg) ->
    socket.broadcast.emit 'user message', socket.nickname, msg

  socket.on 'nickname', (nick, fn) ->
    if nicknames[nick]
      fn true
    else
      fn false
      nicknames[nick] = socket.nickname = nick
      socket.broadcast.emit 'announcement', nick + ' connected'
      io.sockets.emit 'nicknames', nicknames

  socket.on 'disconnect', ->
    return  unless socket.nickname
    delete nicknames[socket.nickname]

    socket.broadcast.emit 'announcement', socket.nickname + ' disconnected'
    socket.broadcast.emit 'nicknames', nicknames

coffeescript で unzip

js2coffee で https://github.com/springmeyer/node-zipfile/blob/master/bin/unzip.js を coffeescript にしてみた。
(変換結果に対して ヘルプのメッセージ変更、空行の追加をしてある。)

$ coffee unzip.coffee ~/work/Books/What_Is_Node/What_Is_Node_.epub
unzipping: META-INF/container.xml
unzipping: OEBPS/cover.html
unzipping: OEBPS/index.html
unzipping: OEBPS/ch01.html
unzipping: OEBPS/ch01s08.html
unzipping: OEBPS/LiberationSerif.otf
unzipping: OEBPS/ch01s02.html
unzipping: OEBPS/LiberationMono-Italic.otf
unzipping: OEBPS/ch01s04.html
unzipping: OEBPS/LiberationMono-BoldItalic.otf
unzipping: OEBPS/author_bios.html
unzipping: OEBPS/ch01s05.html
unzipping: OEBPS/oreilly_large.gif
unzipping: OEBPS/content.opf
unzipping: OEBPS/httpatomoreillycomsourceoreillyimages867093.png.jpg
unzipping: OEBPS/ch01s03.html
unzipping: OEBPS/LiberationMono-Bold.otf
unzipping: OEBPS/httpatomoreillycomsourceoreillyimages867095.png.jpg
unzipping: OEBPS/core.css
unzipping: OEBPS/httpatomoreillycomsourceoreillyimages867097.png.jpg
unzipping: OEBPS/httpatomoreillycomsourceoreillyimages867099.png.jpg
unzipping: OEBPS/httpatomoreillycomsourceoreillyimages867091.jpg
unzipping: OEBPS/toc.ncx
unzipping: OEBPS/ch01s09.html
unzipping: OEBPS/LiberationMono.otf
unzipping: OEBPS/ch01s07.html
unzipping: OEBPS/ch01s06.html

この epub ファイルは
  http://www.amazon.com/What-Is-Node-ebook/dp/B005ISQ7JC/
の無料の電子書籍。

$ cat unzip.coffee
zip = require("zipfile")
fs = require("fs")
path = require("path")
usage = "usage: coffeescript unzip.coffee <zipfile>"

file = process.argv[2]
unless file
  console.log usage
  process.exit 1

zf = new zip.ZipFile(file)
zf.names.forEach (name) ->
  uncompressed = path.join(".", name)
  dirname = path.dirname(uncompressed)
  fs.mkdir dirname, 0755, (err) ->
    throw err  if err and not err.code.match(/^EEXIST/)
    if path.extname(name)
      buffer = zf.readFileSync(name)
      fd = fs.openSync(uncompressed, "w")
      console.log "unzipping: " + name
      fs.writeSync fd, buffer, 0, buffer.length, null
      fs.closeSync fd

2011-12-24

enchant.js を追加: express + coffeescript + mongoose の練習 (その2)

20111224game

http://youichi-kato.cocolog-nifty.com/blog/2011/12/express-coffees.html
> express + coffeescript + mongoose の練習
への追加。

さらに enchant.js での ページも追加してみた。
ファイル構成は次のようになる (nmp install する前の node_modules/ が無い状態)
$ tree
├── README.txt
├── app.coffee
├── package.json
├── public
│   ├── game.html
│   ├── images
│   │   └── miku.gif
│   ├── javascripts
│   │   ├── coffee-script.js
│   │   └── enchant.js
│   ├── src
│   │   └── sample-game.coffee
│   └── stylesheets
│       └── style.css
├── routes
│   └── index.js
└── views
    ├── index.jade
    └── layout.jade

追加したファイルは
public/
    game.html
    javascripts/
        coffee-script.js
        enchant.js
    images/
        miku.gif

coffee-script.js, enchant.js は ネット上から download してくる。
miku.gif は自分で作るか 適当なものを ネット上から download してくる。

game.html、src/sample-game.coffee は
     http://d.hatena.ne.jp/gigi-net/20111222/1324541519
     > CoffeeScript+enchant.jsで始めるゲーム開発入門
にあったサンプル。

$ cat public/game.html
<html>
    <head>
        <title>CoffeScript Canvas</title>
        <script src="javascripts/coffee-script.js" type='text/javascript'></script>
    <script src='javascripts/enchant.js' type='text/javascript'></script>

    <script src="src/sample-game.coffee" type="text/coffeescript"></script>

    </head>
    <body>
    </body>
</html>

$ cat public/src/sample-game.coffee
nchant()
class SampleGame extends Game
  constructor : ->
    super 320, 320
    @fps = 30
    SampleGame.game = @
    @preload "images/miku.gif"
    @onload = ->
      @rootScene.addChild new Player(100, 100)
    @start()

class Player extends Sprite
  constructor: (x, y) ->
    super 44, 32
    @x = x
    @y = y
    game = SampleGame.game
    @image = game.assets['images/miku.gif']
    @addEventListener 'enterframe', ->
      if game.input.up
        @y -= 5
      else if game.input.down
        @y += 5
      if game.input.left
        @x -= 5
      else if game.input.right
        @x += 5

new SampleGame()

$ coffee app.coffee
として、サーバーを起動してから http://localhost/game.html にアクセスする。

カーソルキーでキャラクターが上下左右に移動します。

express + coffeescript + mongoose の練習。

次の様にして coffeescript + mongoose を試してみることができる。
(node, npm, mongodb はインストール済みであるとする。)

$ express foo
$ cd foo
$ edit app.coffee
# ---- app.coffee の内容 は鯉術 ---------

$ edit package.json
# ---- package.json の内容 は鯉術 ---------

$ npm install
# ---- 実行に必要な依存パパッケージが ./node_modules に配置される

# ---- 別のターミナルで mnogodb を起動させておく
# ----  $ mongod --dbpath=./mongo

$ coffee -wc app.coffee

ブラウザで 次の URL にアクセスすると、ターミナルに colsole.log の出力が表示されていく。

http://localhost:3000

http://localhost:3000/add

http://localhost:3000

http://localhost:3000/drop

http://localhost:3000

http://localhost:3000/save?nake=xxx&age=20

http://localhost:3000

========================================
$ cat app.coffee
require 'coffee-script'

express = require 'express'
mongoose = require 'mongoose'

app = module.exports = express.createServer()

app.configure ->
  app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use express.bodyParser()
app.use express.methodOverride()
app.use express.compiler(
  src: __dirname + "/public"
  enable: [ "sass" ]
)
app.use app.router
app.use express.static(__dirname + "/public")

app.configure "development", ->
  app.use express.errorHandler(
    dumpExceptions: true
    showStack: true
  )

app.configure "production", ->
  app.use express.errorHandler()

mongoose.connect 'mongodb://localhost/node'

# schema定義
UserSchema = new mongoose.Schema
   name : String
   age : Number

User = mongoose.model('User', UserSchema)

app.get "/", (req, res) ->
  res.redirect('/find');

# find
app.get "/find", (req, res) ->
  res.render "index", title: "Express"

  User.find {}, (err,users) -> for user in users
    console.log user

# clean
app.get "/drop", (req, res) ->
  res.render "index", title: "Express"

  User.remove {}, (err) ->
    console.log err if err

  console.log "dropped!"

# save?name=foo&age=xx
app.get "/save", (req, res) ->
  res.render "index", title: "Express"

  if req.query["name"]
    rec = new User()
    rec.name = req.query["name"]  if req.query["name"]
    rec.age = req.query["age"] if req.query["age"]

    rec.save (err) ->
      console.log "save! #{rec}"  unless err

app.get "/add", (req, res) ->
  res.render "index", title: "Express"

  rec = new User()
  rec.name = "kato"
  rec.age = 20
  rec.save (err) ->
    console.log "add! #{rec}"  unless err

app.listen 3000
console.log "Express server listening on port %d", app.address().port

========================================
$ cat package.json
{
    "name": "application-name"
  , "version": "0.0.1"
  , "private": true
  , "dependencies": {
      "express": "2.5.2"
    , "jade": ">= 0.0.1"
    , "expresso": ""
    , "coffee-script": ""
    , "mongoose": ""
  }
}

より以前の記事一覧

mokuji

2013年12月
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        

google

  • twitter
  • __
  • _
    Googleボットチェッカー

合わせて読む

  • 合わせて読む
    フィードメーター - katoy: cocolog あわせて読みたい

リンク