Add vs code server service to docker compose service (for royroycat.com)

  code-server:
    image: codercom/code-server:4.22.0-ubuntu
    expose: 
      - 8888
    environment:
      - PASSWORD=${CODE_SERVER_PASSWORD} # change password in env file
    volumes:
      - ./config:/config
      - $PWD:/home/coder/workspace
    ports:
      - 8080:8888
    restart: unless-stopped
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.codeserver.rule=Host(`subdomain.${DOMAIN_NAME}`)"
      - "traefik.http.routers.codeserver.entrypoints=websecure"
      - "traefik.http.routers.codeserver.tls.certresolver=letsencrypt"

publish docker image or dockerFile/docker-compose

除非你整緊個好勁既 software/framework, 個個都想用再 config 佢既

咁你就值得用 image 裝住佢再 publish

但如果你只係 on top d software/framework (i.e. mysql/ python / node…) 得你一個或者幾個人用, 咁用 dockerfile 自身都夠

即係 lego 咁 你整到一盒 lego pack 咁你咪 生image register囉

但你只係拎個城市系列 on top 加d野 , 第2個都唔會用既, 咁你用 docker-compose / dockerFile 就算啦

同埋人地d image registry 位咁少 就知你根本整出黎既野suppose 唔洗整image …

勁過鬼既 software 咪又係得一兩個… 你真係會整咩

vue props (but you want to make ui extension)

首要: props 係 per component 既

edited: 原來係中左 fallthrough attributes : https://vuejs.org/guide/components/attrs.html

所以個 q-inline-edit-table columns:columns rows:rows 會隊晒入 q-table 到, 改都改唔到 (change object ref), 唯有直改 類面 d value

再所以有第二個做法係熄左個 fallthrough attribute 自己用 $attr 去處理… 但上面個方法都得

再再 前者原來 vue 都有叫你(盡量)唔好咁做 : https://vuejs.org/guide/components/props.html#mutating-object-array-props, 但作為 extension 無理由係個 q-table children 到 emit 個 event, 叫 user d code 去突登加個 eventListener 去接再加翻個 action column 既…

btw 佢都頭盔左呢個 design As a best practice, you should avoid such mutations unless the parent and child are tightly coupled by design.

其實 vue 太多 magic shorthand 遇到唔同 tag, case 同一個 syntax 都有唔同結局, 尤其 v-bind

遇到 html tag 但 class 同其他 attr 又會唔同, 遇到 component, 就直頭 pass props.睇唔明諗唔明就睇下 doc 先…

仔唔好亂改個 props 啊 之 哦原來你整既 ui extension 咁又唔同講法

每個 component (加 children) 都有自己既 props, 由阿媽一到傳到落底都係用同一個 props (suppose 你既設計最好係咁)

props 其實係一條同 d html 若即若離既 variables/status tree

又可以向下傳

你 define 左會用咩 props, 就拎得到 !

d props 如果指住左某個 object

columns: [{xxx}, {yyy}]

你d仔係唔可以隨意 assign 個 new array 隊翻入去

會出一個 columns=xxx 既 error

點解呢

  1. 因為個 array 係 proxy array
  2. 你隊個新既係無用
  3. 個 props 係好多隻野望住 (reactive嘛) 你求其隊個新一隻野落去會搞亂晒望住佢既人

咁點算 點改

咪唔好郁個 object ref, 你可以 push, shift 等等 一做就 reflect

其實雙阿媽到整左既 props, 一路傳落去用咪幾好 (EDITED: 今日先發現原來d props 係 auto 向下落, 個 template tag set 好左個 props, 下面d child tag 自然會用到)

(EDITED: template v-slot:body=”props” , using v-slot, props will 自然向下, 反而唔好叫 props 叫 slotProps 好d, v-slot:body=”slotProps”, 呢個係 argument (not parameter) 黎 , props 其實係自動入(同你入咩名無關, 咁不如叫 slotProps 以之識別), 跟住入到去 slot 就會改過花名叫 slotProps)

suppose 好好地用 9成時間 唔洗轉呢面d values

點知你個 task 係整 ui extension , 當你整緊個 q-table wrapper, 阿媽d props 係 user 自己砌, 跟住 pass 入去 q-table son 之前就攝下野

同一時間 你又唔想人用你個 library 個陣要加太多 props, eventlistener 等等

咁你而家想攝野又無可厚非

(e.g. 攝多個 action column 係 columns 前面)

所以即係你要改props la, 但千祈唔好叫佢指個新 ref, 你用住 original 個 value 攝黎攝去, 只要 obj ref 唔變係 ok ga

process.env.xxx in quasar

  1. you need put the env in front of the command rather than using export, it seems quaser build need in the command session (when case you cannot use .env)
  2. it is a replacement of text rather than run in js, so you may check the generated code to see is the actual value you want
  3. use args in docker-compose to pass the variable instead of ENV, it may make you life easier. Seems the process.env is not traditional env. But it similar like a argument passing

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

https://stackoverflow.com/a/61903230

哈哈你以為呢個就係答案?

其實係你個 route set 左個尾有 “/” 或者無 “/”

api url 其實好 strict 個尾有”/” 同無 , 你 call 錯都會出 error… 不過最奇係出上面個 error…

你想唔出 error, 可以去 fastapi 個 docs 到對下有無 call 錯 “/” 既 api … 你想 set “o岩” 可以去 routes 到 set “/” or “” …

但有趣地方係 localhost 又無事

deploy 上 server 先出事 唔知係 traefik 問題定係 browser 對出街既網 strict d 了

traefik some note

php real ip issue:

Use $_SERVER[‘HTTP_X_FORWARDED_FOR’] instead of $_SERVER[‘REMOTE_ADDR’] for php if using traefik as loadbalancer, or 172.X.X.X internal IP is return rather than real ip


http redirect

if need http→https

https://stackoverflow.com/questions/60510232/how-can-i-redirect-http-to-https-using-traefik

put this label under traefik service in docker compose and remember set traefik.enable=true


dashboard:

if you want the dashboard, see this:

https://gist.github.com/Maescool/7ec9836c48e53de79cc51fb70fbe1388

用 docker 又加左 python scheduler 但又無 print 唔出野

但 call 其他野 print 又無啦啦彈翻晒出黎? 放心你個 schedulrr 同個 program 都無事

solution:

put this in docker-compose

PYTHONUNBUFFERED=1

ChatGPT ans:

If you’re using the apscheduler library in your FastAPI app running in a Docker container, and you’re not seeing print messages in the container logs, it’s possible that the messages are being buffered by the apscheduler library or the Python interpreter, and are not being immediately flushed to the Docker logs.

One way to force the print messages to be immediately flushed to the Docker logs is to set the PYTHONUNBUFFERED environment variable to 1 when running the container. This will disable output buffering in the Python interpreter, and ensure that print messages are immediately written to the Docker logs.

quasar / vue

quasar 就係被你用佢原本 d component, 你想 cus 咩

佢就整左 d slot 被你去 攝/cus

加上 vue d shorthand logic (i.e. v-if, v-for) … props 既幫手就可以輕易咁 整/改 quasar or other 牌子 component

btw 你搞咁多野 vue 下面堆 props,data,methods,computed… 全部都係為左 serve 你上面堆 html template… <== vue 之真諦

-ti (for docker / other ssh/terminal program)

-t 即係 -tty (docker doc 話係 pseudo-TTY) 即係扮 terminal … 而家係 ssh … 但又想扮以前古代既 terminal, 呢個 tty = teletypewriter 好古代 真係有部打字機 但係識射d 電 signal 出黎, 個 -t = tty = terminal 真係扮緊呢個

-i 即係 interactive (docker doc 解釋叫 Keep STDIN open even if not attached) , 呢個 interactive 同而家既解釋要少少分別 , 個 _ 閃閃下俾你打字 俾command 去電腦係古代已經好 interactive … 所以 interactive = 被你入去 >_ 到打 command ; 相反唔 interactive 即係唔洗你入去打 command 直接行 program…

所以簡單黎講 你想用 docker 入 container 做d “interactive” 操作就要 exec -ti

終於明點解 js , py 咁鍾意用 get_XXX() 去 return 個 object

係啊 你可以就咁 inline code

route = APIRouter()

點解係要整個

def get_abc_router(p1, p2) -> APIRouter:
  router = APIRouter()
  @router.get("/verify")
  async def verify(user: User = Depends(current_active_user), parameter using p1, p2):
......
  return router

無錯啦 最重要就係個 p1, p2
你可以週位 import 個 get function, 跟住整新 object 個陣仲可以入 p1, p2 去 config
你無 get_xxx function 都得既, py 直 import 個 var
到時咪無得 config 囉

defineComponent vue

defineComponent 係 program 上係無用 直出你個 object

defineComponent  其實主要 for typescript 用
但你無用 ts 都無所謂

都可以 define 下

你可以試下 define 下 components, 你個 ide (vscode) 會即刻將你有用到+define左既 component 著燈

something about vue

  • Options API > Composition API, 但兩者都要學 (options api 本身都係 on top of Composition)
  • data() 即係 reactive state
  • this. 其實佢有好多自動野加左落隻 object 到 已經唔係原本隻 object 了
  • :class :style = v-bind:class v-bind:style
  • v-bind 就係扭個 html attribute value 既工具
  • props 主要係 read-only, 寫 html attribute 到射入 component, 又可以 parent to children
  • props html 係可以用 hyphenated, 入到 js 自動變 CamelCase
  • @ 即係 addEventListener
  • emits 即係 dispatchEvent
  • 你可以 explicit 咁 declare d event, 咁樣就唔會同 native 撞
  • slot 即係將 html value 當 parameter 咁隊入 component html
  • vue 係 shorthand 工具 同一個做法可以用好多方法寫 又好多自動左既 transformation 要睇清楚 manuel
  • ref 即係內置 dictionary, 等你可以加d html element 入去, 被其他去 call
  • v-model 即係 mvc 既 model, 類面係裝 object data 既
  • watch 即係 onchange 咁用, 或者改 value 個陣攝隻手埋去
  • computed 即係 cached get

frontend 真係搵個 nginx 隊住就得…因為全 static 死 file

https://medium.com/@jwdobken/develop-quasar-applications-with-docker-a19c38d4a6ac

# develop stage
FROM node:13.14-alpine as develop-stage
WORKDIR /app
COPY package*.json ./
RUN yarn global add @quasar/cli
COPY . .
# build stage
FROM develop-stage as build-stage
RUN yarn
RUN quasar build
# production stage
FROM nginx:1.17.5-alpine as production-stage
COPY --from=build-stage /app/dist/spa /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

唔怪得dev齋build 就算
build d static file 出黎就完
唔似 server side code 要搵個 program run 住
求其搵個 nginx 隊住就得
你想 dev 試就加 command 落 docker-compose
command: /bin/sh -c “yarn && quasar dev”

btw 同場加映:
用得 docker , d source code 有得 copy 就 copy ; 係 wordpress 有歷史因素(can update src code by button) 呢d另類先唯有用 mount

成日諗唔明點解 promise 點解要放 resolve/reject 做 define function 既 parameter

const promise = new Promise((resolve, reject) => {
  const result = performAsyncOperation();

  if (result) {
    resolve(result);
  } else {
    reject("Async operation failed");
  }
});

你要記住你成堆由 (resolve, reject)=>{xxx} 成舊野(your custom defined function) 都係叫 executor function

因為 promise 個 class pre-set 左 有一句會 call executor(resolve, reject)

既然你明知人地會 call 一個 function 要入 parameter resolve, reject 你創建個個 function 就當然要有 resolve, reject; 唔係人地 call 個陣咪唔夠料囉

你睇下 promise d src code 就知 你 define 塞入去個堆 logic 佢會叫做 executor

class Promise {
  constructor(executor) {
    this.state = 'pending';
    this.value = undefined;
    this.reason = undefined;
    this.callbacks = [];

    const resolve = (value) => {
      if (this.state === 'pending') {
        this.state = 'fulfilled';
        this.value = value;
        this.callbacks.forEach((callback) => callback.onFulfilled(value));
      }
    };

    const reject = (reason) => {
      if (this.state === 'pending') {
        this.state = 'rejected';
        this.reason = reason;
        this.callbacks.forEach((callback) => callback.onRejected(reason));
      }
    };

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  then(onFulfilled, onRejected) {
    if (typeof onFulfilled !== 'function') {
      onFulfilled = (value) => value;
    }
    if (typeof onRejected !== 'function') {
      onRejected = (reason) => {
        throw reason;
      };
    }

  === more promise method below ... ===

好啦 係 code 層面你明 , 人地叫呢個 resolve, reject 係 signal 囉

async 收到 signal (你 個 self define executor function call resolve 個下) 就會 call 用 .then register 既 callback …

揀 sql or mongo (nosql) 一些想法

如果你用緊 model 係 subobject 有一定既 ref 性 (即並非 clone data) 咁樣用 sql 先有意義

即例如你有張單 PO

PO 有堆 PO ITEM

然後有張 集單 List 叫 PL 先算
PL 會有d PO1.POITEM1, PO1.POITEM2, PO2.POITEM2, PO2.POITEM3

但如果 d POITEM 真係 ref 黎, 咁樣 sql 先有意義

如果整 PL 個陣都係抄 POITEM d data 咁樣其實用 document 都係一樣



PO1 {

POITEM1 : {name,qty}

POITEM2 : {name,qty}

POITEM3 : {name,qty}

}

when init PL , the PLITEM is clone from POITEM, 咁其實用 document 儲都好靚仔 最多搵多個 field 記住個 POITEM src ID

但你話唔係, PLITEM { POITEM1 …} 係直接 link 住 POITEM 既 id, 咁就真係有 relationship 既地方, 咁 sql 先有意義

如果係 Clone data 都變一個新個體, 用 document 儲其實仲合符具體現實 跟本無咩 relationship 可言; 你話 update poitem 要update 埋 plitem, 咪做 reflection / event 乜都得啦

decorator of function in py

decorator…

you may think it is used for an extend of an original function.

so you should call the original function in your decorator by your design

(although some rare case, like using a test function to replace the original function)

So, a decorator is a way to extend or modify the behavior of an existing function without modifying its source code.

From POE:

Yes, a decorator is a way to extend or modify the behavior of an existing function without modifying its source code.

When you apply a decorator to a function, the decorator creates a new function that wraps the original function with some additional behavior. The resulting wrapped function can then be called just like the original function, but with the added behavior provided by the decorator.

For example, consider the following decorator function that adds some behavior before and after the wrapped function is called:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before the function is called.")
        result = func(*args, **kwargs)
        print("After the function is called.")
        return result
    return wrapper

In this example, my_decorator is a function that takes another function func as an argument and returns a new function wrapper that wraps func with some additional behavior. The resulting wrapper function can be called just like func, but with the added behavior provided by my_decorator.

Using this decorator function, you can extend the behavior of any function by applying the decorator to the function using the @ syntax, like this:

@my_decorator
def my_function(x):
    return x * 2

In this example, the @my_decorator syntax applies the my_decorator decorator to the my_function function, so that when you call my_function(2), the wrapper function returned by my_decorator is called instead, which first prints “Before the function is called.”, then calls my_function(2), which returns 4. Finally, the wrapper function prints “After the function is called.” and returns 4.

So, a decorator is a way to extend or modify the behavior of an existing function without modifying its source code.

uwsgi vs gunicorn

uwsgi… 用用下會 upstream prematurely closed connection while reading response header from upstream

你又以為從 vm 壞/唔夠 resources, 又以為 nginx set 錯野…

跟住你 google , 點 google 都無咩 solution 係真正永久 work

solution: use gunicorn…

其實仲易 set 過 uwsgi …

docker 好處

唔好講咩 container, 咩 isolation

對 developer 既 develop 方式有更大好處

剩係 dockerFile 同 docker-compose 同 d swarm/k8n 呢d 已經可以:

  • 唔同既 docker software 都係用同一款方式管理, config 規范晒係 dockerFile/docker-compose
  • 比以前 deploy 方式 更多 config file 可以被 commit / reuse
  • dockerFile / docker-compose d config 可以 commit, 可以好快咁重用

你話 makeFile 都可以 commit la, 係架, 但類面d command 都係太 software specific

docker command 將佢變成 RUN, 規范左, 可以專注睇只係識睇既野, 如果用 makeFile 就要學其他唔識睇既 command. Docker 已經規范左d instruction, 就算 parameter 唔識睇 但都實知佢做緊咩

你話 salt/chef 夠可以 config 規范, 係啊. 但只限 server provision. 未達到去 config software 層面

呢d我覺得 je, 唔認同都唔緊要.

vue

vue 只係 node 既一個 program / software

一個行 js 既 program / software, 你寫左一堆 js instruction

vue 呢個 program 就同你 gen 一堆 browser 識睇既 js 出黎

當然你都可以用 global build / cdn 版本

但你就要直接寫d browser 識睇既 js 出黎

node vue program 幫你 gen, 你咪多d component, shorthand, .vue file 幫你寫

cdn 版你就要寫好多”奇怪” code.因為要 browser 識睇

how to disable setting prompt for your custom mac input method

“xxxInputMethod” would like to enable third-party input method “XXX”.

please see your code … is there any “TISEnableInputSource(inputSource);”

find that this function call will trigger the setting prompt.

本身呢個功能應該係 for 有d app 想著某個 輸入法

但如果你個 app 本身係輸入法就應該唔洗 如果唔係個 prompt 就煩死你

如果寫輸入法 TISSelectInputSource 應該都夠做

P.S. google “TISEnableInputSource”. 都幾多野睇同學 對比起就咁 search inputMethod

sql join join join and filter

寫 sql 唔同你寫 program 唔係入個阿媽某個 column 既 value 再隊入去 另一個 table 當 parameter

係乜都用左大 join 先 唔o岩用 ? 日期大過 effective date 既 cost ? join 左先啦

最後先 filter

唔理架 乜都 join 十幾萬 record 大溶爐先 最後想要咩 record 先慢慢 filter

A1 單要配 某個日子既 cost ?

A1(which is Date3)-Cost1 Date1 A1(which is Date3)-Cost2 Date2 A1(which is Date3)-Cost3 Date3

join 晒先 再啄走唔要個d 留翻一個 係我夠知 A1 – Date3 先o岩 你 join 左再用 on 去啄 如果唔係有乜法 je~

SUM() subquery in select clause

SUM 最重要還是 where clause select + where = filter select + sum() + where = satisfy 以前細個學又話叫 filter … 其實我覺得叫 satisfy 好d

又所以 我發覺 sum() subquery in select clause, group by 係唔需要:

select a, b, (select sum(xxx) where [CONDITION] 這裡放 group by 無用) as yyy, …

select …(select sum(xxx) where sth)只能回一個 single row , 唔係就會 error, 所以個 where clause 要俾夠 info 去砌到得翻一個 rowgroup by 本身 for multiple row 去教 table 點 group … 但 single row 其實就無必要

我開頭以為 sum() 既 logic 係 define 係 group by which is 錯既 … 但原來都係放係 where 到

ref: Capture

有時我蠢 要人地解點解要整新功能 去解決緊咩問題 之 map/reduce in js for play with json/data

https://rangle.io/blog/map-reducing-the-pain-of-dealing-with-arrays/

map: But it’s not really a way of dealing with arrays. It’s about mapping one value into a new value, and getting the same type back.

So the takeaway is that you don’t have to care if map loops or not, or how it loops, or in some languages how many threads it uses. If you are using a map method on an array, or on a library Promise or Observable, or anything else, it will do what it has to do to transform the value(s), and give you back the same type, so that you can keep calling map on the result.

under the hood, awesome

under the hood – find the tech underlying

https://www.pauladamsmith.com/articles/redis-under-the-hood.html

https://www.codementor.io/blog/docker-technology-5x1kilcbow

awesome list – find some new library

https://github.com/sindresorhus/awesome

devops – CI software / process / protocol

tech stack – you may find some library / framework that company / software use

getting start – getting start

XML Pretty Print CDATA new one line … not good

Capture

Nani ?

點 pretty print CDATA 都自己跌落一行?

你話無問題 你想 search by <field=”id”>xxx 你就知你d value 要一行過 咁點解決

個問題係錯左 xml tools engine, too long no read, 打死都用 QuickXML

但已經隔左行 7左咁點算

1) Use xmltools > option > Engine:SimpleXML > Linearize > 變翻無格仔一行先

2) Use QuickXML > Pretty Print

entrypoint is the command , CMD is for argument

https://www.ctl.io/developers/blog/post/dockerfile-entrypoint-vs-cmd/

but you want run run entrypoint.sh then start.sh, here is the tricks

ENTRYPOINT ["/entrypoint.sh"]
some code or not...
CMD ["/start.sh"]

entrypoint.sh:

some code for entrypoint ...
exec "$@"

using exec, the start.sh (as parameter) will run

Don’t use python to do big5-hkscs encode

常用字都算ok…深少少都總係 big5 既字 e.g. 苽 都出唔到…

只係出到個 ISO unicode

搞左勁耐以為寫錯 , 但java / vb.net 是 ok的 應該係 py d codec 有問題/唔齊

唔好用 py 做d 中文 big5 處理野

玩死自己

# -- coding: utf-8 --
#!/usr/bin/python
import sqlite3
import re
import logging
import binascii

logger = logging.Logger('catch_all')
conn = sqlite3.connect('table.db')

def main():
    filepath = 'mapped_char.txt'
    cnt = 0
    with open(filepath, encoding='utf-8') as fp:
        line = fp.readline()    
        while line:
            result = [x.strip() for x in line.split(',')]
            code = result[0]
            for text in result[1]:
                if not(isCharacterBig5(text)):
                    a = ''.encode('hkscs')
                    print(a.hex())
                # insertRecord(code, text)
            line = fp.readline()
            cnt = cnt + 1
    conn.commit()
    conn.cursor().close()

def insertRecord(code, text):
    cursor = conn.cursor()
    cursor.execute("INSERT INTO dict (code, text) VALUES (?, ?)", (code, text))

def isCharacterBig5(text):
    pattern = '[^\uE000-\uF8FF]'
    return re.match(pattern, text)

#def convertToUnicode():


#def getBig5HexCode(text):


main()

寫到一半 encode(‘hkscs’) 成日話 illegal multibyte sequence enter image description here

diu 啦 其實係佢個 codec 無呢個字 … (但現實 hkscs 有的) 只係出到個 \ueb51 unicode 代碼 你係政府個網都摷到 ISO 個行既, 但就唔是 BIG-5 囉

ref: https://bugs.python.org/issue28693 http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt

Free account for ios deploy real device to test

https://learnappmaking.com/how-to-create-a-free-apple-developer-account/

  • Requires free Apple Developer account, at a minimum. Free account provisioning expires every 7 days, requiring reloading/rebuilding, but you will not lose any data.

    Paid Apple Developer provisioning may only require re-signing once a year.

wordpress / php-pfm config

1) Ram for php-fpm php.ini -> memory_limit = 512M or up -> max_execution_time = 60 or up
被多d ram php aka wordpress

2) /etc/php5/fpm/pool.d/www.conf https://www.if-not-true-then-false.com/2011/nginx-and-php-fpm-configuration-and-optimizing-tips-and-tricks/

follow forum that config
set 翻o岩 worker 數

3) swap https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-16-04

but vm.swappiness=50 or up and vm.vfs_cache_pressure=80 or up

php 隊盡左 ram, 所以 用 swap, 個網 set 得好低 pressure, 可以高d

4) nginx
nginx.conf
-> worker_connections 1024

校多d workers

Application Support You don’t have permission to save the file

Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “data” in the folder “gamedata”." UserInfo={NSFilePath=file:///var/mobile/Containers/Data/Application/651354D9-30FF-4156-9D31-5F90D92D13C7/Library/Application%20Support/gamedata/data, NSUnderlyingError=0x14010cbf0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

do {
            try NSFileManager.defaultManager().createDirectoryAtPath(GameData.filePath, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error)
        }

        NSKeyedArchiver.archiveRootObject(GameData.data!, toFile: GameData.filePath)
        print(GameData.filePath)

createDirectoryAtPath will say You don’t have permission

OK, so use URL:

let fileManager = NSFileManager.defaultManager()
        let appSupportPath:[NSURL] = fileManager.URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
        let store:NSURL = appSupportPath.first!

        do {
            try NSFileManager.defaultManager().createDirectoryAtURL(store, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error)
        }

        NSKeyedArchiver.archiveRootObject(GameData.data!, toFile: GameData.filePath)
        print(GameData.filePath)

SKView please presentScene(nil) or the scene will still here and eat the memory

me design LevelViewController (TableView) -> present -> GameViewController . SKView . Scene

When I dismiss the GameViewController, the scene “update” (onEnterFrame) still running, to prove that the scene has not been killed

And after several time present the GameViewController, the app will lag becoz too many SKScene is running.

So please (self.view as! SKView).presentScene(nil) when GameViewController self.dismissViewControllerAnimated(true, completion: nil)

Must call a designated initializer of the superclass

  • 即係講到尾, subclass 想 call super.init 唔可以 call 佢個d convenience 只能 call 基本 init
  • 基本 init 又可以有好多個 , 你要 superclass 佢, 就要 required 晒佢~

    class NoteMessage: Message { let content: String
    
        init(content: String, theUser: String)
        {
            self.content = content
            super.init(sender: theUser)
            //Error!:  Must call a designated initializer of the superclass 'Message'
        }
    }
    

enter image description here

如何理解 swift 既 ? 同 !

如何理解 swift 既 ? 同 !

假設有 Class 叫 Animal

Animal? 並不要好似網上d tutorial 話 一係有一係 nil 咁理解

不如你當佢係未知的禮物 type 咁理解 (inspired by wrapped / unwrapped)

Animal? 有兩個狀態 1: S<Type> 或者 2: nil

唔係 nil 就可以打開佢, 打開左先係以前我地認識既 var

呢個世界有 3 個方法去打開禮物包

  1. ! 強行打開

  2. if let abc = xyz { } 禮物打開咪做下面d logic

  3. abc?.function() 有咪行個 function 囉

as? as! 都類似

as! 有機會 nil -> runtime error

as? 就要用 if let 幫幫手

if let animalSelectedNode = selectedNode as? AnimalSpriteNode {

ref: http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language

Debug Command for unix n windows of networking, ip, firewall, port forwarding

Re: SSH to Debian Guest from Windows host via Putty Postby noteirak » 19. May 2013, 11:24

Run the following on the host : CODE: SELECT ALL EXPAND VIEW ipconfig /all route print arp -a netstat -an | find “LISTENING” netsh advfirewall show allprofiles

Run the following in the guest : CODE: SELECT ALL EXPAND VIEW sudo ifconfig -a sudo route sudo arp sudo netstat -lnp sudo iptables -L -n -v

and in virtualbox, if u opening port for flask, pls use 0.0.0.0
or ensure the port forwarding is go to 127.0.0.1 in your VM

my python flask deploy flow

How to update python api sudo su deploy

cd /home/deploy/your-python-project
git pull
source ../py3.4/bin/activate
python setup.py bdist_egg
easy_install dist/<python_proj.egg>
alembic upgrade head
uwsgi –reload ~/uwsgi.pid

git download the src code -> (env) -> pack it into egg -> using easy_install to install the python egg -> update db migration -> restart server

my 幻想 docker flow

  • just write your code first, without docker
  • git push your application when you can first deploy
  • create a docker image, in dockerFile or init of your image, git clone the lastest code
  • pack it into image
  • for old machine, update the container with new image

  • one application one docker
  • mysql no need include in docker, and it should not go into a separate docker. just find a machine or one of a machine to run it.

[ios] convert mpmediaitem to m4a

-(NSString*)convertToM4A : (MPMediaItem * ) mediaItem {
    NSURL *url = [mediaItem valueForProperty: MPMediaItemPropertyAssetURL];

    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];

    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
                                                                      presetName:AVAssetExportPresetAppleM4A];

    exporter.outputFileType = @"com.apple.m4a-audio";

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * myDocumentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

    /* Using date to be file name so no conflict
    [[NSDate date] timeIntervalSince1970];
    NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
    NSString *intervalSeconds = [NSString stringWithFormat:@"%0.0f",seconds];*/

    NSString* mediaTitle = [mediaItem valueForProperty:MPMediaItemPropertyTitle];
    NSString* songTitle = [[NSString alloc]initWithFormat:@"%@",(mediaTitle.length>0 ? mediaTitle : @"Unknown")];

    NSString * fileName = [NSString stringWithFormat:@"%@.m4a", songTitle];

    NSString *exportFile = [myDocumentsDirectory stringByAppendingPathComponent:fileName];

    NSURL *exportURL = [NSURL fileURLWithPath:exportFile];
    exporter.outputURL = exportURL;

    // do the export
    // (completion handler block omitted)
    [exporter exportAsynchronouslyWithCompletionHandler:
     ^{
         int exportStatus = exporter.status;

         switch (exportStatus)
         {
             case AVAssetExportSessionStatusFailed:
             {
                 NSError *exportError = exporter.error;
                 NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
                 break;
             }
             case AVAssetExportSessionStatusCompleted:
             {
                 NSLog (@"AVAssetExportSessionStatusCompleted");
                 /*
                  NSData *data = [NSData dataWithContentsOfFile: [myDocumentsDirectory
                  stringByAppendingPathComponent:fileName]];

                  NSLog(@"Data %@",data);
                  data = nil;
                  */
                 break;
             }
             case AVAssetExportSessionStatusUnknown:
             {
                 NSLog (@"AVAssetExportSessionStatusUnknown"); break;
             }
             case AVAssetExportSessionStatusExporting:
             {
                 NSLog (@"AVAssetExportSessionStatusExporting"); break;
             }
             case AVAssetExportSessionStatusCancelled:
             {
                 NSLog (@"AVAssetExportSessionStatusCancelled"); break;
             }
             case AVAssetExportSessionStatusWaiting:
             {
                 NSLog (@"AVAssetExportSessionStatusWaiting"); break;
             }
             default:
             {
                 NSLog (@"didn't get export status"); break;
             }
         }
     }];
    return [exportURL absoluteString];
}

[ios aubio]ld: symbol(s) not found for architecture arm64

Undefined symbols for architecture arm64:
  "_vDSP_ctoz", referenced from:
      _aubio_fft_do_complex in aubio(fft.c.1.o)
  "_vDSP_fft_zrip", referenced from:
      _aubio_fft_do_complex in aubio(fft.c.1.o)
  "_vDSP_minv", referenced from:
      _fvec_min in aubio(mathutils.c.1.o)
  "_vDSP_create_fftsetup", referenced from:
      _new_aubio_fft in aubio(fft.c.1.o)
  "_vDSP_maxvi", referenced from:
      _fvec_max_elem in aubio(mathutils.c.1.o)
  "_vDSP_vsmul", referenced from:
      _aubio_fft_do_complex in aubio(fft.c.1.o)
  "_vDSP_maxv", referenced from:
      _fvec_max in aubio(mathutils.c.1.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Don’t cry.
Try to import Accelerate.framework which is default in frameworks of xcode.

scrollview with a uiview in masonry

A tableview which scrollview and the tableview can scroll to right

self.tableView = [[UITableView alloc]init];
self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
[self.tableView setDelegate:self];
[self.tableView setDataSource:self];
self.tableView.backgroundColor = [UIColor whiteColor];
[self.tableView setAllowsSelection:NO];

    //build the scrollabe view
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;

    // add subview tree
    [self.scrollView addSubview:self.tableView];
    [self.view addSubview:self.scrollView];

    //build footer view
    self.footerView = [[DetailsTableVTViewFooterView alloc] init];
    self.footerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.footerView];
    [self.footerView.saveButton addTarget:self action:@selector(saveLocalChanges) forControlEvents:UIControlEventTouchUpInside];

    // Using Masonry for autolayout
    [self.footerView makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@footerHeight);
        make.width.equalTo(frame.size.width);
        make.right.equalTo(self.view.right);
    }];

    self.scrollView.backgroundColor = [UIColor redColor];

    [self.scrollView makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.right);
        make.left.equalTo(self.view.left);
        make.top.equalTo(self.view.top);
        make.bottom.equalTo(self.footerView.top);
    }];

    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(tableViewWidth);
        make.bottom.equalTo(self.footerView.top);
        make.left.equalTo(self.scrollView.left);
        make.right.equalTo(self.scrollView.right);
        make.top.equalTo(self.scrollView.top);
    }];

Server Deployment Common Practice

User

  • You has a admin user call your name. Say roychung for me. And other admin has own account too.
  • A user call deploy or your service name for the main service of your written code. It should not be a sudoer. And suppose you cannot login via ssh.
  • For different service, may be redis. You may consider to open an account for it too.
  • So how to deploy to the deploy user? You may consider using sudo su deploy
  • Using Fabric for deployment, login with your own admin account and sudo su make your life easier when there are several server
  • Using redis as example, you may use sudo to install redis (or using redis user install on it home folder), but running redis command will be using that redis user. So other user can modify it without knowing your account

music player in background ios

Solution 1. MPMusicPlayer ipodPlayer

it is actually calling the ipod player, which it is not related to the app anymore. Easy implement, 但有時 load 得多歌 會有d lag, 超建議開多個 tableView 做, 可以 store 住d mediaItemCollection, 因為呢個 framework 係唔會 交返d mediaItemCollection 你, 除非你用 hidden private API

Solution 2. AVPlayer with MPRemoteCommandCenter and MPNowPlayingInfoCenter

you can implement like this. Good Point is the music playing will also appear in the universal toolbar (the bottom one), and click one it, it will show yr app instead of ipod Music. Bad Point is no itunes cloud music can play, and many feature need to implement yrself, 連 previous 都好似無, shuffle 都有d 難做, 但用個d remoteCommand , 下面d 制都可以用, 同埋 用 nowplayinginfocenter 可以 改個 lock screen 個d song info. 無記錯呢個方法要改少少 plist, 有 background audio, 如果做完前者, 出 app無 聲, 試下

MPMusicPlayer ApplicationPlayer is a good choice 如果你想只播歌係你個 app 入面, 因為一出 app 就會 收聲

ref:

http://www.mixedcase.nl/articles/2013/01/29/mediaplayer-apples-worst-framework/ (solution 1)

小米音樂 app (solution 2)

UIBarButtonItem title 入 nil 唔好入 @””

用 code 整 nav button … 如果無 title 就入 nil … 入 @”” … 佢會因為其他有 component 郁 而 會移動並出現在 strange position

錯的
UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithTitle:@""
                                                               style:UIBarButtonItemStylePlain
                                                              target:self
                                                            action:@selector(showLeftMenu:)];

對的
UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithTitle:nil
                                                               style:UIBarButtonItemStylePlain
                                                              target:self
                                                            action:@selector(showLeftMenu:)];

decorator in python

http://www.dotblogs.com.tw/rickyteng/archive/2013/11/06/126852.aspx

class entryExit(object):
def __init__(self, f): 
    print 'entry init enter' 
    self.f = f 
    print 'entry init exit'
def __call__(self, *args): 
    print "Entering", self.f.__name__ 
    r = self.f(*args) 
    print "Exited", self.f.__name__ 
    return r
print 'decorator using'
@entryExit 
def hello(a): 
print 'inside hello' 
return "hello world " + a
print 'test start' 
print hello('friends')
>>> ================================ RESTART ================================ 
>>> 
decorator using 
entry init enter 
entry init exit 
test start 
Entering hello 
inside hello 
Exited hello 
hello world friends

property inheritance in ios

http://bhapca.blogspot.hk/2012/11/how-to-access-backing-ivars-for.html

How to access backing ivars for inherited properties in Objective-C
I had a superclass that declared and synthesized a read only property, meant to be set in its subclasses. The code was something like this:

@interface A : NSObject
@property (nonatomic, readonly) NSUInteger prop;
@end

@implementation A
@synthesize prop = _prop;
@end

@interface B : A
@end

@implementation B

  • (void)establishValueForProp
    {
    _prop = 1; // PROBLEM !!!
    }

@end

The instance variable backing the property seemed to be invisible in the subclass. The error was pretty unclear when compiling an iOS app: “Use of undeclared identifier ‘_prop'”. To get around the error I did the following:

@interface A : NSObject {
NSUInteger _prop;
}
@property (nonatomic, readonly) NSUInteger prop;
@end

That is, I explicitly declared the backing variable in the declaration of the superclass.

Interestingly, when I was preparing this blog post I compiled the code above as a “Command Line Tool” type of project, not an iOS app. The error was different, dare I say better, more telling of the root cause: “Instance variable ‘_prop’ is private”. So it’s a matter of the visibility of the ivar, so perhaps a better fix would be:

@interface A : NSObject {
@protected
NSUInteger _prop;
}
@property (nonatomic, readonly) NSUInteger prop;
@end

Kind of interesting though that properties are synthesized by default as private ivars. Learned something new.
Posted by Bogdan Hapca at 12:09 PM
Email This
BlogThis!
Share to Twitter
Share to Facebook
Share to Pinterest

Labels: iOS, Objective-C
1 comment:

Liviu Macsen said…
Thank your Bogdan for your solution. I found that you can also synthesize in subclass in order to solve this problem.

@implementation B

@synthesize prop = _prop;

  • (void)establishValueForProp
    {
    _prop = 1; // Working !!!
    }

@end

ONLY_ACTIVE_ARCH

debug YES becoz u only want to build in your testing device (or compile too long time and waste the other arch build)

release NO u should make sure all ios devices can run

set segue.destinationViewController property

method 1. typecast

APPDetailViewController myController = (APPDetailViewController)segue.destinationViewController;
myController.myString = string;

method 2. selector

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.destinationViewController respondsToSelector:@selector(setMyData:)]) {
         [segue.destinationViewController performSelector:@selector(setMyData:) 
                                               withObject:myData];
    } 
}

in destination View Controller

@property (nonatomic, strong) MyData *myData;

Assertion failure in -[XXXView layoutSublayersOfLayer:]

2014-08-06 12:17:02.511 Jtab[6255:60b] *** Assertion failure in -[JTChordCollectionView layoutSublayersOfLayer:], /SourceCache/UIKit/UIKit-2935.138/UIView.m:8794 2014-08-06 12:17:02.512 Jtab[6255:60b] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Auto Layout still required after executing -layoutSubviews. JTChordCollectionView’s implementation of -layoutSubviews needs to call super.’

    [super layoutSubviews];

    [chordLabelView makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(labelPlaceHolder.centerX);
        make.centerY.equalTo(labelPlaceHolder.centerY);
    }];

solve by add [super layoutSubviews]; before add constraints ….

fitFontSize

-(void)fitFontSize:(UILabel*)label {
CGFloat actualFontSize;
[label.text sizeWithFont:label.font
minFontSize:label.minimumFontSize
actualFontSize:&actualFontSize
forWidth:label.bounds.size.width
lineBreakMode:label.lineBreakMode];
label.font = [label.font fontWithSize:actualFontSize];
label.adjustsFontSizeToFitWidth = NO;
}

usage: self.keyLabel = [self makeLabel:[UIFont fontWithName:@”AkzidenzGroteskBE-BoldCn” size:45.0f]];

    self.keyLabel.frame = CGRectMake(0, 0, self.cellWidth / 4.0, self.cellHeight);
    self.keyLabel.text = @"C";

    [self fitFontSize:self.keyLabel];
    [self.keyLabel sizeToFit];
    [self.keyLabel makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.centerX);
        make.centerY.equalTo(self.centerY);
    }];

Masonry in ios

constraints is funny

if u use Masonry or updateConstraints to a UIView, may no reaction till u drag one constraints to it…

Becoz

  1. storyboard default has constraints already (if u dun drag any) it just the current frame be the constraints (if u tick autolayout which is usually ticked)
  2. when u drag the constraints, it override
  3. when u code using Masonry or constrains programming, it override

But sometimes it will say broken, becoz the constraints jammed… so… one solution: http://img.thissoso.com/img/2/cee33f4f55e0.png

it will ignore all the storyboard constraints, so u can use the coding one now.

auto size font size uilabel

- (void)drawPageLabel {
  self.pageLabel = [[UILabel alloc] init];

  [self addSubview: self.pageLabel];

  self.pageLabel.textColor = [UIColor blackColor];
  [self.pageLabel setAlpha:0.5];
  self.pageLabel.font = [self.pageLabel.font fontWithSize:140];
  [self.pageLabel setNumberOfLines:1];
  self.pageLabel.adjustsFontSizeToFitWidth = YES;
  self.pageLabel.minimumScaleFactor = 0.5f;

  // get a approiate font size using "1" char
  self.pageLabel.text = @"1";

  // make a frame for it to adjust it width for suitable fontSize
  CGFloat innerCircleWidth = self.radius * 0.2f * 2;
  self.pageLabel.frame = CGRectMake(0, 0, innerCircleWidth, innerCircleWidth); // maintain a square size

  // remeber the recommended font size
  CGFloat actualFontSize;
  [self.pageLabel.text sizeWithFont:self.pageLabel.font
               minFontSize:self.pageLabel.minimumFontSize
            actualFontSize:&actualFontSize
                  forWidth:self.pageLabel.bounds.size.width
             lineBreakMode:self.pageLabel.lineBreakMode];

  // use the recommended font size and dun adjust anymore
  [self.pageLabel setFont:[UIFont systemFontOfSize:actualFontSize]];
  [self.pageLabel sizeToFit];

  self.pageLabel.adjustsFontSizeToFitWidth = NO;
}

-(void)updatePageLabel:(int)currentNumber {
  self.pageLabel.text = [NSString stringWithFormat:@"%d", currentNumber];
  [self.pageLabel sizeToFit];
  self.pageLabel.frame = CGRectMake(self.pageLabel.superview.frame.size.width/2 - self.pageLabel.frame.size.width/2,
                                    self.pageLabel.superview.frame.size.height/2 - self.pageLabel.frame.size.height/2,
                                    self.pageLabel.frame.size.width,
                                    self.pageLabel.frame.size.height);
}

CGFloat actualFontSize;
[self.pageLabel.text sizeWithFont:self.pageLabel.font
         minFontSize:self.pageLabel.minimumFontSize
      actualFontSize:&actualFontSize
            forWidth:self.pageLabel.bounds.size.width
       lineBreakMode:self.pageLabel.lineBreakMode];

this make my life … get the recommend font size after adjustsFontSizeToFitWidth
stupid sizeToFit only fit for the setted font size

kvo , key value observer script

in swipeView:

pair set:
– willChangeValueForKey:
– didChangeValueForKey:

or call this
- setValue:forKey:

[self.swipeView addObserver:self
                 forKeyPath:@"currentItemIndex"
                    options:NSKeyValueObservingOptionNew
                    context:nil];

self 個到有

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
     NSLog(@"hi"); 
}

vagrant simple example

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Vagrantfile API/syntax version. Don’t touch unless you know what you’re doing!
VAGRANTFILE_API_VERSION = “2”

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.provider “virtualbox” do |v|
v.memory = 1024
v.cpus = 1
end
config.vm.define “prod” do |prod_config|
prod_config.vm.box = “jamnplayer”
prod_config.vm.network “forwarded_port”, guest: 8080, host: 8081
prod_config.vm.network “forwarded_port”, guest: 5000, host: 5001
prod_config.vm.network “forwarded_port”, guest: 22, host: 2200, auto_correct: false, id: “ssh”
prod_config.vm.host_name = “prod”
end
end

======

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Vagrantfile API/syntax version. Don’t touch unless you know what you’re doing!
VAGRANTFILE_API_VERSION = “2”

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.provider “virtualbox” do |v|
v.memory = 2048
v.cpus = 1
end
config.vm.define “default” do |default_config|
default_config.vm.box = “ubuntu-14.04”
default_config.vm.network “forwarded_port”, guest: 6543, host: 6543
default_config.vm.network “forwarded_port”, guest: 8080, host: 8080
default_config.vm.network “forwarded_port”, guest: 5000, host: 5000
default_config.vm.network “forwarded_port”, guest: 22, host: 2222, auto_correct: false, id: “ssh”
default_config.vm.host_name = “default”
end
end

the virtualbox system ubuntu bit maybe wrong

I know at least 2 ways. Open a terminal and type:

uname -a

Result for 32-bit Ubuntu:

Linux discworld 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux

whereas the 64-bit Ubuntu will show:

Linux discworld 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux

or

file /sbin/init

Result for 32-bit Ubuntu:

/sbin/init: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped

whereas for the 64-bit version it would look like:

/sbin/init: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped

python property, getter, setter

Try this: Python Property

The sample code is:

class C(object):
def __init__(self):
self._x = None

@property
def x(self):
“””I’m the ‘x’ property.”””
print “getter of x called”
return self._x

@x.setter
def x(self, value):
print “setter of x called”
self._x = value

@x.deleter
def x(self):
print “deleter of x called”
del self._x

[ios] filter music from ios by MPMediaQuery

MPMediaQuery *songQuery = [MPMediaQuery artistsQuery];
// OR
MPMediaQuery *songQuery = [MPMediaQuery songsQuery];

// local only
[songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithBool:NO] forProperty:MPMediaItemPropertyIsCloudItem]];

NSArray *songs = [songQuery items];

And u will retrieve a list … but music video is still here…
becoz music video is 2049 … ok u see

enum {
// audio
MPMediaTypeMusic = 1 << 0, MPMediaTypePodcast = 1 << 1, MPMediaTypeAudioBook = 1 << 2, MPMediaTypeAudioITunesU = 1 << 3, // available in iOS 5.0 MPMediaTypeAnyAudio = 0x00ff, // video (available in iOS 5.0) MPMediaTypeMovie = 1 << 8, MPMediaTypeTVShow = 1 << 9, MPMediaTypeVideoPodcast = 1 << 10, MPMediaTypeMusicVideo = 1 << 11, MPMediaTypeVideoITunesU = 1 << 12, MPMediaTypeAnyVideo = 0xff00, MPMediaTypeAny = ~0 }; typedef NSInteger MPMediaType; tht's it: MPMediaTypeMusic: 1 MPMediaTypePodcast: 2 MPMediaTypeAudioBook: 4 MPMediaTypeAudioITunesU: 8 (iOS 5) MPMediaTypeAnyAudio: 255 MPMediaTypeMovie: 256 MPMediaTypeTVShow: 512 MPMediaTypeVideoPodcast: 1024 MPMediaTypeMusicVideo: 2048 MPMediaTypeVideoITunesU: 4096 MPMediaTypeAnyVideo: 65280 2049 is MPMediaTypeMusicVideo + MPMediaTypeMusic MPMediaQuery *songQuery = [MPMediaQuery artistsQuery]; OR MPMediaQuery *songQuery = [MPMediaQuery songsQuery]; OR [songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInteger:MPMediaTypeMusic] forProperty:MPMediaItemPropertyMediaType]]; even add comparisonType:MPMediaPredicateComparisonEqualTo 3 methods no work ... it want mediaType contain 1 and 2049 is still here method : filter it: NSArray *songs = [songQuery items]; NSMutableArray *finalSongs = [NSMutableArray array]; [songs enumerateObjectsUsingBlock:^(MPMediaItem *song, NSUInteger idx, BOOL *stop) { NSInteger mediaValue = [[song valueForProperty:MPMediaItemPropertyMediaType] integerValue]; if (mediaValue == 1) [finalSongs addObject:song]; }];

AFNetworking using manager to eat @”text/plain”

make AFHTTPRequestOperationManager can eat text/plain (or other content-type)
rmb re-init serializer for it…
the default one like JSON very much … but i m not doing JSON …

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@”text/plain”];

rmb add “file://” when using multipart form file
NSString *file = [[NSString alloc] initWithFormat: @”file://{file_address}];

import vamp into ios

put all library into a Vendors/VampPlugin folder
add -lstdc into build settings, other linker flags
edit the to “library” if needed
(dun add the simple host first)
comment the main a gXXx.c , since it crash the “main”
compile and goodbye

install harmtrace in linux

install haskell-platform
update cabal
cabal install HarmTrace

it will warn u no gsl
install gsl then

sudo apt-get install libgsl0-dev liblapack-dev

then
cabal install HarmTrace

finish

~/.cabal/bin/harmtrace

harmtrace recognise –file=/Users/roychung/project/harmtrace/let_it_be.mp3 –mode=group –grammar=pop -o=/Users/roychung/project/harmtrace/output –log-dir=/Users/roychung/project/harmtrace/log –csv-dir=/Users/roychung/project/harmtrace/csv –sa-path=/Users/roychung/project/harmtrace/sonic-annotator –vamp-dir=/Users/roychung/project/harmtrace/vamp

in /Users/roychung/project/harmtrace/vamp need transform file
which is generate by sonic annotator

http://code.soundsoftware.ac.uk/projects/sonic-annotator/wiki

then it will say no sox

http://sox.sourceforge.net/

then sox want lame and mad (from readme)
install them

transform file is sth like :
$ sonic-annotator -s vamp:vamp-example-plugins:fixedtempo:tempo
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix vamp: <http://purl.org/ontology/vamp/> .
@prefix : <#> .

:transform a vamp:Transform ;
vamp:plugin <http://vamp-plugins.org/rdf/plugins/vamp-example-plugins#fixedtempo> ;
vamp:step_size “64”^^xsd:int ;

vamp:block_size “256”^^xsd:int ;
vamp:parameter_binding [
vamp:parameter [ vamp:identifier “maxbpm” ] ;
vamp:value “190”^^xsd:float ;
] ;
vamp:parameter_binding [
vamp:parameter [ vamp:identifier “maxdflen” ] ;
vamp:value “10”^^xsd:float ;
] ;
vamp:parameter_binding [
vamp:parameter [ vamp:identifier “minbpm” ] ;
vamp:value “50”^^xsd:float ;
] ;
vamp:output <http://vamp-plugins.org/rdf/plugins/vamp-example-plugins#fixedtempo_output_tempo> .
$

hint:
beat-tracker transform need change to 256 …
it has error about it, or u cannot generate the beat-tracker.txt

something about harmtrace on mac and ubuntu

i m going to install your harmtrace in my mac to make some chord file. but unluckily, i always got buildFail when linking to a package call hmatrix-gsl-stats-0.2

<... some loading package message above .. >
Loading package vector-0.10.0.1 … linking … done.

Loading package hmatrix-0.15.2.1 … linking … done.

Loading package hmatrix-gsl-stats-0.2 … linking … ghc:

lookupSymbol failed in relocateSection (relocate external)

/Users/roychung/Library/Haskell/ghc-7.6.3/lib/hmatrix-gsl-stats-0.2/lib/HShmatrix-gsl-stats-0.2.o: unknown symbol `_mean’

ghc: unable to load package `hmatrix-gsl-stats-0.2′

Failed to install HarmTrace-2.2.0

Updating documentation index /Users/roychung/Library/Haskell/doc/index.html

cabal: Error: some packages failed to install:

HarmTrace-2.2.0 failed during the building phase. The exception was:

ExitFailure 1

do u have idea to solve ?

i m in OSX 10.9

Roy Chung

Thx so much for u reading this email (though u dun solve my problem)

========================================================================================================================

I just reinstall the whole things. and turn off “shared: False” in cabal config when face this linkage problem. This will turn off the linkage dynamic lib of apple , i think the problem is occur by here. And harmtrace can be succeed install.

And i try to install virtualbox and install an ubuntu image. It just install successfully and smoothly. (so i think linux is better … )

[ios] audio conversion using AVAssetExportSession / AVAssetWriter from AVFoundation

Target : ipod library -> aiff / wav / caf (which eat by libsndfile (already ported to ios))

first, i think AVAssetExportSession can solve my problem due to this link:

http://tuchangwei.github.io/blog/2013/06/04/how-to-export-mp3-from-ipod-library/

but it is for converted-to-mp3 only (or converted-to-m4a)

(Trick :

Some points you need notice:
when you init AVAssetExportSession object, the “presetName” argument must be “AVAssetExportPresetPassthrough”.
The “outputFileType” may be “com.apple.quicktime-movie”.

And rename to mp3)

why i know it is for mov or m4a

if u write :
NSLog(@”export.supportedFileTypes : %@”,export.supportedFileTypes);

u will get:
exporter.supportedFileTypes : (
“com.apple.quicktime-movie”,
“com.apple.m4a-audio”,
“public.mpeg-4”,
“com.apple.m4v-video”,
“public.3gpp”,
“org.3gpp.adaptive-multi-rate-audio”,
“com.microsoft.waveform-audio”,
“public.aiff-audio”,
“public.aifc-audio”,
“com.apple.coreaudio-format”
)

but it is only telling u these type exporter can convert
in api:
Discussion
Not all presets are compatible with all assets.

So after i run
NSLog(@”%@”, [AVAssetExportSession exportPresetsCompatibleWithAsset:songAsset]);
2014-05-27 18:29:35.792 Jtab[1723:60b] (
AVAssetExportPresetAppleM4A,
AVAssetExportPreset960x540,
AVAssetExportPresetLowQuality,
AVAssetExportPresetMediumQuality,
AVAssetExportPreset640x480,
AVAssetExportPresetHighestQuality,
AVAssetExportPreset1280x720
)

only m4a is available (and mp3 using mov one)
whatever your ipod library song is mp3, m4a, wav (i tried)
so it is fail

And note that using AVAssetExportSession, the output extension is concerned, if type != extension will error

So i go to other solution AVAssetWriter:

wav example:
http://objective-audio.jp/2010/09/avassetreaderavassetwriter.html

wav example:
http://iphonedevsdk.com/forum/iphone-sdk-development/62807-export-audio-as-m4a-alac.html

caf example:
http://swordinhand.iteye.com/blog/1942043

同場加映:

Easy AAC compressed audio conversion on iOS
http://atastypixel.com/blog/easy-aac-compressed-audio-conversion-on-ios/
using https://github.com/michaeltyson/TPAACAudioConverter

But i think use AVAssetExportSession to m4a can solve the problem…,so TPAACAudioConverter is useless now

strong vs retain and weak vs assign and blah blah blah

After reading so many articles, SO posts and demo apps to check variable property attributes, I decided to put all the attributes information together:

atomic //default
nonatomic
strong=retain //default
weak
retain
assign //default
unsafe_unretained
copy
readonly
readwrite //default
Below is the detailed article link where you can find above mentioned all attributes, that will definitely help you. Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

1.strong (iOS4 = retain )

it says “keep this in the heap until I don’t point to it anymore”
in other words ” I’am the owner, you cannot dealloc this before aim fine with that same as retain”
You use strong only if you need to retain the object.
By default all instance variables and local variables are strong pointers.
We generally use strong for UIViewControllers (UI item’s parents)
strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.
Example:

@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;
2.weak –

it says “keep this as long as someone else points to it strongly”
the same thing as assign, no retain or release
A “weak” reference is a reference that you do not retain.
We generally use weak for IBOutlets (UIViewController’s Childs).This works because the child object only needs to exist as long as the parent object does.
a weak reference is a reference that does not protect the referenced object from collection by a garbage collector.
Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil
Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;
Strong & Weak Explanation:

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying “Look! A dog!” As long as the dog is still on the leash, the little kids can still see the dog, and they’ll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

3.retain = strong

it is retained, old value is released and it is assigned retain specifies the new value should be sent
retain on assignment and the old value sent -release
retain is the same as strong.
apple says if you write retain it will auto converted/work like strong only.
methods like “alloc” include an implicit “retain”
Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;
4.assign

assign is the default and simply performs a variable assignment
assign is a property attribute that tells the compiler how to synthesize the property’s setter implementation
I would use assign for C primitive properties and weak for weak references to Objective-C objects.
Example:

@property (nonatomic, assign) NSString *address;

@synthesize address;
share|improve this answer
edited Nov 14 ’13 at 8:25

http://stackoverflow.com/questions/8927727/objective-c-arc-strong-vs-retain-and-weak-vs-assign

cannot get position, or cell reuse animation cannot control

if u r doing AVAudioPlayer, and u grep currentTime, if u wanna has a more accurate time, it cannot do it … since it is quite discrete (for compress song like mp3) … so

CACurrentMediaTime() may help u

beginTime = CACurrentMediaTime()

… some animation …

animateTime = CACurrentMediaTime() – beginTime

so i have some value can calculate the view if the animation wanna pause in the middle

(too complicated animation recommend use CAKeyFrameAnimation)

[ios] declare const

1. private

myfile.m
NSString *const SelectionSort = @”SelectionSort”;

2. public

myfile.h
extern NSString *const SelectionSort;
and in myfile.m define them

myfile.m
NSString *const SelectionSort = @”SelectionSort”;

It works, but only if you need a non global constant. Static constant is not visible outside the file. Otherwise use the 1st option.

http://stackoverflow.com/questions/6188672/where-do-you-declare-constant-in-objective-c

============================================

The #define is a pre-processor macro. That means that it basically goes through your code and replace your macro with what you’ve defined.

If you use a const, it’s going to be a pointer to the string in memory. It’s way more efficient than having the same string being allocated wherever/whenever it is used.

To do that, you’ll need both .h and .m files. Your .h file will look something like:

extern NSString * const YOUR_STRING;
And your .m file:

NSString * const YOUR_STRING = @”your string”;

no need Class.THIS_IS_A_CONST , just THIS_IS_A_CONST then ok

===============================================

把NSString宣告為常數
錯誤的宣告方式
會出現warning:(Sending ‘const NSString *__strong’ to parameter of type ‘NSString *’ discards qualifiers)
.h
extern NSString * SelectionSort;
.m
const NSString *InsertionSort = @”SelectionSort”;

正確的宣告方式
.h
extern NSString *const SelectionSort;
.m
NSString *const SelectionSort = @”SelectionSort”;

http://mywayonobjectivec.blogspot.hk/2014/05/nsstring.html

UICollectionView 的心路歷程

project 是寫一個 guitar chord + music player
data 只有 那些 chord, 我的 project 就是要 用 cell 一格格的跟住音樂 著燈

1. using UICollectionView
problem 1: offset
因為我用了 endTime – startTime, 原來會累積 一些 error ,導致後面不準

problem 2: UICollectionView reloaditemsAtIndexPath 有 animation 在閃
求其 set 了 就繼續做
[UIView setAnimationsEnabled:NO];

http://stackoverflow.com/questions/14094684/avoid-animation-of-uicollectionview-after-reloaditemsatindexpaths

到第一個 deadline : 發現這兩問題

首先要解決閃的問題,因為 setAnimationsEnabled:NO 會令到 needle (音樂器的秒數指標)

solution 1 : 用了 PSTCollectionView ,改 src code, 熄了那 .3 的 animation
但用舊野可能有後遺症
所以轉了第二個 function

用 reloadData , 其實是整幅 cells reload
壞處是不能有 animation 在其中,不斷 call 的話,scroll 也不能
visibleCells 也有不準的情況 (其實放在 reload 前 就會o岩了)

offset 問題,本想用 ticker 可處理
每 0.01 秒去 發 notification 和 cells 對話
cells 轉自己的 isCurrentChord = YES 同埋
call delegate (viewController) 話邊粒係 current
本應很好,但 0.01 秒去 call 一個 reload function
call reloadData 還好,call reloaditemsAtIndexPath 簡直炒晒
因為 refresh 得太密, scroll 要自己設計,click 亦不能,此路不通

solution 3 : 返回基本步,用 UICollectionView ,仍覺得閃可以解決,使用了
[UIView animateWithDuration:0 animations:^{
[collectionView performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:indexPaths];
} completion:nil];
}];

needle 仍舊不能動

好友提議下,將 endTime – startTime 改成 currentCell.startTime – musicPlayer.currentTime 做 timer interval
currentIndex++ after one timer trigger

offset 問題解決了,誤差不會再 stack 上去, 就算有誤差,都係本身一個 cell 的極少誤差

reloadItemsAtIndexPaths 不能用,唯有用 relaodData
注意 reloadData 係 async 的
亦 rmb use layoutIfNeeded 去 trigger update
但因為無用 ticker, 小心處理動畫問題,用起上來蠻方便的

[magento] some important file

read the following file can know more about the route and flow

store/app/code/core/Mage/Core/Controller/Varien/Front.php <== front controller store/app/code/core/Mage/Core/Model/App.php <== (Main) App Model (Object) about REFERENCE : 即係跳 block 專用技
Diagram 3

is used to make reference to another block. By making a reference to another block, the updates inside will apply to the it correlates to (see diagram 3).

In order to make the reference, you must target the reference to a block by using the ‘name’ attribute. This attribute targets the tag’s ‘name’ attribute. So if you were to make a reference by , you’re targeting the block called .

[magento] debugging ? open css hint

need some tricks:

http://www.redlightblinking.com/blog/magento-debugging-how-to-debug-template-paths-logging-and-display-errors

MAGENTO DEBUGGING – HOW TO DEBUG TEMPLATE PATHS, LOGGING AND DISPLAY ERRORS
Categories: Blog, Magento
Developing in Magento without these debugging tips can be challenging! Here is how you can debug magento:

Turn on Template Path Hints
Turn on error/system logging
Turn on SQL logging
Display PHP errors

Turn on Template Path Hints

Would you like to see the path of the file that is producing the HTML for each block on the page?

1. Log into the admin

2. Goto -> System ->Configuration, and on the bottom of the list select “Developer”

3. click on Debug – you will only see “Profiler”. Here is the trick – you have to switch the “Current Configuration Scope:” [in the upper left] to a website instead of default. Select “Main Website”.

4. Now you will see the selection for Template Path Hints – check yes. This will display the path of the template for each block of the page so you can find stuff! You can also choose to “Add Block Names to Hints” to see the corresponding model class for the block.

Turn on error/system logging

1. In the admin Goto -> System ->Configuration, and on the bottom of the list select “Developer”

2. Select the Log Settings tab and put Enabled = Yes

3. *to avoid any permissions issues, create folder/file

/var/log/system.log

Turn on SQL logging

To enable SQL Debugging find the file

/lib/Varien/Db/Adapter/Pdo/Mysql.php

change line 45
protected $_debug = false;

to
protected $_debug = true;

It will then generate the file var/debug/sql.txt.

*If you have any issues create this file manually first…

Display PHP errors

Frustrated you can’t see your PHP errors? This is how you turn them on – for development use only, don’t do this on a production site!

In Index.php change

Mage::setIsDeveloperMode(true);

ini_set(‘display_errors’, 1);

mac freeze login steam

You should now be able to see the Steam folder, and the registry.vdf file inside that. Simply rename the file, or delete the full stop so that Steam doesn’t recognise the file (you can delete the file, but best to rename first as if this fails, you might want to be able to revert back).

Once the file has been renamed, you should be able to start up Steam and get back online. Note: if the above fails, try following all of the steps again but rather than starting up Steam, re-install it instead.

Worked for me – I’m now back online.

http://steamcommunity.com/discussions/forum/2/828934724089990063/

multiple domain to subfolder htaccess rewrite


RewriteEngine On
RewriteBase /

# —————————————
# BEGIN Domain to folder mapping

# pointing so9sad.com to folder_1
ReWriteCond %{HTTP_HOST} so9sad.com
ReWriteCond %{REQUEST_URI} !so9sad/
ReWriteRule ^(.*)$ so9sad/$1 [L]

# pointing youtube9loop.com to folder_2
ReWriteCond %{HTTP_HOST} youtube9loop.com
ReWriteCond %{REQUEST_URI} !youtube9loop/
ReWriteRule ^(.*)$ youtube9loop/$1 [L]

# END Domain to folder mapping
# —————————————

# —————————————
# BEGIN htaccess pretection


order allow,deny
deny from all

# END htaccess pretection
# —————————————

With wordpress:

RewriteEngine On
RewriteBase /

# —————————————
# BEGIN Domain to folder mapping

# pointing domain_1.com to folder_1
ReWriteCond %{HTTP_HOST} domain_1.com
ReWriteCond %{REQUEST_URI} !folder_1/
ReWriteRule ^(.*)$ folder_1/$1 [L]

# pointing domain_2.com to folder_2
ReWriteCond %{HTTP_HOST} domain_2.com
ReWriteCond %{REQUEST_URI} !folder_2/
ReWriteRule ^(.*)$ folder_2/$1 [L]

# END Domain to folder mapping
# —————————————

# —————————————
# BEGIN WordPress

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress
# —————————————

# —————————————
# BEGIN htaccess pretection


order allow,deny
deny from all

# END htaccess pretection
# —————————————

ref: http://wordpress.org/support/topic/success-mapping-multiple-domains-to-different-folders-with-htaccess

[android] center a drawText

For y :

int yPos = (int) ((canvas.getHeight() / 2) – ((paint.descent() + paint.ascent()) / 2)) ; //((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.

For x :

http://stackoverflow.com/questions/4909367/how-to-align-text-vertically

Solve WebView problem

 

add this back

http://code.google.com/p/android/issues/detail?id=20446


code.google 有discuss

http://code.google.com/p/android/issues/detail?id=25722


http://stackoverflow.com/questions/5213635/honeycomb-hardware-acceleration

try this, turn off the alpha channel (no use)


http://thehelios.wordpress.com/2012/09/13/hardware-acceleration-on-android-4-0/

more ref, and have many hints !

http://developer.android.com/guide/topics/graphics/hardware-accel.html


change to translateX (try)


http://stackoverflow.com/questions/13500452/android-webview-renders-blank-white-view-doesnt-update-on-css-changes-or-html

or read this


add this
-webkit-overflow-scrolling: touch;

http://stackoverflow.com/questions/11370418/scrolling-through-touchmove-is-choppy


http://developer.android.com/reference/android/webkit/WebSettings.html

change RenderPriority and CACHE SETTING (try)


https://groups.google.com/forum/?fromgroups=#!topic/android-developers/4YATUvb-t68

try large heap true (try)


change all png to jpg
(no transparency channel in yr app)


smooth transition trial

1. try webkit back face visibility hide
2. try the slide animation time is linear ie deltaX * 10ms, but not diff distance but same time
3. try window.location.href = “#body” to do a fast auchor

good luck

活用 CI log to know a model is loaded

You can use the log_message() function and put it in the constructor, so it will be executed when it initiated

Put this in your model’s constructor (parent::Model())

log_message (“debug”, “Yourmodel is loaded”);
don’t forget to set the log config to debug mode, see the config.php file

$config[‘log_threshold’] = 2;
And set the system/logs directory permission to writable (by default CI will create the log files here)

or set the logs directory in another dir

$config[‘log_path’] = ‘another/directory/logs/’;
CI will then create the log file in the directory. monitor the log files as you like. You can get the debug message to see if your model is already loaded or not in the log files.

src : http://codeigniter.com/forums/viewthread/180787/

save me time ! solve BeanCreationException for TilesConfigurer

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ’tilesConfigurer’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.servlet.view.tiles2.TilesConfigurer]: Constructor threw exception;

http://richardbarabe.wordpress.com/2009/02/23/apache-tiles-2-integration-with-spring-mvc/

Update:

add this dependencies to solve :
[xml]
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-el</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-template</artifactId>
<version>2.2.2</version>
</dependency>
[/xml]

FLEX module的使用(转载)

1 ModuleLoader组件概述
1.1Module技术简介
flex的Modules技术是可以被flex程序使用的一个swf文件,它不能脱离程序独立运行,但是多个程序之间可以共享它。
flex的Modules技术将应用程序分割成小块、模块,主程序动态的加载所需要的模块。主程序在启动时并不全部加载所有的模块。当用户和模块没有交互的时候它不需要加载模块,同时它在模块不需要的时候可以卸载模块并释放内存和资源。[1]

flex的Modules技术主要有如下的优点:
让swf文件初始下载尺寸更小
让加载时间更短
对应用程序更好的封装性

1.2ModuleLoader组件功能
ModuleLoader组件是一种可视化的组件,方便开发人员在运行期间动态地加载和卸载module。
注:加载:从服务器下载到浏览器中

1.3 ModuleLoader类的继承关系
包:mx.modules[2]
ModuleLoaderInheritanceVBoxInheritanceBoxInheritanceContainerInheritanceUIComponent
注:ModuleLoader类暂无spark组件

相关类:
* IModuleInfo – module接口,所有的module都实现了此接口,可以提供module信息,比如url 和 加载状态。
* Module – 基于MXML的module的基类
* ModuleBase –基于ActionScript的module基类
* ModuleManager –一个系统只有一个此类,用于管理所有动态加载的module
* ModuleEvent – module相关事件

1.4 相似组件
(1)SWFLoader
ModuleLoader与swfLoader组件功能相同
ModuleLoader要求加载的SWF文件必须实现接口IFlexModuleFactory,这样,ModuleLoader通过工厂模式可以根据需要创建多个实例。
swfLoaderr组件对于SWF文件没有任何要求。

(2)ViewStack
ModuleLoader与ViewStack的作用比较类似,都用于加载多个不同模块。
ModuleLoader只能加载module,而且一次只能从服务器加载一个。ModuleLoader不必在初始化时携带加载所有的孩子组件,节省了下载量。
ViewStack一次加载多个容器,比如panel,cavas,但是可以延时初始化,以提高速度。ViewStack必须下载所有孩子组件后,只对当前使用的孩子组件进行初始化,加快显示速度。

(3)ModuleManager
ModuleLoader组件提供了可视化的加载和卸载module的操作。
ModuleManager类提供了低层次的处理Module的装载卸载以及事件响应等方法。这种方式比起纯粹的 ModuleLoader方式稍微复杂一点,但是ModuleManager提供了比ModuleLoader更加强大的能力来管理Module模块的加 载过程。

(4)RSL
RSL和module都是代码独立和复用机制[3]
Modules被编译到SWF文件内,可以加载和卸载
类库被编译到SWC文件内,可以在编译期间使用并编译到application中,并在application运行前加载

参考文献
[1]Modularapplicationsoverview.http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-799a.html
[2]ModuleLoader类.http://www.adobe.com/devnet/flex/tourdeflex/langref/mx/modules/ModuleLoader.html
[3] Flex Modules . http://www.flexafterdark.com/docs/Flex-Modules

2 ModuleLoader常用属性和方法
@font-face { font-family: “宋体”; }@font-face { font-family: “@宋体”; }p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0cm 0cm 0.0001pt; text-align: justify; font-size: 10.5pt; font-family: “Times New Roman”; }div.Section1 { page: Section1; }
名称
分类
说明
applicationDomain
属性
ApplicationDomain类,将你的模块加载到哪个应用域,详见例3.9
url
属性
String类型。要加载的外部MXML module 的url.,详见例3.1和例3.2
loadModule
方法
格式:loadModule (url:String = null, bytes:ByteArray = null):void
加载module,详见例3.2
unloadModule
方法
格式:unloadModule():void
卸载module,释放内存,详见例3.2
error
事件
当module抛出错误时派发,参见例3.3
loading
事件
当ModuleLoader开始根据URL加载module时派发
progress
事件
Module加载过程中以一定的间隔周期派发,参见例3.3
ready
事件
当module完成加载时派发,参见例3.3
setup
事件
当module已下载(通过info()函数访问),但module并没有加载完成时(not ready)派发
unload
事件
当module卸载完成时派发,参见例3.3
urlChanged
事件
当ModuleLoader有了一个新的URL时派发

3 ModuleLoader使用方法
3.1 通过URL自动加载module和Alert使用举例
功能说明
通过loadModule加载外部的WelcomeModule,点击module中的alert,显示欢迎

关键代码
ModuleLoaderExam1.mxml


说明:
(1)如果在module中使用Alert,必须声明PopUpManager,并且实例化,原因未知。
(2) creationComplete事件表示,当加载完成时,将当前应用程序的域赋给module1,这个语句可以不加,为防万一,最好加上。

ModuleExam1.mxml
protected function openAlert_clickHandler(event:MouseEvent):void
{
Alert.show(“欢迎”, “欢迎点击Alert”, Alert.OK, this);
}

代码详见:ModuleLoaderExam1.mxml和ModuleExam1.mxml

3.2手工加载和卸载module举例
功能说明
通过设置URL属性,手工加载和卸载module
函数说明:loadModule (url:String = null, bytes:ByteArray = null):void
url:默认为null,表示当前要加载的module的URL,如果ModuleLoader的URL不为null,则该方法无效
bytes:module的SWF文件的字节数,可以通过URLLoader类获取

关键代码
ModuleLoaderExam2.mxml
public function loadModule21():void
{
if(mod_loader.url==null)
mod_loader.url = “example/ModuleExam21.swf”;
}
public function loadModule22():void
{
mod_loader.loadModule(“example/ModuleExam22.swf”);
}
public function unload():void
{
mod_loader.unloadModule();
mod_loader.url = null;//注意,卸载完成后必须设置URL为null,否则内存泄露
}

说明:
(1)mod_loader.url的值被修改后,直接触发重新加载module,不必再调用loadModule方法
(2) mod_loader.url = null;必须在卸载完成后加上,否则内存泄露

代码详见:ModuleLoaderExam2.mxml、ModuleExam21.mxml和ModuleExam22.mxml

3.3 module常用事件举例
功能说明
演示常用事件的处理,module的常用事件包括
Error:加载错误时引发
Ready:加载完成后引发
Progress:加载过程中定时引发
Unload:卸载完成后引发

关键代码
ModuleLoaderExam3.mxml

protected function mod_loader_errorHandler(event:ModuleEvent):void
{
lbRecord.text=lbRecord.text+”n error:”+event.module.url;
}
protected function mod_loader_readyHandler(event:ModuleEvent):void
{
lbRecord.text=lbRecord.text+”n ready:”+event.bytesLoaded+”bytes:”+event.bytesTotal;
}
protected function mod_loader_progressHandler(event:ModuleEvent):void
{
lbRecord.text=lbRecord.text+”n progress:”+event.bytesLoaded+”bytes:”+event.bytesTotal;
}
protected function mod_loader_unloadHandler(event:ModuleEvent):void
{
lbRecord.text=lbRecord.text+”n unload:”+event.bytesLoaded+”bytes:”+event.bytesTotal;
}
代码详见:ModuleLoaderExam3.mxml、ModuleExam21.mxml和ModuleExam22.mxml

3.4 Application调用module中的方法举例
功能说明
演示Application程序如何调用module中的方法
Application并不能直接访问module提供的方法,而是通过moduleLoader中的属性child来完成的。

关键代码
ModuleLoaderExam4.mxml

private function getTitle():void {
s = (m1.child as ModuleExam4).getModTitle();
}

ModuleExam4.mxml
public function getModTitle():String {
return “Child Module 1”;
}
说明:
(m1.child as ModuleExam4).getModTitle(),表示将m1中的属性child对应的对象强制转换为ModuleExam4类,再调用这个对象的方法。

代码详见:ModuleLoaderExam4.mxml和ModuleExam4.mxml

3.5 通过ModuleLoader的URL向module传递参数举例
功能说明
通过URL属性向module传递参数
GET参数基本上是这种格式,url=module1.swf?param1=value1&param2=value2

关键代码
ModuleLoaderExam5.mxml
public function submitToModule():void {
var s:String = “example/ModuleExam5.swf?”
+ “firstName=” +ti1.text + “&lastName=” + ti2.text;
m1.url = s;
}

ModuleExam5.mxml
//对参数进行过滤
var myPattern:RegExp = /.*?/;
var s:String = this.loaderInfo.url.toString();
s = s.replace(myPattern, “”);
// 通过&拆分成数组name=value,保存为String类型数据
var params:Array = s.split(“&”);
// 显示数组中各个元素的值
var keyStr:String;
var valueStr:String;
var paramObj:Object = params;
for (keyStr in paramObj) {
valueStr = String(paramObj[keyStr]);
ta1.text += keyStr + “:” + valueStr + “n”; //keyStr的值为0。1.2…
}
// 通过=拆分各个元素,并保存到变量salutation中
for (var i:int = 0; i < params.length; i++) { var tempA:Array = params[i].split("="); if (tempA[0] == "firstName") { o.firstName = tempA[1]; } if (tempA[0] == "lastName") { o.lastName = tempA[1]; } } 代码详见:ModuleLoaderExam5.mxml和ModuleExam5.mxml 3.6利用ActionScript接口实现Module与Application数据交互举例 功能说明 对于Module模块和Application对象间的通信,可以定义一个ActionScript接口,Module模块对象实现了这个接口中定义的方 法和属性,那么Application就可以访问这个接口中定义的属性和方法。接口中定义了Module模块对象和Application需要共享的数据 和方法,是两者间共同的一个契约,同时也实现了接口和实现的分离,达到了松耦合的目的。 接口类IModuleInterface.as: public interface IModuleInterface extends IEventDispatcher { function getModuleName():String; function setAdjusterID(s:String):void; function setBackgroundColor(n:Number):void; } ModuleExam6.mxml 模块必须实现以上接口,代码如下
public function setAdjusterID(s:String):void {
adjuster = s;
}
public function setBackgroundColor(n:Number):void {
bgcolor = n;
}
public function getModuleName():String {
return “module Insurance”;
}
说明:
这个module实现了接口中的三个方法。

ModuleLoaderExam6.mxml
private function applyModuleSettings(e:Event):void {
// m1.child 是接口IModuleInterface的具体实现对象
//var ichild:* = mod.child as IModuleInterface;
var ichild:IModuleInterface = m1.child as IModuleInterface;
if (m1.child != null) {
ichild.setAdjusterID(myId.text);
ichild.setBackgroundColor(myColor.selectedColor);
}
//从接口获取模块的名称
currentModuleName = ichild.getModuleName();
}
说明:
Application通过接口中的方法setAdjusterID和setBackgroundColor向module传递数据,
Module通过接口中的方法getModuleName向Application传递数据
代码详见:ModuleLoaderExam6.mxml、ModuleExam6.mxml和IModuleInterface.as

3.8 Module与Module之间数据交互举例
功能说明
一个Application如果具有两个Module,这两个Module可以通过Application传递数据。原理如下:




在module1中,你可以通过以下方法访问module2的属性和方法
parentApplication.module2.child.someProperty;
parentApplication.module2.child.someMethod();

关键代码
ModuleLoaderExam7.mxml

ModuleExam71.mxml
[Bindable]
public var m1:String=”module1″;
public function getProperty(event:MouseEvent):void {
lbmodule2.text=parentApplication.module2.child.m2;
}
public function getMethod(event:MouseEvent):void {
lbmodule2.text=parentApplication.module2.child.getModuleName();
}



说明
getProperty函数功能:直接访问module2中的属性m2
getMethod函数功能:通过调用module2中的函数getModuleName获取文本输入框的值

ModuleExam72.mxml
[Bindable]
public var m2:String=”module2″;
public function getModuleName():String {
return lbmodule2.text;
}

说明
m2与lbmodule2之间的绑定是单向的,修改m2的值,则改变lbmodule2的text,修改lbmodule2的值并不影响m2的值
代码详见:ModuleLoaderExam7.mxml、ModuleExam71.mxml和ModuleExam72.mxml

参考文献

Flex Modules . http://www.flexafterdark.com/docs/Flex-Modules

3.9 applicationDomain属性举例
功能说明
ApplicationDomain 类是一个容器,用于管理不同swf的安全域和类之间的关系。它们允许同一个类存在不同的ApplicationDomain。
ApplicationDomain是一个树形结构,Application所在的域(以下简称主域)就是它唯一的子域,使用Loader类加载swf时可以通过指定ApplicationDomain 参数将swf加载到不同的域(Domain)。
ApplicationDomain最根部的是系统域(system domain),主程序所在的域(以下简称主域)就是它唯一的子域。SWF 文件中的所有代码被定义为存在于应用程序域(ApplicationDomain)中。主应用程序在”当前域”中运行。”系统域”中包含所有应用程序域 (包括当前域),也就是,它包含所有 Flash Player 类。
所有应用程序域(除系统域外)都有关联的父域。主应用程序的应用程序域的父域是系统域。已加载的类仅在其父级中没有相关定义时才进行定义。不能用较新的定义覆盖已加载类的定义。

有两种方式可以访问 ApplicationDomain :
(1)ApplicationDomain.currentDomain
currentDomain是ApplicationDomain的静态变量,表示当前代码所在的域。例如:该变量在主程序里指向主域,在加载到子域的模块里和currentDomain则指向该模块所在的子域。
参见例3.1,通过URL自动加载module和Alert使用举例

虽然 ApplicationDomain有个 parentDomain 属性,但子域已经自动获得了父域的类定义,所以通过 ApplicationDomain.currentDomain 就可以获取父域定义了——包括主程序和加载到主域的共享库。(注:系统域不可直接访问,主域和所有新域即系统域子域的parentDomain属性为 null)
参见例3.8,Module与Module之间数据交互举例

(2)LoaderInfo类的applicationDomain属性
此方式可以访问任何方式加载的swf的 ApplicationDomain。对于主程序来说,加载到同域的库定义已经存在于 ApplicationDomain.currentDomain ,而模块的类主程序一般用不到。所以这种方式个人不推荐使用。
使用Loader类加载swf时可以通过指定 ApplicationDomain参数将swf加载到不同的域(Domain):
var loader : Loader = new Loader();
var context : LoaderContext = new LoaderContext();
/* 加载到子域(模块) */
context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
/* 加载到同域(共享库) */
context.applicationDomain = ApplicationDomain.currentDomain;
/* 加载到新域(独立运行的程序或模块) */
context.applicationDomain = new ApplicationDomain();
loader.load(new URLRequest(“loaded.swf”), context);

(1)加载到子域(module)—参见图中的用法C
类似于“继承”,子域可以直接获得父域所有的类定义,反之父域得不到子域的。和继承关系不同的是,如果子域中有和父域同名的类,子域定义的类会被忽略而使用父域的定义的类。最大特点是可以动态的加载和移除。便于垃圾回收。
context.applicationDomain = new
ApplicationDomain(ApplicationDomain.currentDomain);
说明创建一个新的域,并变成当前域的子域

(2)加载到同域(RSL) —参见图中的用法B
就是在当前的ApplicationDomain添加新的类定义。类似集合里的合并关系。被加载swf里的所有类定义被合并到当前域中可以直接使用。和加载到子域相同,和当前域同名的定义也会被忽略。
context.applicationDomain = ApplicationDomain.currentDomain;

(3)加载到新域(独立运行的程序或模块) —参见图中的用法A
用的不是很多,实际上是单独的创建一个新的域和当前应用程序域平级。作为系统域的真子集。
swf载入指定域之前,先要检查该域及其父域中是否存在同名类,重复定义一概忽略。如果加载别人写的程序,或者使用旧版本的主程序加载新版本的模块,为避免类名冲突就要加载到新域独立运行以使用自己的类。
context.applicationDomain = new ApplicationDomain();
loader.load(new URLRequest(“loaded.swf”), context);
说明:创建了一个新的域,并加载到独立的程序loaded.swf中。

模块加载到同域不是一样可以吗?为何要加载到子域呢?
好处就在于,卸载一个加载到子域的模块时,只要确保清除所有到该模块的引用,模块的所有类定义将被垃圾回收(Garbage Collection)。

关键代码
ApplicationDomain中的currentDomain属性使用参见例3.1
ApplicationDomain中的parrentDomain属性使用参见例3.8

参考文献
1. Flex 中ApplicationDomain. http://www.wedoswf.com/questions/935
2. flash 中的 ApplicationDomain . http://chaimzane.javaeye.com/blog/470987
3. AS3应用程序模块化开发与ApplicationDomain . http://hereson.javaeye.com/blog/192337

3.10 module中使用PopUpManager和DragManager异常说明
通常将module加载为主域的一个子域,module里面的类都不属于主域的。比如第一个module载入了类PopUpManager,那么整合到 Application中,它就成了PopUpManager的拥有者,因为像这种manager都是单例的,如果另外一个模块稍后要使用这个 PopUpManager,就会引发运行时异常。
解决办法就是确保这些managers,比如PopUpManager和DragManager或者其他一些共享的服务是在application中定义的,这样就能确保所有模块都能够使用,代码如下:
import mx.managers.PopUpManager;
import mx.managers.DragManager;
private var popUpManager:PopUpManager;
private var dragManager:DragManager;

这项技术同时也被应用到组件中,当module第一次使用组件时,将在它自己的域中拥有这些组件的类定义。如果别的module试图使用这些已经被另一个 module使用的组件,它的定义将会不能匹配到现存的定义中。因此,为了避免组件的定义不匹配,在主应用程序中创建组件的实例,让所有的module去 引用。
但是这个坏处很明显,这些声明看起来莫名其妙,成为了一个个”木偶变量”。另一个解决方法是借助 ApplicationDomain 来共享这些代码和资源。在ModuleLoader 的creationComplete方法中加入moduleLoader.applicationDomain = ApplicationDomain.currentDomain; 表示将其加载到运行时库。对于使用ModuleManager,则可以在IModuleInfo的load方法里指定域。

参见:
flash.system.ApplicationDomain
flash.system.SecurityDomain

When to new your model?

http://joelhooks.com/2011/03/12/an-introduction-to-robotlegs-as3-part-2-models/

you dun need actually
public class AuthorModel extends Actor
{
private var _list:Array;

public function get list():Array
{
if(!_list)
initializeList();
return _list;
}

protected function initializeList():void
{
var twain:Author = new Author(“Twain”);
var poe:Author = new Author(“Poe”);
var plato:Author = new Author(“Plato”);
var fowler:Author = new Author(“Fowler”);

twain.quote = “Why, I have known clergymen, good men, kind-hearted, liberal, sincere” +
“, and all that, who did not know the meaning of a ‘flush.’ It is enough ” +
“to make one ashamed of one’s species.”;
fowler.quote = “Any fool can write code that a computer can understand. ” +
“Good programmers write code that humans can understand.”;
poe.quote = “Deep into that darkness peering, long I stood there, wondering, ” +
“fearing, doubting, dreaming dreams no mortal ever dared to dream before.”;
plato.quote = “All things will be produced in superior quantity and quality, and with greater ease, ” +
“when each man works at a single occupation, in accordance with his natural gifts, ” +
“and at the right moment, without meddling with anything else. “;

_list = [twain,fowler,poe,plato];
}
}

got it ?

solve module load in flex, getStyle problem

Flex App 直接引用外部 Module 的問題
最近同事遇到一個 Flex 問題,只要 Module 內放了其它組件
執行就會出現各種奇怪 Error
後來發現是因為在 Main Application 直接引用編譯到 Module Class
然後又企圖用 ModuleLoader 再載入一次相同的 Module SWF
當然這樣做是錯誤的範例,Flash Builder 也會給予警告

Warning: Mod is a module or application that is directly referenced.
This will cause Mod and all of its dependencies to be linked in with MainApp.
Using an interface is the recommended practice to avoid this.

不要明確引用就正常了
不過還是覺得有點不合理,至少應該能正常執行吧

譬如以下的例子 MainApp.mxml










直接引用到外部 Module,又企圖載入一次同一個外部 Module – Mod.mxml





隨著 Module 內放置組件不同,可能會得到以下各種錯誤訊息

Main Thread (Suspended: ArgumentError: Error #2004: 有一個參數無效。)
flash.display::Graphics/drawRect [no source]
spark.components.supportClasses::TextBase/updateDisplayList
mx.core::UIComponent/validateDisplayList
mx.managers::LayoutManager/validateDisplayList
mx.managers::LayoutManager/doPhasedInstantiation
mx.managers::LayoutManager/doPhasedInstantiationCallback

Main Thread (Suspended: TypeError: Error #1009: 無法存取 Null 物件參考的屬性或方法。)
mx.core::UIComponent/getStyle
mx.core::UIComponent/getConstraintValue
mx.core::UIComponent/get horizontalCenter
spark.layouts::BasicLayout/measure
spark.components.supportClasses::GroupBase/measure
mx.core::UIComponent/measureSizes
mx.core::UIComponent/validateSize
spark.components::Group/validateSize
mx.managers::LayoutManager/validateSize
mx.managers::LayoutManager/doPhasedInstantiation
mx.managers::LayoutManager/doPhasedInstantiationCallback
Flex ModuleLoader 預設載入外部 Module 時
是會從目前 ApplicationDomain 建立一個 child ApplicationDomain 作為載入之用
也就是說假如 Main App 已經包含一份 Module 定義
再載入同名類別,就會被前面的類別定義覆蓋
實際上,被 new 出來的實體其實是 Main App 內定義的

假如兩份定義完全一樣,應該也是要能正常執行吧
問題就是出在這裡了,用 ASV 分別去觀察兩個 SWF 內的 Module 類別
發現是不一樣的!

當 Flex Module 編譯為獨立 SWF 時
MXMLC Compiler 會塞入一些額外的 Metadata Tag, Code… 做初始化
可是 MainApp 內的 Module 定義少了這些動作,導致無法正常執行

解決的方式不難,ModuleLoader Ready 時
自己手動執行一下關鍵的初始動作就好了 – styleManager.initProtoChainRoots();








robotlegs in module, 3 種方法解決

1. http://joelhooks.com/2010/05/02/modular-robotlegs/

裝呢個 addon, 共用同一個 injector,
但不能使用 module loader

min code of this method
http://blog.yoz.sk/examples/ModularRobotlegs/srcview/

2. http://labs.riamore.com/content/robotlegs/examples/dynmodules

可以 dynamic 了,但其實是將 module 的 applicationDomain hardcore 同 mainApp 一樣

3. http://ticore.blogspot.com/2011/10/robotlegs-module-issue.html

一人一個獨立 robotlegs,但要 hack 少少 code 先做到,其實都係 override 下 je 🙂

js object and js function class

var yung = { variable : xxx, add: function () { } }

they are all accessible by other

yung.Class = function(someSetting) {

var privateVar
this.publicVar
function privateFunction
function publicFunction

//public function
$.extend(this, {
publicFunction: publicFunction
});

yung.obj = new yung.Class(someSettings);

}

scope:

(function(object1, jquery, window, settings) {

code….

})(object1, jquery, window, settings);

blackberry debug token

http://docs.blackberry.com/en/developers/deliverables/27280/Running_unsigned_apps_debug_tokens_1585072_11.jsp

http://docs.blackberry.com/en/developers/deliverables/27280/Configure_app_signing_from_cmd_line_1463563_11.jsp

About Configuring your application
http://docs.blackberry.com/en/developers/deliverables/27280/Configuring_your_application_1524626_11.jsp

About tablet xml
http://docs.blackberry.com/en/developers/deliverables/23959/Configuring_your_application_1524626_11.jsp

trick on as2

dynamic new a movieClip with init var
http://www.jonnyreeves.co.uk/2007/05/movieclips-and-object-scope-in-as2/

WORTH to read, many FAQ about as2
http://www.senocular.com/flash/tutorials/faq/#newmovieclip

event receive and dispatch and delegate example
http://flash-creations.com/notes/asclass_eventdispatcher.php

hope example help
http://www.bit-101.com/blog/?page_id=1164

reference will be missed at first explanation
http://stackoverflow.com/questions/896335/referencing-movie-clip-class-instances-immediately-in-actionscript-2

EventDispatcher instantiate methods
http://archive.darronschall.com/weblog/2004/03/the-many-faces-of-eventdispatcher.html

container constructor first -> button constructor
container constructor want to call button stuff, but button hvnt construct
http://www.kirupa.com/forum/showthread.php?241544-AS2-0-Linkage-and-attachMovie-Woe

wtf bitmapData

SWF 13+ (Flash Player 11, AIR 3) the practical limit is the amount of memory available. (The theoretical limit to width or height is the largest positive integer — divided by 20 to allow for twips, but you will hit memory limits long before reaching this size.)
SWF 10 (Flash Player 10, AIR 1.5) the maximum size for a BitmapData object is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a BitmapData object is 8,191 pixels wide, it can only be 2,048 pixels high.)
SWF 9 (Flash Player 9, AIR 1.1) the limitation is 2,880 pixels in height and 2,880 pixels in width. If you specify a width or height value that is greater than 2880, a new instance is not created.

Flash Player 11 is very good 🙂
Flash Player 10 need alchemy 🙁
Flash Player 9 no byteArray, so no need think of playing dynamic image processing :((

WTF Flex 4.5.1 eat shit SDK for UIComponent

TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChildAt()
at fl.controls::BaseButton/drawBackground()
at fl.controls::LabelButton/draw()
at fl.core::UIComponent/drawNow()
at fl.controls::ScrollBar/draw()
at fl.core::UIComponent/callLaterDispatcher()

I know u meet this error

i know you read this:
http://joshblog.net/2008/02/10/how-to-use-the-flash-cs3-component-set-in-a-flex-builder-actionscript-project/

or this
http://de-co-de.blogspot.com/2008/03/wheres-my-skin.html

but still cant play the UIScrollbar
What i think is, i the past, i use this method still can use, i think it is the issue of flex sdk, okok,

i got it

// trick to bring in the skins for the button
sb.setStyle( “ScrollArrowDown_downSkin”, new ScrollArrowDown_downSkin());
sb.setStyle( “ScrollArrowDown_overSkin”, new ScrollArrowDown_overSkin());
sb.setStyle( “ScrollArrowDown_upSkin”, new ScrollArrowDown_upSkin());
sb.setStyle( “ScrollArrowUp_disabledSkin”, new ScrollArrowUp_disabledSkin());
sb.setStyle( “ScrollArrowUp_downSkin”, new ScrollArrowUp_downSkin());
sb.setStyle( “ScrollArrowUp_overSkin”, new ScrollArrowUp_overSkin());
sb.setStyle( “ScrollArrowUp_upSkin”, new ScrollArrowUp_upSkin());
sb.setStyle( “ScrollBar”, new ScrollBar());
sb.setStyle( “ScrollTrack_skin”, new ScrollTrack_skin());
sb.setStyle( “ScrollThumb_downSkin”, new ScrollThumb_downSkin());
sb.setStyle( “ScrollThumb_overSkin”, new ScrollThumb_overSkin());
sb.setStyle( “ScrollThumb_upSkin”, new ScrollThumb_upSkin());
sb.enabled = true;
sb.visible = true;

add this, where sb is the scrollbar object 🙂

by pass as3 8191px problem

Core Concept : Dun draw in bitmap

Example:
in urUploader, Thumbnail can over 8191px, loadBytes is according to file size, so if file size too large, yr machine will hang.

[as3]private function genThumbnail():void {
var l:Loader = new Loader();
l.loadBytes(transcodeManager.baAlchemy);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, onThumbnailComplete);
}

private function onThumbnailComplete(e:Event):void {
var b:Bitmap = MCUtil.scaledImage(Bitmap(e.target.content).bitmapData, new ThumbnailLayout().width);
_thumbnail.addChild(b);

var data:Object = { uploadJob : this };
dispatchEvent(new UploadJobEvent(UploadJobEvent.THUMBNAIL_GENERATED, data));
}

[/as3]
This is the scale function, so after scale to small size, now can draw 🙂

[as3]public static function scaledImage(bd:BitmapData, s:Number = 120) : Bitmap
{
var newWidth:Number;
var newHeight:Number;
var result:BitmapData;
var bitmap:BitmapData = bd;
var size:Number = s;
var matrix:Matrix = new Matrix();
try
{
if (bitmap.width > bitmap.height)
{
newWidth = size;
newHeight = bitmap.height * (size / bitmap.width);
}
else
{
newHeight = size;
newWidth = bitmap.width * (size / bitmap.height);
}
matrix.scale(newWidth / bitmap.width, newHeight / bitmap.height);
result = new BitmapData(newWidth, newHeight);
result.draw(bitmap, matrix);
bitmap.dispose();
return new Bitmap(result);
}
catch (e:Error)
{
trace("Scaled image error");
}
return null;
}// end function[/as3]

ref: photobox photobook program

alchemy, libjpeg ref

日文翻譯文,教你裝同 run
http://www.4ucode.com/Study/Topic/678551

http://www.4ucode.com/Study/Topic/677284

原文,日文
http://d.hatena.ne.jp/amachang/20081118/1227005285

教你用 libjpeg
http://blog.csdn.net/achellies/article/details/4238056

MUST WATCH
Blog
http://www.websector.de/blog/2009/06/21/speed-up-jpeg-encoding-using-alchemy/

config alchemy
http://wiki.zeropointnine.com/?n=FlashPlatform.Alchemy

how to include jconfig.h, jpeglib.h …
http://forums.adobe.com/message/1059134#1059134

using alchemy to do bubble sort
http://blog.comtaste.com/2010/07/adobe_alchemy_a_comparative_ex.html

simple explanation on bytecode

AS3 -> ABC (bytecode) -> AVM (Flash player) -> Windows, Linus, Mac…
落 bytecode 等唔同 OS 既 VM 都行到,但 點解唔直行 AS3 要 compile 落 bytecode ,因為你寫d 野太7 ,變做 While Loop,改你d var, function 名 改短d 靚d 好過 🙂

flash is suck in urlStream or fileRef.upload

urlStream is always good, it trigger the browser request to server, but very raw and cannot detect the upload progress (no progress event fire during upload) ( cal the speed and use Timer to pretend the progress bar )

but fileRef.upload is really poor, it use its user agent, so it is independent to browser, so no session can be save, it make a new session i think

judge yourself use which class then 🙂

skype development ref

@ww_boy6 roy:
wwboy: http://skype.sourceforge.jp/index.php?Skype%20API%20For%20Java%20(English)
roy:
this can help ?
roy:
actually they think so 麻煩 becoz they want to do VOIP
roy:
but we only need msg
roy:
wwboy: https://imo.im/
roy:
u see this web app can do skype
roy:
http://developer.skype.com/skypekit/reference/java/html/com/skype/api/Message.html
roy:
for ww

URL request in Flash

IE -> 用 domain 做 base-path
Firefox, chrome -> 用 swf 個 file 個 location 做 base-path

okok, 唔好煩,用死 absolute path, server_url + relative_url 好無 ?

Note Update :

用呢個 “.” d swf location 就會係 swf 個個位置

[as2] some movieClip property you may always need

[as3] function resetStartProps():Void {
delete _startProps; //Aids in memory management
_startProps = {};
var sp = _startProps;
var axisPoint_obj = this.axisPoint;
var mdx = _targetObject._parent._xmouse – axisPoint_obj.x; //Distance to mouse along the x-axis
var mdy = axisPoint_obj.y – _targetObject._parent._ymouse; //Distance to mouse along the y-axis
var md = Math.sqrt(mdx * mdx + mdy * mdy); //Total distance to mouse
var angleAxisToMouse = Math.atan2(mdy, mdx);

var rdx = _targetObject._x – axisPoint_obj.x; //Distance between axis point and registration along the x-axis
var rdy = axisPoint_obj.y – _targetObject._y; //Distance between axis point and registration along the y-axis

var angle = _targetObject._rotation * (Math.PI / 180); //rotation translated to radians
var rAngleAxisToMouse = angleAxisToMouse + angle; //Rotated (corrected) angle to mouse (as though we tilted everything including the mouse position so that the _targetObject is at a 0 degree angle)

sp.centerX = this.centerX;
sp.centerY = this.centerY;
sp.axisX = axisPoint_obj.x;
sp.axisY = axisPoint_obj.y;
sp._x = _targetObject._x;
sp._y = _targetObject._y;
sp._xscale = _targetObject._xscale;
sp._yscale = _targetObject._yscale;
sp._rotation = _targetObject._rotation;
sp.angle = angle;
sp._xmouse = _targetObject._parent._xmouse;
sp._ymouse = _targetObject._parent._ymouse;
sp.angleAxisToMouse = (angleAxisToMouse + Math.PI * 2) % (Math.PI * 2);
sp.distAxisToMouseX = Math.cos(rAngleAxisToMouse) * md;
sp.distAxisToMouseY = Math.sin(rAngleAxisToMouse) * md;
sp.distAxisToMouse = md;
sp.distRegToCenterX = _targetObject._x – sp.centerX;
sp.distRegToCenterY = _targetObject._y – sp.centerY;
sp.distAxisToReg = Math.sqrt(rdx * rdx + rdy * rdy);
sp.angleAxisToReg = Math.atan2(rdy, rdx);

if (_bounds.xMax != undefined) { //If we need to constrain dragging to stay within a rectangle…
var bnds = _targetObject.getBounds(_targetObject._parent);
sp.xMin = _bounds.xMin + (_targetObject._x – bnds.xMin) + 1;
sp.xMax = _bounds.xMax – (bnds.xMax – _targetObject._x) – 1;
sp.yMin = _bounds.yMin + (_targetObject._y – bnds.yMin) + 1;
sp.yMax = _bounds.yMax – (bnds.yMax – _targetObject._y) – 1;

sp.angleAxisToTL = (Math.atan2(_bounds.yMin – axisPoint_obj.y, _bounds.xMin – axisPoint_obj.x) + (Math.PI * 4)) % (Math.PI * 2);
sp.angleAxisToTR = (Math.atan2(_bounds.yMin – axisPoint_obj.y, _bounds.xMax – axisPoint_obj.x) + (Math.PI * 4)) % (Math.PI * 2);
sp.angleAxisToBR = (Math.atan2(_bounds.yMax – axisPoint_obj.y, _bounds.xMax – axisPoint_obj.x) + (Math.PI * 4)) % (Math.PI * 2);
sp.angleAxisToBL = (Math.atan2(_bounds.yMax – axisPoint_obj.y, _bounds.xMin – axisPoint_obj.x) + (Math.PI * 4)) % (Math.PI * 2);
}

}
/**********************************************/
/* get-set Function */
/**********************************************/
function get centerX():Number {
return this.centerPoint.x;
}
function get centerY():Number {
return this.centerPoint.y;
}
function get centerPoint():Object {
var p = {x:_localCenterX, y:_localCenterY};
_targetObject.localToGlobal(p);
_targetObject._parent.globalToLocal(p);
return p;
}
function get axisX():Number {
return this.axisPoint.x;
}
function get axisY():Number {
return this.axisPoint.y;
}
function get axisPoint():Object {
var p = {x:_localAxisX, y:_localAxisY};
_targetObject.localToGlobal(p);
_targetObject._parent.globalToLocal(p);
return p;
}

/*****************************************************************************/
/* */
/* This is the function to find the relative center Point */
/* */
/*****************************************************************************/
function resetCenterPoint():Void {
var rotation_num = _targetObject._rotation;
_targetObject._rotation = 0; //We need to straighten it temporarily to measure accurately…
var bounds_obj = _targetObject.getBounds(_targetObject._parent);
var x1 = (bounds_obj.xMax + bounds_obj.xMin) / 2; //Find the center x-coordinate when the rotation is 0
var y1 = (bounds_obj.yMax + bounds_obj.yMin) / 2; //Find the center y-coordinate when the rotation is 0
var dx = x1 – _targetObject._x; //distance between the _targetObject’s registration point and center point along the x-axis
var dy = _targetObject._y – y1; //distance between the _targetObject’s registration point and center point along the y-axis
var radius = Math.sqrt((dx * dx) + (dy * dy)); //Find the distance between the _targetObject’s registration point and the center point.
var angle1_num = Math.atan2(dy, dx);
var angle = (rotation_num * (Math.PI / 180)) – angle1_num; //Total angle that we’re adding/moving (we have to subtract the original angle to just get the difference)
var x = _targetObject._x + (Math.cos(angle) * radius);
var y = _targetObject._y + (Math.sin(angle) * radius);
_targetObject._rotation = rotation_num; //Re-apply the rotation since we removed it temporarily.
var p = {x:x, y:y};
_targetObject._parent.localToGlobal(p);
_targetObject.globalToLocal(p);
_localCenterX = p.x;
_localCenterY = p.y;
}

/*****************************************************************************/
/* */
/* This is the function to find the relative X Y */
/* */
/*****************************************************************************/
function setAxis(x:Number, y:Number):Void { //x and y according the the _targetObject._parent’s coordinate space!
var p = {x:x, y:y}; //Make a point so that we can do localToGlobal()
_targetObject._parent.localToGlobal(p); //Translates the coordinates to global ones (based on _root)
_targetObject.globalToLocal(p); //Translates the coordinates to local ones (based on _targetObject)
_localAxisX = p.x;
_localAxisY = p.y;
}
[/as3]

[jquery] xxx.fn.funtionName() {} is prototype

Prototype

All objects have a prototype property. Whenever the interpreter looks for a property, it also checks the prototype. jQuery uses that extensively to add methods to jQuery instances.

var form = $(“#myform”);
form.clearForm; // undefined
form.fn.clearForm = function() {
return this.find(“:input”).each(function() {
this.value = “”;
}).end();
};
form.clearForm() // works for all instances of jQuery objects, because the new method was added to the prototype

(This example needs clarification: how does it modify the prototype when the word “prototype” doesn’t appear anywhere? The implication is that form.fn is simply an alias for form.prototype, but if that’s the case then it should be explained. :-?)

In javascript:the definitive guide 5 edition,dont add attibute to Object.prototype

something i learn from hactl

1. Dun leave a place easily, yes, u can still change yr job from AP to SA, but if u go too rapidly, u miss the skill building period.

2. Dun just follow a trend to build software. Say IPad, if ipad is hit and release app, then the hit is gone, u got only money. Build your career.

3. If u want to be developer, go other place out of HK. This is commercial place, we are only users. You can do what you want but you cant change the fact.

4. You can leave, if you learn most of the things. You can try to tell yourself wt u done n learnt. If u can tell, u learnt.

[apache][phpmyadmin] change phpmyadmin to 443 using default phpmyadmin package

idea: rewrite engine to make http => https

1. go to .htaccess in /usr/share/phpmyadmin

add
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

2. activate the rewrite engine by a2enmod rewrite , then restart apache2

3. make SSL cert, some command like the following
#openssl req $@ -new -x509 -days 365 -nodes -out /etc/apache2/apache.pem -keyout /etc/apache2/apache.pem

details: http://www.debianadmin.com/install-and-configure-apache2-with-php5-and-ssl-support-in-debian-etch.html

4. permission for the cerf : #chmod 600 /etc/apache2/apache.pem

5. Listen 443 in ports.conf

6. Set the phpmyadmin conf in sites-available:

# phpMyAdmin default Apache configuration
Alias /phpmyadmin /usr/share/phpmyadmin

DocumentRoot /usr/share/phpmyadmin
SSLEngine on
SSLCertificateFile “/etc/apache2/apache.pem”

Options Indexes FollowSymLinks
AllowOverride All
DirectoryIndex index.php


AddType application/x-httpd-php .php

php_flag magic_quotes_gpc Off
php_flag track_vars On
php_flag register_globals Off
php_value include_path .

# Authorize for setup


AuthType Basic
AuthName “phpMyAdmin Setup”
AuthUserFile /etc/phpmyadmin/htpasswd.setup

Require valid-user

# Disallow web access to directories that don’t need it

Order Deny,Allow
Deny from All


Order Deny,Allow
Deny from All

7. Finish.

Zinc, f-in-box 之 Z-drive 之謎?

flash流媒体播放器;讨论以内存流方式播放FLASH的技术

flash流媒体播放器:讨论以内存流方式播放FLASH的技术可行性?
来源: 发布时间:星期三, 2008年9月24日 浏览:44次 评论:0
这样可以实现保护flash文件,而且用flash做界面发布时不要带swf文件,很方便,国外有一个 Control 可以实现,大家一起来讨论一下这样实现的技术方案.
告诉你一个最简单的Method
前面步骤和播放文件一样设置
ShockwaveFlash1.Movie = ‘c:temptemp.swf ‘;

ShockwaveFlash1.EmbedMovie = True
ShockwaveFlash1.Movie = ‘-_-!! ‘;
这样swf就含在窗体文件(dfm)中了
发布的时候不用单独带swf文件

这样是可以了,如果想把一个SWF文件做成资源,启动时再载入怎么实现呢?
创建一个不可见、只能当前句柄的program可访问的虚拟硬盘

[轉載]
flashplayercontrol貌似就是以这种方式实现的
虚拟硬盘 这个玩大了
这样就必须用到驱动 flashplayercontrol用驱动不可能吧
反汇编 跟踪 发现真的搞了一个虚拟硬盘,生成了一个临时文件Z:FromMemory46A10F369771449587DE913EFC0A258C1E4ED7C01D28A43418DBF2CB92CC35E56.swf

http://www.plm.hk/Phpgm/archiver/tid-638.html

[mac][tricks]Use Tab To Switch Between Dialog Buttons

http://www.mactricksandtips.com/2008/10/use-tab-to-switch-between-dialog-buttons.html

The one single “bug” on Mac OS X by far is the ability to switch buttons in dialog boxes. For example I mean using Tab to go between OK, Cancel, Don’t Save etc. For a long while until today I had just got used to using the mouse. Although you can use some shortcut keys for Save, but these aren’t always reliable. Windows has the ability to tab through button options. Why not Mac? Well you can and it is blindingly obvious.
To enable you to tab through dialog boxes go to System Preferences > Keyboard & Shrotcuts. At the very bottom there will be an option saying about full keyboard access. Check the radio button that says “All Controls”.

Now when you find a dialog box (a new file in TextEdit is quickest), when you hit tab you will be able to move through the dialog box options. Very neat. As the option at the bottom states if you hit Control + F7 you will be able to change this setting, although I doubt would have to.

[as3] fscommand fix

fscommand(“exec”, “abc.exe”)
呢個你識用啦,將個 abc.exe 放係 fscommand 既 folder 到
好啦,但係好大問題就係 你想入 argument 入去 係唔 work
fscommand(“exec”, “abc.exe argu1”),無呢回事
咁點算好!

solution:

System.setClipBoard(cmd);

再用 C++ 寫個小 program
個 program 就係貼上 clipBoard 既字再 run
咁就乜 seven 都 run 到啦!
唔洗下下用 C++ 自己寫 flash player 或者 d zinc framework 咁煩~

[AS3] Zinc 夾 GAIA, d path 錯曬!

http://www.designdisclosure.com/2009/07/make-mdm-zinc-applications-with-the-gaia-framework-for-adobe-flash/
Solution here~

July 5, 2009 by Alistair Stead in ActionScript, Flash Comments ( 3 )
The Gaia Framework for Adobe Flash is a something I have been using for some time. It is one of the most useful frameworks I have found for use with Flash. It adds a great deal of useful functionality and can generate large swathes of source code that you would otherwise need to write from scratch. However it is a very lightweight and unobtrusive ActionScript framework, you are still free to build your flash application in the same way you always have. You can continue to use your existing workflow but also take advantage of the framework features such as scaffolding, swfAddress, SEO optimization and asset loading and pre-loading.

With all this said when using the Gaia Framework with MDM Zinc application wrapper you have a couple of issues to resolve.

File paths and references from the application executable.
External Interface calls.
Most flash developers are likely unfamiliar with developing installable applications so these issues may be daunting when first encountered. However once explained there are simple solutions to both these issues that I will explain in detail.

File Paths and References

When Flash is used within a website it is served by a webserver and files can always be referenced from the root of the website e.g. /flv/example-video.flv or relative to the location of the .swf e.g. flv/example-video.flv.

However when your .swf is running inside the MDM Zinc wrapper it can no longer reliably reference files using the absolute path from root or a relative path. To resolve this you will need to evaluate the location that the application is running at before creating a path to the files based on this computed path.

Zinc Context Object

To solve this problem I have created a singleton context object. This object allows me to run the required application setup code and access the application properties from everywhere within my Gaia based application.

package com.designdisclosure.utils.mdm
{
import mdm.*;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.display.*;

public class ZincContext extends Sprite
{
private static var _instance:ZincContext;
public var zincGlobals:ZincGlobals;

/**
* Public static method to instantiate the ZincContext object.
* @return ZincContext Object Instance
*/
public static function get instance():ZincContext
{
if(_instance === null)
{
_instance = new ZincContext(new SingletonEnforcer());
}

return _instance;
}

public function ZincContext(pvt:SingletonEnforcer):void
{
if(pvt == null)
{
throw new Error(“Error: Instantiation failed: Use ZincContext.instance instead of new.”);
}

// Initialize an MDMZinc application and create a callback method for when this is completed
mdm.Application.init(this, onMDMinit);
}

private function onMDMinit():void
{
// Use this method to setup your Zinc application
// This is the same as applicationDidFinishLaunching from cocoa
}

/**
* Get the absolute path to the application and its files.
* I use a VMWare machine during testing and found
* that the application path is alittle un-reliable
* and needs modification when running in the VM.
*/
public function getApplicationPath():String
{
var path:String = mdm.Application.path;

return path;
}

public function get isZincApplication():Boolean
{
return (getApplicationPath.length)? true : false;
}
}
}

internal class SingletonEnforcer {}
This object can be used to obtain the application path, an absolute location at which the Zinc application is running. The can then be used in any function the loads external resources. However here is the main problem within the Gaia framework. It is possible to update the path to the site.xml file that is loaded in main.as but even if you load the file from an absolute path the framework does not update the paths used to load any assets referenced in the xml file its self.

Fixing the file paths

Although my next suggestion is not by any means ideal as it involves modifying the framework, I have yet to find a better solution. This obviously will lead to problems when updating the framework to future revisions. However these changes re fairly limited in scope as it is only a single file SiteModel.as. Here are my modifications that inject the application path if it exists into any location where external files are loaded.

public function load(path:String):void
{
if (path == null) path = “site.xml”;
if (path != “xml/site.xml” && path != “site.xml”) GaiaDebug.log(“site.xml path = ” + path);
var request:URLRequest = new URLRequest(CacheBuster.create(ZincContext.instance.getApplicationPath()+path));
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.load(request);
}
private function parseSite():void
{
_title = _xml.@title || “”;
_preloader = _xml.@preloader || ZincContext.instance.getApplicationPath()+”preload.swf”;
_menu = (_xml.@menu == “true”);
_delimiter = _xml.@delimiter || “: “;
_routing = !(_xml.@routing == “false”);
_history = !(_xml.@history == “false”);
_indexFirst = (_xml.@indexFirst == “true”);
_assetPath = _xml.@assetPath || ZincContext.instance.getApplicationPath();
// preloaderDepth
var depth:String = String(_xml.@preloaderDepth).toLowerCase();
if (depth == Gaia.MIDDLE || depth == Gaia.BOTTOM) _preloaderDepth = depth;
else _preloaderDepth = Gaia.TOP;
// preloaderDomain
var domain:String = String(_xml.@preloaderDomain).toLowerCase();
if (domain == Gaia.DOMAIN_CURRENT || domain == Gaia.DOMAIN_NEW) _preloaderDomain = domain;
else _preloaderDomain = Gaia.DOMAIN_NULL;
// defaultFlow
var flow:String = String(_xml.@flow).toLowerCase();
if (flow == Gaia.PRELOAD || flow == Gaia.REVERSE || flow == Gaia.CROSS) _defaultFlow = flow;
else _defaultFlow = Gaia.NORMAL;
if (_routing) _routes = {};
}
private function parsePage(node:XML, parent:PageAsset = null):PageAsset
{
validateNode(node, true);
var isIndex:Boolean = (node.@id == _indexID);
var page:PageAsset = new PageAsset();
page.node = node;
page.id = node.@id;
page.src = ZincContext.instance.getApplicationPath()+node.@src;
page.title = node.@title;
page.bytes = node.@bytes;
page.assetPath = ZincContext.instance.getApplicationPath()+node.@assetPath || _assetPath;

page.preloadAsset = true;
page.menu = (node.@menu == “true”);
if (page.menu && page.title.toLowerCase() == “about”) GaiaDebug.warn(‘* Warning * “About” is not permitted in Flash context menus’);
if (page.menu && page.title.length > 0) _menuArray.push(page);
page.landing = (node.@landing == “true”);
// domain
var domain:String = String(node.@domain).toLowerCase();
if (domain == Gaia.DOMAIN_NEW || domain == Gaia.DOMAIN_CURRENT) page.domain = domain;
// depth
var depth:String = String(node.@depth).toLowerCase();
if (!isIndex)
{
page.setParent(parent);
page.external = (node.@src.split(“.”).pop() != “swf” || node.@src.indexOf(“javascript”) > -1);
if (page.external) page.window = node.@window || “_self”;
if (depth == Gaia.TOP || depth == Gaia.BOTTOM || depth == Gaia.NESTED) page.depth = depth;
else page.depth = Gaia.MIDDLE;
}
else
{
if (depth == Gaia.TOP || depth == Gaia.MIDDLE) page.depth = depth;
else page.depth = Gaia.BOTTOM;
}
// flow
var flow:String = String(node.@flow).toLowerCase();
if (flow == Gaia.NORMAL || flow == Gaia.PRELOAD || flow == Gaia.REVERSE || flow == Gaia.CROSS) page.flow = flow;
// assets
if (node.asset.length() > 0 || node.@seo != undefined) page.assets = parseAssets(node.asset, page, node.@seo, int(node.@seoBytes));
// child pages
if (node.page.length() > 0)
{
page.defaultChild = node.@defaultChild;
page.children = parseChildren(page, node.page);
if (!page.children.hasOwnProperty(page.defaultChild)) page.defaultChild = node.page[0].@id;
}
// terminal page
else
{
if (page.src.substr(page.src.length – 4) == “.swf”) page.landing = true;
if (isIndex) GaiaSWFAddress.isSinglePage = true;
}
// only add terminal and landing pages to routes
if (_routing && page.landing)
{
var route:String = node.@route || page.title;
if (isIndex) route = route || page.id;
page.route = getValidRoute(route, page.id).toLowerCase();
_routes[page.route] = page.branch;
}
return page;
}
These changes allow you to test your application within the flash authoring environment as the application path will be empty and it will load the files with local references. If you run the application inside a Zinc wrapper the files will be references with an absolute path.

External Interface calls

In order for flash applications to communicate with the browser they use External Interface. This is used extensively within the Gaia framework for logging and also search engine optimization with swfAddress. However MDM Zinc does not handle these calls particularly gracefully and as it is not possible to turn this functionality off within the framework we again need to make a couple of modifications.

Blocking external calls

Inside SWFAdress.as there is a test for ExternalInterface.available however inside Zinc this will incorrectly report true. The only fix for this is as follows:

private static var _availability:Boolean = false; // used to be ExternalInterface.available;
Conclusion

The solutions I have proposed here will resolve the issues the prevent you from using Gaia within a Zinc application. However I believe that these issues could be resolved in a number of ways within the respective products.

MDM Zinc need resolve the issue with ExternalInterface and the its incorrect implementation as this is essentially a bug in the platform.

The issues with the Gaia framework can not be considered bugs as the framework does exactly what it was intended to do. However I would suggest that the framework would be greatly improved if additional configuration were made available to users. Being able to turn off the SEO modules such as SWFAddress and external calls would be very helpful. Not only for use within MDM Zinc but also in situations where the flash application is not the entire web page. If you use Gaia to be build a smaller component within a page the SWFAddress calls can also cause problems.

The loading of assets would also be greatly improved if it were possible to update their paths at run time. Obviously this is not a common requirement but it would make the framework much more flexible and far more useful.

[AS3] Signal 野: Signal VS DeluxeSignal

http://insideria.com/2010/10/an-introduction-to-as3-signals.html
睇左先
up 一大春英文,搞咩,超簡單
signal 係可以 pass parameter,但 pass 個個 object 就係個個 object 囉

DeluxeSignal 就勁啦,係 pass event
event signal 都識 pass 啦,咁你就錯
呢個 event 係 as3 d fd,你 pass 左,過到去,有翻曬你以前 event 玩既野
例如 event.currentTaret, event.type, event.target 咁
咁咪開心又興奮囉~

[AS3] 兩個 SWF event 傳黎傳去既方法

你仲想利用個 event 傳data ?

[actionscript3]
mother.addEventListener(CustomEvent.MODULE_CLOSE, onModuleClose)

function onModuleClose(e:*):void {

var data = e.data;

}

var data = {a:1, b:"hello"};

swf.dispatchEvent(new CustomEvent(CustomEvent.MODULE_CLOSE, data));

[/actionscript3]

PS

如果要玩 bubbling: 記得 extend 個陣 要 override 埋 clone 呢個 function!

[AS3] Hit on hitTestObject

hitTestObject is always use

but do u know:

mc.hitTestObject(target)

if target.visible = false and target.alpha =0

其實都 hit 中 return true

小心d 啦~ 最好加多個 condition

mc.hitTestObject(target) && target.visible

[AS3] Flex no MXML using Application

[as3]
package
{
import mx.core.Application;
import mx.events.FlexEvent;
import mx.styles.StyleManager;
import mx.styles.CSSStyleDeclaration;
import mx.controls.Button;
import mx.skins.halo.HaloBorder;
import flash.display.Bitmap;

public class Main extends Application
{
[Embed(source="../library/up.png")]
public var UpState : Class;
[Embed(source="../library/over.png")]
public var OverState : Class;
[Embed(source="../library/down.png")]
public var DownState : Class;

public function Main()
{
super();

this.layout = "absolute";
this.addEventListener(FlexEvent.CREATION_COMPLETE, handleComplete);

setupStyles();
}

private function setupStyles() : void
{
var style:CSSStyleDeclaration = new CSSStyleDeclaration();
style.setStyle( "borderSkin", mx.skins.halo.HaloBorder );
StyleManager.setStyleDeclaration( "Application", style, false );

style = new CSSStyleDeclaration();
style.setStyle( "textAlign", "left" );
style.setStyle( "fontAntiAliasType", "advanced" );
style.setStyle( "fontGridFitType", "pixel" );
style.setStyle( "paddingLeft", 10 );
style.setStyle( "paddingRight", 10 );
style.setStyle( "paddingTop", 5 );
style.setStyle( "paddingBottom", 5 );
style.setStyle( "horizontalCenter", 0 );
style.setStyle( "verticalCenter", 0 );
style.setStyle( "upSkin", UpState );
style.setStyle( "overSkin", OverState );
style.setStyle( "downSkin", DownState );

StyleManager.setStyleDeclaration( "Button", style, false );
}

private function handleComplete( event : FlexEvent ) : void
{
var button : Button = new Button();
button.label = "labelBtn";
addChild( button );
}
}
}
[/as3]

[AS3] Saving file by FileReference

FileReference.save()

http://blog.everythingflex.com/2008/10/01/filereferencesave-in-flash-player-10/

API

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#save%28%29

(題外話,講 load 的)

叫你注意 loader.dataFormat = URLLoaderDataFormat.BINARY;

http://www.actionscript.org/forums/showthread.php3?t=187580

如果 advance d coding的話,用 fscommand出一個小exe將 bytearray -> jpg都得。

[AS3] AS3 Framework / API Collection

Adobe APIs
corelib, mappr, flickr, youtube and more.
http://labs.adobe.com/wiki/index.php…apis:libraries
APE (Actionscript Physics Engine)
http://www.cove.org/ape/
as3awss3lib
ActionScript 3.0 library for interacting with Amazon S3
http://code.google.com/p/as3awss3lib/
as3soundeditorlib
Actionscript 3.0 library for sound editing
http://code.google.com/p/as3soundeditorlib/
as3ds
AS3 Data Structures For Game Developers
http://code.google.com/p/as3ds/
ASCOLLADA
http://code.google.com/p/ascollada/
As3Crypto
ActionScript 3 Cryptography Library
http://crypto.hurlant.com/
asinmotion
Animation Library for AS3
http://code.google.com/p/asinmotion/
Away3d
http://code.google.com/p/away3d/
ebay API
http://code.google.com/p/as3ebaylib/
facebook-as3
AS3 API to access Facebook’s Platform API
http://code.google.com/p/facebook-as3/
flest
Flest Framework for Adobe Flex and ActionScript3 Applications
http://code.google.com/p/flest/
FZip
Actionscript 3 class library to load standard ZIP archives and extract/decompress contained files.
http://codeazur.com.br/lab/fzip/
lastfm-as3
Actionscript 3.0 library to access the Last.fm web services
http://code.google.com/p/lastfm-as3/
MapQuest
http://company.mapquest.com/mqbs/4a.html
mecheye-as3-libraries
A set of ActionScript 3 Libraries, primarily for Flash game development.
http://code.google.com/p/mecheye-as3-libraries/
Papervision3D
http://code.google.com/p/papervision3d/
Salesforce Flex Toolkit
http://wiki.apexdevnet.com/index.php/Flex_Toolkit
Tweener
Full featured animation library
http://code.google.com/p/tweener/
Twitter AS3 API
http://twitter.com/blog/2006/10/twitter-api-for-flash-developers.html
uicomponents-as3
Lightweight AS3 UI component library
http://code.google.com/p/uicomponents-as3/
XIFF
XMPP client library
http://svn.igniterealtime.org/svn/repos/xiff/branches/xiff_as3_flexlib_beta1/
Yahoo AS3 APIs
http://developer.yahoo.com/flash/as3_api_libraries.html

[Flex] Beginner for flex

http://zh-tw.w3support.net/index.php?db=so&id=141288

可以使用Flex框架/組件少許的MXML?

http://sujitreddyg.wordpress.com/2008/02/05/splitting-flex-application-into-modules/

Splitting Flex application into modules

http://mromecki.fr/en/post-using-flex-3-component-without-mxml-only-as3#/post-using-flex-3-component-without-mxml-only-as3

http://cookbooks.adobe.com/post_Creating_Application_without_MXML-11123.html

Using Flex 3 Component without MXML – only AS3 (FLEX 3333333333333333333333333!)

about mask

http://rhinotw.blogspot.com/2009/01/as3mask.html

AS3的mask並不會改變原物件的長寬;
舉例來說,一個長寬500×500的A_mc,被一個200×200的B_mc所mask,
AS2的時候,trace會發現A_mc的長寬變成200×200了,
但AS3則仍然trace出500×500。
這問題在需要對A_mc縮放的時候,會有大麻煩,
例如我想放大到寬度是1000px,則AS2會放大5倍,但AS3只會放大2倍;
試過DisplayObject的getRect()跟getBounds(),都是trace出500×500,
Vanilla找到一個怪招:
bitmapData.draw(A_mc);
trace(bitmapData.getColorBoundsRect(0xff000000,0xff000000,true));
就會回報正確的長寬了!
感謝Vanilla!

error 2007, load swf with Flash UI component error

TypeError: Error #2007: 參數 child 不能是 Null。
at flash.display::DisplayObjectContainer/addChildAt()
at fl.controls::BaseButton/drawBackground()
at fl.controls::BaseButton/draw()
at fl.core::UIComponent/drawNow()
at fl.controls::ScrollBar/draw()
at fl.controls::UIScrollBar/draw()
at fl.core::UIComponent/drawNow()
at fl.controls::TextArea/updateScrollBars()
at fl.controls::TextArea/drawLayout()
at fl.controls::TextArea/draw()
at fl.core::UIComponent/callLaterDispatcher()

TypeError: Error #2007: 參數 child 不能是 Null。

當你用了 load swf,而咁o岩裡面個 swf 有用到 UI component d 野
(e.g. scrollbar, checkbox 等)
你用 main 個個 swf load 佢,本身都應該相安無事
但你搞下個 fl library,例如玩下 focusManager,又或者 (我估) add 其他 UI component
咁佢就會鬧你 load swf 個個搵唔到適當既 UI component
其實無咩野,出下 error,想解決就係 main library 都加埋 個個 UIcomponent la~

duplicate MC……自己 load 自己

http://asgrocery.blogspot.com/2010/02/actionscript-3-duplicate-stage-instace.html#more

很有趣的構思

[actionscript3]
package {
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;

/**
* …
* @author Focus1921
*
* 複製無綁定類別movie clip場景實體(stage instance)實作demo(fla文件類別)
*/
public class DocTest extends MovieClip {
//stage instance
public var test_box_mc:MovieClip; //場景上僅有的movie clip, 實體名稱test_box_mc

private var ba:ByteArray; //儲存自己這個swf的byte array
private var ldr:Loader; //建一個loader來load ba
private var tmpX:Number;
private var tmpY:Number;

/**
* 建構式
*/
public function DocTest() {
if (stage) {
init();
}else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}

private function init(e:Event = null):void {
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;

//確保主場景load只load自己一次,避免溢位
if (parent is Stage) {
trace("parent is Stage");
//建構url loader(binary)去load自己的byte array
var _urlLoader:URLLoader = new URLLoader();
_urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
//trace(root.loaderInfo.url);
_urlLoader.load(new URLRequest(root.loaderInfo.url));
_urlLoader.addEventListener(Event.COMPLETE, onURLLdrComplete);
}

//建構loader, 註冊complete完成偵聽
ldr = new Loader();
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onLdrComplete);

//stage註冊click偵聽
stage.addEventListener(MouseEvent.CLICK, onStageClick);
}

//—Event Handler—————————————————————————–

private function onURLLdrComplete(e:Event):void {
e.currentTarget.removeEventListener(Event.COMPLETE, onURLLdrComplete);
//把load到的byte array存起來
ba = e.currentTarget.data;
}

private function onLdrComplete(e:Event):void {
//用實體名稱去抓到要複製的movie clip,每次load完都會傳不同的引用
var _mc:MovieClip = <div style="display: inline; height: auto; position: absolute; visibility: hidden; width: auto; ">MovieClip</div>MovieClip(ldr.content).getChildByName("test_box_mc") as MovieClip;
//屬性設定不同的值,證明的確不是同一個引用
_mc.x = tmpX;
_mc.y = tmpY;
_mc.alpha = Math.random();
//加入顯示清單
addChild(_mc);
}

private function onStageClick(e:MouseEvent):void {
//把點擊座標記起來,當作複製後的mc的座標
tmpX = e.stageX;
tmpY = e.stageY;
//loader去load(loadBytes)存起來的byte array(ba)
ldr.loadBytes(ba);
}

}

}
[/actionscript3]

Hack Flash Projector to change some value (e.g. title name)

Player without minimize, maximize and close buttons when not full screen:

Using third party projector tools such as mProjector, Zinc, SWF Studio or Screenweaver. Flash alone cannot do that.

Another way to hide the minimize, maximize and close buttons (and also, if you want, to modify/remove others menus, dialog windows etc.), but only applicable at a projector file, is to use a resource editor program, also called ‘hacking’ program. With such programs (for example: ‘XN Resource Editor’, ‘Resource Hacker’), you can usually ‘hack’ Win32 PE files (modules); that is why you will be able to edit only the projector file.

http://www.wilsonc.demon.co.uk/d10resourceeditor.htm

http://www.angusj.com/resourcehacker/

Using swc rather than Embed tag

http://www.arpitonline.com/blog/2009/03/21/flex-builder-tip-use-swcs-for-image-assets-not-embed-metatags-for-pure-actionscript-projects/

PS

What is Flex Assets?

When using [Embed] to store some bitmap, it will extends BitmapAssets, etc……….

so somethime may not want to use Embed tag, then u can import the Asset class inside and extends by yrself!

http://www.ultrashock.com/forums/flex/embed-flex-assets-without-using-flex-123405.html

as3 event bubbling notice

The event can only bubble up through the display list if the object that dispatched the event is a DisplayObject (or an ancestor of DisplayObject, such as a Sprite or MovieClip) so that it can be in the display list AND it is added to the display list at the time of the event dispatch.

唔係你係類面 new 個 instance ,佢就識玩 bubble

而係 addChild 落個 displaylist 到先識玩 bubbling

new object 個個你就要一層層咁自己 dispatch~

Flash compile exe -> Flash player 可選!

最新既 flash player 10 多左個 digital cert 功能,可惜的是 IE 去開既時候會鬧你無正確既 digital cert,咁點解決呢

1. 用 zip -> sfx 既方法,IE 就唔當 flash player 開

2. compile 既時候,換個 flash player,用 無cert 既 9 或者用 10 既 debug version (但希望你個 program 無 bug,唔係出 error)

how?

program files -> flash -> player

換左類面個 player 佢

export 出黎既 exe 就係包呢款 player,

(projector 原理: 包個 flash player,叫佢開個 swf 之嘛)

無 cert 既 projector 就過關了!

模擬 multiple inheritance

http://www.darronschall.com/weblog/2006/10/multiple-inheritance-in-actionscript-3.cfm

用 implement interface + #include 去摸擬

實際上佢 implement 個 interface,但只有 function 名,對嘛

然後每個要 (扮) extends 個個 class implement 完左 #include 一定要個d functions,

咁咪一定要用個d function 囉?

咁就 == 一定有個堆 function 兼 function 名 及可以用 is 等等

咁就可以無限 (扮) extends!

(not a gd practice, btw)

Playing Audio with Flash

http://milkmidi.blogspot.com/2010/07/as3-scratch.html 我由呢個 demo 開始睇

http://www.anttikupila.com/flash/soundfx-out-of-the-box-audio-filters-with-actionscript-3/ 有呢個好正既 sound filter, 識做 echo, phase, feedback, cutoff, resonance 個d effect

用 pixelBlender Mix 歌

http://www.kaourantin.net/2008/10/audio-mixing-with-pixel-bender.html#4759002868008324481

http://blogs.adobe.com/kevin.goldsmith/2009/08/pixel_bender_au.html

載入 mp3

http://www.flexiblefactory.co.uk/flexible/

embed xml

[sourcecode language=”actionscript3″]
[Embed(source="info.xml", mimeType="application/octet-stream")]
protected var EmbeddedXML:Class;

var ba : ByteArray = (new EmbeddedXML()) as ByteArray;
var s : String = ba.readUTFBytes( ba.length );
xml = new XML( s );
[/sourcecode]

papervision, 關於上色

cube20100325

陰影很怪。

這個本應使用了 FlatShadeMaterial 去直接打光上去上色。

在 cube 上再加上一塊 bitmap mapping / movieClip mapping / colorMaterial

[sourcecode language=”actionscript3″]
material = new CompositeMaterial();
var mat = new ColorMaterial(ColorLibrary.YELLOW_COLOR, THREE_D_OBJ_ALHPA);
material.addMaterial(mat);
var mat = new FlatShadeMaterial(_light, Conf.LIGHT_COLOR, Conf.AMBIENT_COLOR, 20, THREE_D_OBJ_ALHPA);
material.addMaterial(mat);[/sourcecode]

將兩個 material 合埋使用,

因為立體有了自身的顏身再上 flatShade 咁就靚曬啦!

明天就是 deadline! (一)

24032010

還有很多立體要畫。

用了 papervision 。但經過不斷的 research, 聽聞 away3d 更好。

(聽聞)只少在 import 3D卡通時較易上手。

之後很想學 blender 或者 3D studio max,做一d 得意既 3D 動畫或者網站!

P.S. 明天就是 deadline,後面加了 (一),好明顯我知道這類 Post 應該以後陸續有黎!

external assets swf (getDefinition)

[sourcecode language=”actionscript3″]
package {
/*
the main swf that loads everything, starting with assets swf…
*/
import flash.display.*;
import flash.net.URLRequest;
import flash.utils.*;
import flash.events.Event;</code>

public class Requiem extends MovieClip {
private var AssetLoader:Loader;
private var Request:URLRequest;
private var AssetsURL:String = "RequiemAssets.swf"

public function Requiem (){
var Request = new URLRequest(AssetsURL)
var AssetLoader = new Loader()
AssetLoader.load(Request)
AssetLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete)

}

private function onComplete(e:Event):void{
trace ("Load Complete")
var ldrInfo = e.currentTarget as LoaderInfo;
ldrInfo.removeListener (Event.COMPLETE, onComplete)

var assets:MovieClip = e.currentTarget as MovieClip;
var Home:Class = assets.loaderInfo.applicationDomain.getDefinition("home")
var home:MovieClip = new Home()
addChild (home)
}
}
}
[/sourcecode]

用黎 load 一個 swf,拎佢 library 裡面d 野出黎

Developer Blog, Site 推薦 (一)

一定要 keep 住睇! 日本 developer 既蒲點,好多 idea 可以係到搵到
http://wonderfl.net/
http://beautifl.net/

比較淺
http://tutorials.flashmymind.com/

呢個係賣code 既,睇下都學到好多野
http://activeden.net/

一個鍾意玩 pv3d 既人既 blog
http://sebleedelisle.com/

show news 多
http://www.flashmagazine.com/

比較淺,可睇可唔睇
http://www.riacodes.com/

一定要睇,show 新 technique 多過教你寫 code
http://www.everydayflash.com/

papervision technical 野多
http://blog.zupko.info/

effect technical 野多,較難,推薦
http://www.dehash.com/

閒話家常,technical 唔多
http://www.blog.lessrain.com/

可以一看
http://flashenabledblog.com/

日本野! Good!
http://www.be-interactive.org/

好勁既 papervision3d blog
http://professionalpapervision.wordpress.com/

Flex Community, show news 多
http://blog.flexcommunity.net/

一個鍾意玩 Augmented Reality 既人既 blog
http://www.harrynorthover.com/blog/

Flash Framework

GAIA Flash Framework
http://www.gaiaflashframework.com/
寫網站時試用,包了 swfAddress 同自動分頁

Papervision 3D
http://blog.papervision3d.org/
不用介紹吧,正在研究

PureMVC
http://puremvc.org/
MVC Model,還在研究中

XIFF
http://www.igniterealtime.org/
做 real-time community 用,例如 chatting,還在研究中

TweenLite
http://www.greensock.com/tweenlite/
做 motion tween 用

JiglibFlash
http://www.jiglibflash.com/blog/
Physics Engine For 3D,還在研究中

CASA Lib
http://casalib.org/
提供一大堆有用既 Class

BetweenAS3 (TweenLite d friend)
http://www.be-interactive.org/works/20090911/slide_betweenas3.html

Popforge
http://code.google.com/p/popforge/
Sound Library

Five3D

http://five3d.mathieu-badimon.com/
主要用翻 flash 10 個 3D engine 去做既 library