Tuesday, October 21, 2008

.net try catch finally

Yesterday, dechu said he once read my blog. I then realize I have a blog... Almost forgot this place. Today I am going to talk about try, catch, finally.
Few years ago, I used try catch to avoid unexcepted error, and always put everything in a big try block. Catch the error, maybe print it out and that's it. This is a really bad practice.
I started to look at other people's code, and learned to do some clean up in finally block, however, this is still not enough. Now I started to use multiple level try & catch, in the lower level,
trying to rollover previous actions like a sql transaction in catch block, and then throw new exception to upper level code. This improve the error handling abilities and allow code structure to be easily handled. The disadvantage is the performance issue of throwing exceptions.
But considering we are not using exceptions mechanism to achieve certain result, the time consuming exception won't eat up resources in the normal run.

First look at this code below:

/ try-catch-finally
using System;public class TRYCATCHFINALLY
public static void Main ()
Console.WriteLine("Executing the try statement.");
catch (System.Exception sex)
throw new SomethingFailedException();
Console.WriteLine("Now something done, try other things now.");
catch (System.Exception oex)
throw new OtherthingFailedException();
Console.WriteLine("Executing the try all done.");
catch (SomethingFailedException sfe)
Console.WriteLine("{0} Caught exception #1.", e);
catch (OtherthingFailedException ofe)
Console.WriteLine("{0} Caught exception #1.", e);
Console.WriteLine("Executing finally block. Clean up
private void DoSomething()
//Hello 6sb
catch (System.Exception e)
throw new Exception WhateverException();
// clean up

private void DoOtherthing()
//lv 6sb
catch (System.Exception e)
throw New Exception WhateverException();
// clean up

Wednesday, October 8, 2008

.Net 的优缺点

.Net === 一堆库+虚拟机
.Net + C# === Java + JVM
1. MS主推
2. 支持多语言
3. .NET的核心虚拟机CLR将c#这种编译出来的CIL中间代码再编译成机器代码,而非jvm的解析,所以运行速度快
4. 安全,内存,异常处理都在虚拟机内得到一定的保证。
5. 跨平台ms没做,支持了一个叫Mono的项目,可以在Linux, Solaris, Mac OS X, BSD, HP-UX下面跑,不过现在也就做到.Net 2.0
1. 写完程序配置起来简单,基本上机器都会在自动跟新的时候装上这个.net runtime envrionment
2. 学起来容易,不管是web application还是desktop software,学了很大一部分能通用
3. VS用起来蛮舒服。
4. 跟sqlserver也结合紧密,甚至可以说跟ms的所有东西都结合紧密。
5. 开速开发GUI的首选吧。
6. 开发web service嗷嗷简单,客户端如果也用.net,API这块省力。
1. 代码保护不容易,跟java似的。。
2. 更新太快,丫的3.0还好,3.5就是一个更新的平台,引进一堆没听过的东西。。现在已经出4.0了。
3. 跟人说会这么好像很没面子,不如gs的python来的野性。。。哈哈
4. 有些功能没有,要调用windows library里面的函数了,MFC能干的丫的managed code不一定能干,只能走unsafe code的路子,但是前面的优势就没那么明显了。


Monday, September 29, 2008

SQL Server Profiler fonts error

运行SQL Server Profiler,生成,连接数据库,正常,当点下run开始跟踪的时候,报错:"only TrueType fonts are supported. There id not a TrueType font"。倒,微软还真进步,看来要淘汰windows中的非TrueType字体了。


点击 Tools菜单->Options...

然后在选项对话框开头的Display Options部分,"Choose Font..."换一种TrueType的字体即可,我比较喜欢Vendana 。

Monday, September 8, 2008

windows form c# -- User Interface tips to show system status

When a time consuming task is performed, we can either perform it using backgroundworker, or using a little tips like this:
Cursor.Current = Cursors.WaitCursor;
// Perform your task here
Cursor.Current = Cursors.Default;
From the UI perspective, User understand that the system is busy and will be more than happy to wait rather than disappointed.

Saturday, September 6, 2008

General Linux Common Command

Generic Linux

df -h shows disk usage in human readable form
man <commandname> shows more info about a command
uname -a kernel release version
/usr/sbin/smbd -V samba version
/usr/sbin/httpd -v apache version
mysql -v mysql version
php -v php version
mv moves or renames a file
cp copies or backsup a file
rm removes or deletes a file
ps -ax|grep <process> outputs processes running <process>
ps -AH report process status
top shows processes
top -i shows only active processes
iptraf shows network info
mc -d show midnight commander to navigate through system easily
cat /proc/mdstat shows software raid
host -t mx aol.com shows the mx records for aol.com
net groupmap list shows samba mappings to nt groups
telinit 1 changes to single user mode
ifconfig shows detailed info on ethernet ports
grep -r "casesensitivesearch" * finds all documents containing the criteria in a dir
tail -f /var/log/<LOGFILE> realtime viewing of your log file
hdparm -t /dev/mdx (where x is 0,1,2,etc) shows software raid performance
mdadm --detail /dev/mdx (where x is 0,1,2,etc) gives raid info
tar -czvf foo.tar.gz foo creates a tar/zip file of a directory
tar -xvzf foo.tar.gz untar/unzip a tar/zip file
scp -P <ssh_portnumber> foo.tar.gz <other_server_ipaddress>:/opt transfers file to another server
rsync --progress -te "ssh -p <ssh_portnumber>" foo <other_server_ipaddress>:/opt transfers file to another server
sed -i s/foo/fee/g <FILENAMEORPATHTODIR> replaces foo with fee

Tuesday, September 2, 2008

vc++ compiler support Ecma c++ standards

Visual C++ complies with these standards:

  • ISO C 95

  • ISO C++ 98

  • Ecma C++/CLI 05


The GNU C library is compatible with the C standard adopted by the American National Standards Institute (ANSI): American National Standard X3.159-1989---"ANSI C".
The header files and library facilities that make up the GNU library are a superset of those specified by the ANSI C standard.

Monday, September 1, 2008

segmentation fault in linux/unix

A wired error happened today when I am trying to run a gcc complied application.
"Segmentation fault" happened in the least expected place (at least according to cout, it paused), so I tried very hard to
modify this bit of code in many ways. I couldn't solve the problem until I tried gdb.
After reading wikipedia for the simplest way of using gdb, and few other articles on the web, I start to debug the code.
I find that the application had a bug in one line, which is way below the code that I was messing around. 
How stupid I am... I should know that the application is still running and cout just haven't finish printing.....
I should have turn to debugging straight away because this is c++, not c#.

Conclusion: Never trust manual debug using cout.

Saturday, August 30, 2008

Thesis --- Infrastructure Development for a Mind Attention Interface

Chapter 1
For a long time, people have dreamt of using their mind as direct input to control
machines. Researchers on Brain-Computer Interfaces (BCIs) have been working
to build practical systems which can be used by disabled people and there have
been significant results which show that computers can be slowly but effectively
controlled by a human mind [1, 63]. "Mind" here refers to the combination
of thought, emotion, perception, imagination, and other brain states. In the
Mind Attention Interface (MAI), we intend to measure mind states by using
Electroencephalograms (EEG).
For some time, psychology and neuroscience researchers have had a research
focus on attention. Attention is the cognitive process of selectively concentrating
on things that the mind is interested in [35]. It is one of the cognitive processes
which is considered as having a most concrete association with the human mind,
and it is closely linked with perception [40]. Audio and visual cues for attention
are another source that we can use to help improve communication with
computers. In the MAI, measurements of attention such as gaze, head or hand
movements are obtained from dedicated recording systems.
The idea of the Mind Attention Interface is to create a platform for interacting
with a virtual reality theatre using EEG and measures of attention. This thesis
describes the construction of such extensive hardware and software platform,
which is called the MAI System. The rest of this chapter introduces the most
important concepts behind the Mind Attention Interface.
1.1 Brain-Computer Interfaces
1.1.1 Background
A Brain-Computer Interface (BCI) is an interface between a person's brain and
a computer. It is a computer interface that only uses signals from the brain,
and which does not require any user motor activity [2] such as eye or other body
potentials. Research on BCIs started in the 1970s and have developed rapidly
in the 1990s [25]. BCIs can be classified in two major categories: invasive and
non-invasive. In invasive BCIs, electrodes are implanted into the brain during
neurosurgery, and these systems diagnose and repair damage brain functions.
(Invasive BCIs will not be discussed further in this thesis) Non-invasive BCIs, on
the other hand, detect brain signals from the surface of the brain, such as the
scalp of a user, using an electrode cap. Electroencephalography (EEG) is the
most commonly used non-invasive BCI due to its fine temporal resolution, ease
of use and cost [63]. By converting the acquired analogue signals to digital, and
sending them to a computer for processing, a BCI can be used to control certain
electronic devices.
1.1.2 Electroencephalographic BCIs
The first electroencephalogram (EEG) recording was obtained by Hans Berger
in 1929 [19]. An EEG is a graph of measurements of the electrical activity of
the brain as recorded from electrodes placed on the scalp or on the cortex itself.
Because electrical activity is closely involved in the way the brain works,
EEG provides "direct measurements" of brain functions in comparison with technologies
which rely on blood flow or metabolism which maybe decoupled from
brain activity. Traditionally, this non-invasive technology has several limitations:
Firstly, scalp electrodes are not sensitive enough to pick out action potentials
of individual neurons. Instead, the EEG picks up signals from the synchronised
groups of neurons. Secondly, identifying the source locations of measured EEG
potential is an invoice problem which means that these desired locations are very
non-specific. In contrast with other brain-imaging techniques such as functional
magnetic resonance imaging (fMRI) , the spatial resolution in the region could
be less than 3 millimetres. Thirdly, due to its susceptibility to noise, this method
can be largely affected by the surrounding environments, such as the 50Hz AC
noise (50Hz is the mains power frequency in Australia). On the other hand, EEG
has several positive aspects as a tool of exploring brain activity. As mentioned
above, it is an affordable system for most research groups. The setup and scalp
preparation for modern EEG systems is relatively straightforward to use. In particular,
its temporal resolution is very high. EEG has a time resolution down to
sub-milliseconds compared with other methods for researching brain activities,
which have time resolution in the order of seconds or even minutes.
The types of waves measured in the EEG signal are studied together with
mental states. Major types of continuous, sinusoidal EEG waves are delta, theta,
alpha, beta, and gamma. The only difference between these signal types is the
frequency range † . They are listed in Table 1.1 with associated mental states.
Electroencephalographic BCI applications can provide disabled users with a
new channel for sending messages to the outside world [66]. In [23], slow cortical
potential (SCP) was used to control cursor movements on a computer screen.
This rhythm shows up as large drifts in the cortical voltage which last from a few
hundred milliseconds up to several minutes. In [66], similar cursor movement BCI
is implemented by controlling the amplitudes of the sensorimotor activity signals
such as the mu rhythm in the alpha frequency band (8 -12Hz). Other commonly
Functional fMRI is the use of magnetic resonance imaging to measure the haemodynamic
response related to neural activity in the brain. MRI is a non-invasive method used to render
images of the inside of an object.
†There is no precise agreement on the frequency ranges for each type.
wave frequency range associated mental states
Delta 0-4 Hz certain encephalopathy, deep
Theta 4-8 Hz trances, hypnosis, lucid dreaming,
light sleep
Alpha 8-12 Hz relaxation, calmness, abstract
Beta 12+ Hz anxious thinking, active concentration
Gamma 26 - 100 Hz higher mental activity including
perception, problem solving, fear,
and consciousness
Table 1.1: EEG waves associated with mental states [13]
used signals in BCIs are Event-Related Potentials (ERPs), Visual Evoked Potentials
(VEPs), and Steady State Visual Evoked Responses (SSVERs) [64, 65].
Among these signals, an ERP response to unpredictable stimuli called the
P300 (or simply P3) is one of the most robust [11]. The P300 ERP appears as
a positive deflection of the EEG voltage at approximately 300ms. Based on this
phenomenon, P300 character recognition is designed in [14] to choose characters
for disabled users: A 6 × 6 grid containing alphabet letters and numbers is
displayed on screen and users are asked to count the number of times the row or
column flash which contains the character they wanted to select. Every twelve
flashes are called a set, which all rows and columns have flashed once. P300
amplitude is measured and the average response to each row and column is used
to determine the selected character.
Although there are many existing BCI systems in use at present, the extensive
training required before users obtain such technology and the slowness in com1.2.
munication is the substantial barrier of using BCI systems. One implementation
by Wolpaw in [65] using mu rhythm achieved 10.88 binary decisions per minute
with 2 month training. In another word, a typical cursor move from the centre of
a video screen to a target located at the top or bottom edge will take 3 seconds.
Another example would be P300 character recognition system implemented by
Donchin in [11], which achieved 9.23 binary decisions per minute online classification
rate. The classification rate is the way BCI uses to compare the speed
of the system. In P300 for example, more than five binary decisions (correct
ones) are needed to choose a single symbol as there are totally 36 symbols. To
summarise, users are normally trained through biofeedback for several weeks to
months before they make use of the systems, and online classification rate are
less than 15 binary decisions per minute [47].
1.2 Attention and the Mind as a Computer In-
1.2.1 Attentive Interface
The so-called "Attentive Interface" is a relatively new category of user interface,
which dynamically prioritises the information it presents to its users [58]. In
[46], Selker gives a definition of Attentive Interface as: "Context-aware human-
computer interfaces that rely on a person's attention as the primary input". Here
attention is epitomized by eye gaze which is one of the key features that have
been widely used in Attentive Interfaces. Figure 1.1 shows a typical eye-gaze
tracking system. In recent years, interactive applications using eye tracking have
improved to the stage that they now allow people to type, draw, and control
an environment[26]. In these interfaces, the synchronised rotation of the eyes is
often used as a pointing device to point to and select a graphical object located
at the intersection of the eye-gaze vector and the screen (see [52] for example).
Blinking, eye gestures and movements, as well as eye dwell-time can all be used
in selection and control [56]. At present, training is essential to use attentive
interfaces because none of the above methods is natural. Some experts believe
that ongoing research may bring us generation interfaces with more natural eye
movements for selection and control [38].
Figure 1.1: Gaze system by SeeingMachinesTM
1.2.2 Mind and Attention for Interaction with a Virtual
In virtual environments, real-world human movements can be mapped to actions
in a virtual world. The effect of these actions is often to do with manipulation
of the entire objects in 3D spaces. Although most emphasis has been placed
on physical controllers together with tracking systems, eye gaze has also been
considered as an interface to a virtual environment [18]. Tanriverdi and Jacob,
in [52], claim that eye movement-based interaction offers the potential of easy,
natural, and fast ways of interacting in virtual environments. A comparison of
the performance that eye movement and pointing based interactions in virtual
environments was undertaken, and the results show that eye gaze based technique
has speed advantage especially in distant virtual environment.
Bayliss in [3, 5] demonstrate examples of EEG based BCI systems in control
of virtual environments. Her past research in [4] also gives us a clue of the effects
that eye tracker and virtual environment impact on EEG recording, and the
results indicate that neither eye tracker nor virtual environment will introduce
significant noise than computer monitors to the EEG signal quality. Therefore,
the Mind Attention Interface idea seems realistically, which all devices would
work together without affecting others.
My infrastructure goal was to build a fundamental framework for Wedge virtual
reality theatre that supported mind and attention data from different sources,
in different formats, and which would go beyond a simple BCI interface. Firstly,
the real-time analysis of brain states from EEG was planned to be quite sophisticated
and to go beyond a simple classification of signals into frequency bands.
Secondly, it was planned to provide natural feedback of a user's brain states to
the evolution of an immersive virtual experience which included 3D graphics and
surround sound. Thirdly, the measurements of eye-gaze-based attention from a
user in virtual environment were intended to provide feedback on the brain state
of a user. Eye gaze can also play a role in filtering EEG signals for interference
from oculomotor events. Head position, orientation, and other control devices can
also be used to interact with the virtual world. Figure 1.2 shows the feedback
loop that we intend to create in the MAI.
1.3 This Thesis
This thesis describes infrastructure development for a "Mind Attention Interface".
This Mind Attention Interface enables sensor measurements of a subject's mind
states and attention states to be used as control and feedback data for a virtual
environment. Sensor devices measure EEG brain activity, eye gaze, and head and
hand movements. The MAI has been built for use in the Wedge, a two-walled
immersive virtual environment which combines stereoscopic computer graphics
with surround sound. Its goal is to contribute to Human Computer Interface
Figure 1.2: Feedback loop in the MAI
(HCI) and Brain-Computer Interface (BCI) research in virtual environments,
and, by so doing, provide new insights into the human behaviour and the human
The infrastructure of the MAI described here consists of four major layers:
The first layer is the Data Acquisition (DAQ) layer which handles the device
drivers, data transmission over the network, and timing. The second layer is a
central server that handles peer connections, header information and provides the
application layer clients with a gateway to access data over the network. The third
layer is the signal-processing layer, which processes raw data and provides highlevel
information for further usage. The Spectral Engine Connection Kit (SECK)
enables multiple processing modules to be used in this layer and thus distributes
processing over the network. The last layer in the MAI is the application layer
that connects to the MAI and display information in the virtual environment.
My major contributions are the MAI System, which include first and second
layers and software libraries created for the fourth layer. Although the signalprocessing
layer is largely the work of others, its interfacing components are also
a contribution of the present thesis.
When I commenced this project, the MAI had just been funded and no MAI
infrastructure existed. In the last one and half years, my research has included
the investigation and purchase of hardware, and the development of software for
the MAI framework. This thesis describes my research process: System hardware
and associated software are described in Chapter 2. Chapter 3 specifies
the MAI System software platform requirements and states the studies over a
set of comparable systems. Chapter 4 contains a discussion of the MAI software
design considerations based on the requirements. Chapter 5 describes the implementation
of the system enabling components. Utilities that create supportive
environments for carrying out experiments are also described in Chapter 5. Subsequently,
profiling results of the current system performance in comparison with
another similar system are shown in Chapter 6. Overview of this project and
future work are summarised in Chapter 7.


2002年5月2号----2003年5月6号 回忆录


5月2号 天气晴



C++ Read Binary File and convert char * to float

I recently need to write a c++ data reader. The data reader reads a file while is in binary format, and every four byte should be convert into float. I found it very easy to read file, you only need to specify ios::binary when reading. This is a bit different from c#. If you don't define ios::binary, you will get unexpected eof in the middle of the file. With regards to conversion, there are 2 possible ways. First, memcpy which is slow and time consuming. You can also do reinterpret_cast. For example:
char* tmp = new char[sizeof(float)];
float val = 0;
memcpy(tmp, val, sizeof(float));
val = *reinterpret_casttmp
This should give you some idea on how to handle binary file read. The following is the complete example, might not suit your situation though.


using namespace std;
#define interval 400

class Data {
float** data;
Data (const string& file);

Data::Data (const string& dataFile) {
ifstream file (dataFile.c_str (),ios_base::in|ios_base::binary);

string line;
int file_length = 0;

file_length = file.tellg();
file_length -= 19;

this->data = new float* [file_length/4];
for (int i =0 ; i< file_length/4 ; i++)
this->data[i] = new float [3];

// Read Header File, Basiclly Ignore It.
char* header = new char[19];

int t = 0;
char* acc = new char[12*interval];
// Read Actual Data;
while (!file.eof())
int read_length = file.gcount()/12;

for (int k = 0 ; k < read_length ; k ++ )
for(int j=0;j<3;j++)
this->data[t+k][j] = (*reinterpret_cast(acc+12*k+4*j));
t += read_length;

Tuesday, August 26, 2008




轮回. 业力.因果. 彼岸. 度. 贪. 嗔. 痴.









谈苦之余,玩了下黑板报推荐的东东,发现俺的名字roy pk 不过 dan 和 james.





小学:小学时最幸福的时代,在另一个肖老师的帮助下,垮地段的进了南昌市百花洲小学。肖老师是我的数学老师,我的班主任黄老师是现在南昌市教委的重要任务了。那时的黄老师才刚刚毕业,很年轻,现在想来可能比我还小,带着大家一起走了4年,后来离开了我们发展前途去了。五年级的时候来了个王老师,隐约记得王老师年级很大。最近一次见到肖老师和黄老师是高考的谢师宴。记得小时候常去黄老师家里上课,学语文竞赛的东西,黄老师家的小狗特别可爱,那是我唯一喜欢的小狗了。 小学还有很多好朋友,这里就不提他们了,只是写的时候,忍不住要停下来想想。


高中:高中又重演了初中时换班主任的闹剧,化学老师游老师只教了我们短短3个月。这段友谊一直在我们这个小圈子里面维系到大二。走马上任的肖老师对我的人生气了很大的帮助,至于后来换到一中之后,OBB熊老师接任,也让我伤心了好久。刚开始有个非常闹心的物理老师,总觉得我们班物理不够好,老拿难题刁难我,拿我们和四班比,那时就很羡慕一班和三班的物理老师,娇弱的可爱(男的,男的)。分班之后我如愿的得到了这个娇弱的物理老师,哈哈,虽然可能实力不如我。隔壁班有漂亮的化学老师,而我们班的肖老师却也对我胃口,虽不是美女,但绝对是好老师。语文老师是俺的心头痛,我除了考试还算对得起老师的栽培,文学方面是沾不上边了。数学老师应为叫多了外号,现在也只知道叫 “嬷嬷”,还有 “土拨鼠”。嬷嬷是对我评价和期望极高的老师,土拨鼠是数学天赋不错的一个老师。几乎解除了外国语学校所有的英语老师,比如徐明珠老师,就最喜欢我了,不过后来好像还有了其他宠爱,比如boggar。徐柯老师虽然是我的初中英语老师,但是我的英语基本上从她那里学的,当然,初中时还有几个不知名的老师,对我的帮助也很大。赵老师在高中的时候安排俺做过主持,可是俺天生好动,虽然口语相貌还过得去,但毕竟不是这块材料。







在电脑里找出一本旅游的书,津津有味的看着,最有意思的不是祖国大江南北的名胜古迹和山川河流,也不是各地的风土人情,确实家乡的点点滴滴。 “鄱阳湖的草,南昌人的宝”, 绳金塔的南昌米粉, 就留那南昌火车站的黑司机,我都丝毫没有厌恶的情绪了。



滕 王 阁 序 王 勃






























原本计划写个澳洲股市101,可以自己还没弄明白,最近时间不多,都被资本家剥削去了,不过有一点却很明显,澳洲的权证(option)市场绝对没有国内的权证市场那么容易看透,都是投机,但国内投的是机遇,难得的机会加上狂热的投机偏好,澳洲却完全是对利润最大化的理性投机。想必这幕后得到好处的,一定还是搞出这个四不像的那群管理层,蹿通了媒体的炒作和热钱的涌入,最后是价格偏离价值曲线,反而越演越烈,什么查处啊,什么严办啊,有用吗? 换个躯壳换杆枪,又是一条搅乱秩序的败类. 嗯,不久了,看看半年之后,这东西怎么收场,哈哈,我能想到的闹剧就是以一种更乱的结局来破除人们的一般性期待,从而冠冕堂皇的掩饰他们的罪行. 当然,我是这个东西受益者,因为我赚钱了.但我低估了国内这种混乱和黑暗,经过这次之后,每次投资,我都会告诉自己, "你面对的是一个混乱而黑暗的市场,不要指望靠你的理论和逻辑,贪得无厌和追求高利润是本质,学习他们操纵的手法,抓住投机的恰当机会." 宝钢才疯狂了短短两天, 不够, 只有一支玩,不够灵活,被大家盯上了还不好换地方. 大家说他要涨50%,我就涨200%,诱惑吗?我还能涨400%。只要有人跟进来一起玩,资金只要有流动,我就是活的。“不要想着最大化的利润,因为我们玩不过庄,庄家都是惹不起的主,但是跟庄赚点小钱,保赚不赔啦,哈哈”。







Monday, August 25, 2008

How to Convert between byte and Hex string

Please see the function below:

/// Convert a string of hex digits (ex: E4 CA B2) to a byte array.
/// The string containing the hex digits (with or without spaces).
/// Returns an array of bytes.
private byte[] HexStringToByteArray(string s)
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;

/// Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)
/// The array of bytes to be translated into a string of hex digits.
/// Returns a well formatted string of hex digits with spacing.
private string ByteArrayToHexString(byte[] data)
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();

Sunday, August 24, 2008


笔者通过dyndns.com注册了一个域名,并通过路由器通知域名服务商真实的IP地址。 今日我的合作伙伴需要从国内连接这个域名,却发现DNS无法解析。 这个问题在国内比较普遍,我的处理方案是通过添加一个国外的DNS服务器,从而实现解析。

以下是用来解决此问题的vbs script脚本代码,它通过快速添加DNS 150.203.x.xx,达到实现解析的目的。其实在TCP/IP属性里也可以手动添加,但过程麻烦,直接运行脚本自动添加减少了手动添加造成的不便。

On Error Resume Next

strComputer = "."
strNewDNSServer = "150.203.x.xx"

Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

For Each objNicConfig In colNicConfigs
intNewArraySize = 0
arrDNSServerSearchOrder = objNicConfig.DNSServerSearchOrder
If Not IsNull(arrDNSServerSearchOrder) Then
For Each strDNSServer In arrDNSServerSearchOrder
End If
intNewArraySize = UBound(arrDNSServerSearchOrder) + 1
ReDim Preserve arrDNSServerSearchOrder(intNewArraySize)
arrDNSServerSearchOrder(intNewArraySize) = strNewDNSServer
intSetDNS = _
If intSetDNS = 0 Then
End If

Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

For Each objNicConfig In colNicConfigs
If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
For Each strDNSServer In objNicConfig.DNSServerSearchOrder
End If

Things to do when you arrived and wanted to settle down in Australia

Things to do First

Below is a list of 7 important things that you should do as soon as possible after arriving in Australia.
1. Apply for a Tax File Number (TFN)

Do this first. To receive an income in Australia, you need a Tax File Number (TFN).
2. Register with Medicare

The Australian Government provides help with basic medical expenses through a scheme called Medicare.
3. Open a bank account

In Australia, most income including salary or wages and government benefits are paid directly into a bank account.
4. Register with Centrelink

Centrelink is a government agency which delivers a range of services to the community.
5. Register for English Classes

Communicating in English is very important and the key to your successful settlement.
6. Enrol Your Children in School

Under Australian law, children must attend school until they are 15 years old.
7. Apply for a Driver's Licence

Information on gaining a driver's licence.
Beginning a life in Australia Booklets

The Beginning a Life in Australia booklets welcome newly-arrived migrants and humanitarian entrants to Australia. They provide useful national, state/territory and local settlement information for migrants, humanitarian entrants, their sponsors and service providers. This information is available to download in English and 37 community languages for each state and territory.

Margin Lending Tips

1. Beat rising interest rates
Prepaying interest on a margin loan may produce interest savings in a rising interest rate environment. By locking at a competitive fixed interest rate for three, six or nine months, potential variable rate rises over the rest of the financial year can be avoided.

2. Can you claim 'professional trader' deductions?
Those who claim share trading as their profession rather than just being an investor must convince the Australian Taxation Office before they can claim trading losses as tax deductions. The ATO warns there are strict criteria to be met for someone to be classed as a share trader following confusion amongst investors who have incurred losses and then tried to offset these against their other income.

3. Caution needed on protected equity loans
Protected equity loan products allow investors to gain leveraged exposure to the sharemarket with a built-in safety net if their portfolio stocks take a dive. Investors can't lose their base capital but can keep dividends and capital gains. They also benefit from tax concessions with 100 per cent deductibility for their interest and capital protection costs. But not all financial planners and tax experts are convinced that these products are the best way to achieve a solid investment return. They say their high buy-in costs and uncertainty about when the Tax Office might change the deductibility treatment make them unattractive. Experts say the costs can run as high as 17 per cent in addition to paying loan interest when investors pay for embedded put options to protect the products' downside.

4. Don't try the prepay fiddle
If focussing on the tax benefits of prepaid interest, don't try and pull a swifty by taking out a loan, prepaying interest, then cancelling the loan and getting a refund of the interest after claiming the deduction. It won't work. Prepaid interest cannot be refunded. As a tax strategy, margin loans and prepaying interest are only beneficial if you plan on actually investing the borrowed funds.

5. Establishment fee protection
Under a protected equity loan arrangement, some lenders include the value of the establishment fee in the capital guaranteed amount. For example, if you borrow and invest $100,000 and $1000 is taken out in establishment fees, some lenders will still provide a capital guarantee over $100,000, others will only guarantee $99,000.

6. Fixed interest rates
Interest rates on protected equity products are fixed but not necessarily for the full term of the loan. Some products have a rate fixed for the full term, others reset the fixed rate each year of the loan term. These resets will reflect the interest rate environment at the time.

7. Is the interest on protected equity loans tax deductible?
There has been much debate about the deductibility of the interest payments on capital protected loans because of the difficulty in distinguishing between the capital protection component and pure loan interest component of the payments. Only the interest component is tax deductible. The amount of interest available for deduction will be the lower of:

* the amount determined by the Reserve Bank's Indicator Rate for personal unsecured loans
* the amount determined on a sliding scale depending on the term of the product (85 per cent for five years, 82.5 per cent for four years, 80 per cent for three years, 72.5 per cent for two years and 60 per cent for one year)

8. Loans for interest
Some protected equity lenders offer a separate, secondary loan to cover the first year's interest payment on a protected equity loan. These loans will have different rates, terms and conditions than the primary investment loan.

9. Prepay interest for tax benefits
Most borrowers are able to claim margin loan interest and other costs of investment as tax deductions - depending on personal circumstances. Prepaying twelve months in advance just before the end of the tax year is the way to make the most of the tax benefits. By paying a year's interest in June, the deduction can be enjoyed almost immediately in your upcoming tax return in July. But be aware that this really only amounts to tax deferment, not tax reduction. Investors are only bringing forward a tax deduction by one year, not reducing overall tax in the long run.

10. Tax advantages of borrowing to invest
There are several tax advantages when you borrow to invest in shares:

* you can claim your interest payments against your taxable income and if you earn less on the share investments than the interest payments you can claim the interest against other assessable income;
* you can prepay the interest up to 13 months ahead, prior to June 30, which is helpful for cash-flow planning and also allows you to claim the deduction a full year in advance;
* you can defer any capital gains tax liability until the shares are sold;
* as you're geared into the market you will own more shares than if you had paid cash, so you will receive more dividend payments. If the shares are franked then you can offset the franking credits against your assessable income.

11. The trade off between loan cost and share growth
Protected equity lenders broadly offer two different ways to reduce the high interest costs of their capital protected loans. 'Shared upside' simply offers the borrower a lower interest rate in return for sharing any capital growth at the end of the loan term with the borrower at a set proportion, eg. 25 or 50 per cent. Alternatively, some borrowers offer investors the ability to write call options over the stocks in their loan portfolio at preset "strike" prices. The sale proceeds from these options can be used to help fund the loan interest. But this also means that if the price of a stock in the portfolio rises above the option strike price, the buyers of the call options can then buy the stock outright from the investor, leaving the investor with only the capital growth up to the strike price.

Saturday, August 23, 2008

Sending small data segments over TCP with Winsock

When a Microsoft TCP stack receives a data packet, a 200-ms delay timer goes off. When an ACK is eventually sent, the delay timer is reset and will initiate another 200-ms delay when the next data packet is received. To increase the efficiency in both Internet and the intranet applications, Microsoft TCP stack uses the following criteria to decide when to send one ACK on received data packets:
If the second data packet is received before the delay timer expires, the ACK is sent.
If there are data to be sent in the same direction as the ACK before the second data packet is received and the delay timer expires, the ACK is piggybacked with the data segment and sent immediately.
When the delay timer expires, the ACK is sent.
To avoid having small data packets congest the network, Microsoft TCP stack enables the Nagle algorithm by default, which coalesces a small data buffer from multiple send calls and delays sending it until an ACK for the previous data packet sent is received from the remote host. The following are two exceptions to the Nagle algorithm:
If the stack has coalesced a data buffer larger than the Maximum Transmission Unit (MTU), a full-sized packet is sent immediately without waiting for the ACK from the remote host. On an Ethernet network, the MTU for TCP/IP is 1460 bytes.
The TCP_NODELAY socket option is applied to disable the Nagle algorithm so that the small data packets are delivered to the remote host without delay.
To optimize performance at the application layer, Winsock copies data buffers from application send calls to a Winsock kernel buffer. Then, the stack uses its own heuristics (such as Nagle algorithm) to determine when to actually put the packet on the wire. You can change the amount of Winsock kernel buffer allocated to the socket using the SO_SNDBUF option (it is 8K by default). If necessary, Winsock can buffer significantly more than the SO_SNDBUF buffer size. In most cases, the send completion in the application only indicates the data buffer in an application send call is copied to the Winsock kernel buffer and does not indicate that the data has hit the network medium. The only exception is when you disable the Winsock buffering by setting SO_SNDBUF to 0.

Winsock uses the following rules to indicate a send completion to the application (depending on how the send is invoked, the completion notification could be the function returning from a blocking call, signaling an event or calling a notification function, and so forth):
If the socket is still within SO_SNDBUF quota, Winsock copies the data from the application send and indicates the send completion to the application.
If the socket is beyond SO_SNDBUF quota and there is only one previously buffered send still in the stack kernel buffer, Winsock copies the data from the application send and indicates the send completion to the application.
If the socket is beyond SO_SNDBUF quota and there is more than one previously buffered send in the stack kernel buffer, Winsock copies the data from the application send. Winsock does not indicate the send completion to the application until the stack completes enough sends to put the socket back within SO_SNDBUF quota or only one outstanding send condition.

Friday, August 22, 2008

How to add smecontribs repository

Log into SME Server console as root.

Issue the following command

yum update smeserver-yum

Thats all. It will add the repository on completion

Sunday, August 17, 2008

Create startup script in SMEServer

SME Server is a pre-configured Linux server designed for small to medium businesses!
It used Red Hat Enterprise Linux kernel, or CentOS kernel.

When creating packages, I wanted a script to be running when the system boot up. For example, an auto usb drive mounting script. I started with something that running in the background, and didn't work quite well. Using & straight away is not a clever way because script in init.d folder should follow certain standard, and can be managed by the boot up program manager( it might be called something else).

Firstly, you can write a normal script and wrap it as the following example:

# description: usbMountWrapper is the daemon to xxxxxx

. /etc/rc.d/init.d/functions

function start()
printf "Starting %s: " "usbMountWrapper"
daemon /opt/smebackup/usbMountWrapper &
touch /var/lock/subsys/usbMountWrapper

function stop()
printf "Stopping %s: " "usbMountWrapper"
killproc usbMountWrapper
rm -f /var/lock/subsys/usbMountWrapper

function reload()
pid=`pidof ulogd`
if [ "x$pid" != "x" ]; then
kill -HUP $pid 2>/dev/null
touch /var/lock/subsys/usbMountWrapper

case "$1" in
status usbMountWrapper
printf "Usage: %s {start|stop|status|restart|reload}\n" "usbMountWrapper"
exit 1

exit 0

This is a much nice way of writing boot up script and you can start or stop them like this:
/etc/rc.d/init.d/usbMountWrapper start
/etc/rc.d/init.d/usbMountWrapper stop
/etc/rc.d/init.d/usbMountWrapper restart

Friday, August 15, 2008

C# GDI double buffer to stop screen flick

The code is really simple.

this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint , true);

I assume you know where to put them. Enjoy.

Monday, August 11, 2008

How to backup Linux to FAT32 External Drives

There is very good tutorial on this issue, however, i wanted to add a bit more. How to backup Linux to FAT32 External Drives | WickedBlog
The backup process sounds pretty easy, but indeed, there are heaps problems when you actually working on it.

I am a windows user, and nowadays, most product are targeting windows user.  I developed the backup utility for the SMEServer (e-smith server) and First of all,
the priority is that things can be extract in Windows.  Obviously , NTFS is not a good option cause it is not supported in SMEServer.  So Fat32 was chosen and I didn't realise the file size limit of 4G until some time had passed and all my backups are smaller than 4G.

Let's begin with backup first.

tar -czf /media/DRIVENAME/BACKUPNAME.tgz /home

This is the real simple solution to backup one folder, and of course, we have more to backup.  So, we introduce the following one:

'tar -cz --files-from '+ FILELIST_TAR + ' > ' + TAR_OUTPUT+'.tgz'

NOTE that I now read files from a list, and this is recommended to do only when programming.

Finally, we need to split it

'tar -cz - --files-from '+ FILELIST_TAR + ' |  split -b 3880m - ' + TAR_OUTPUT+'.tgz'

Re-constitute properly with this customized restore command:

cat /media/DRIVENAME/BACKUPNAME.tgz.* | tar -zxf -

And of course, I didn't forget the windows user, you can re-constitute the files like this:
copy /b BACKUPNAME.tgz.* ALL_IN_ONE.tgz /b


Sunday, August 10, 2008

Vi: Start-up, Modes, Save and Quit

Vi: Start-up, Modes, Save and Quit

Vi: Start-up, Modes, Save and Quit

To enter Vi type:


Vi has two modes: Normal (command) mode and edit mode.

 Switch to normal mode:     <ESC>
Switch to edit mode: i or a

Getting out of Vi (change to normal mode <ESC>):

 Exit Vi:                       :q
Exit Vi (ignore changes): :q!
Save: :w
Save and Exit: :wq

Switch to (edit) an other file:


Getting help:

:help topic

.Net window form file uploader to webservice

Wanna Upload file in a asynchronise way in .Net ? Here I create a simple demo to upload your file to the webservice.
The code below is pretty useful especially creating three-tier applications and your desktop form application is not directly connecting to database.

public partial class FileUploader : Form
public FileUploader()

private void btnBrowse_Click(object sender, EventArgs e)
using (OpenFileDialog dialog = new OpenFileDialog())
dialog.Title = "Open File";
dialog.Filter = "All Files|*.*";
dialog.FileName = "";

dialog.InitialDirectory = "C:\\Temp";
// skip it
if (dialog.FileName == "")
txtFileName.Text = dialog.FileName;

private void UploadFile(string filename)

// get the exact file name from the path
String strFile = System.IO.Path.GetFileName(filename);

// create an instance of the web service
localhost_test.GetInfo ws = new formapp.localhost_test.GetInfo();
ws.Credentials = System.Net.CredentialCache.DefaultCredentials;

// get the file information form the selected file
FileInfo fInfo = new FileInfo(filename);

// get the length of the file to see if it is possible
// to upload it (with the standard 4 MB limit)

long numBytes = fInfo.Length;
double dLen = Convert.ToDouble(fInfo.Length / 1000000);

// Default limit of 128 MB on web server
// have to change the web.config to if
// you want to allow larger uploads
if (dLen < 128)

// set up a file stream and binary reader for the selected file
FileStream fStream = new FileStream(filename,FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);

// convert the file to a byte array
byte[] data = br.ReadBytes((int)numBytes);

// pass the byte array (file) and file name to the web service using asynchronise way
ws.UploadFileCompleted += new UploadFileCompletedEventHandler(this.UploadFileCompleted);
ws.UploadFileAsync(data, strFile);

//// pass the byte array (file) and file name to the web service using synchronise way
//string sTmp = ws.UploadFile(data, strFile);
//// this will always say OK unless an error occurs,
//// if an error occurs, the service returns the error message
//MessageBox.Show("File Upload Status: " + sTmp, "File Upload");
// Display message if the file was too large to upload
MessageBox.Show("The file selected exceeds the size limit for uploads.", "File Size");
catch (Exception ex)
// display an error message to the user
MessageBox.Show(ex.Message.ToString(), "Upload Error");

private void btnUpload_Click(object sender, EventArgs e)
if (txtFileName.Text != string.Empty)
MessageBox.Show("You must select a file first.", "No File Selected");

private void UploadFileCompleted(object sender, UploadFileCompletedEventArgs args)
//Bind returned results to the UI data grid
MessageBox.Show("File Upload Status: " + args.Result + " File Uploaded.");

Saturday, August 9, 2008

Zhen Yang's Resume

Zhen Yang
yangzhen@gmail.com Mobile 0401924381


Seeking application development position where I can utilise my skills, qualifications, research experience, and abilities in IT field that offers professional growth.

Qualifications Summary

  • Technical proficiency in .Net (C#) Technology, and SQL database technologies. Over six years experiences in designing and developing web and desktop applications.
  • Demonstrated capability to explore solutions and solve problems. Comprehensive industry knowledge on both Windows and Linux platform.
  • Well established team work skills and management experience. Highly motivated and productive team player with client facing experience.
  • Extensive knowledge on OO concepts, Design Patterns, Agile development, SDLC


l  Language: C#, ASP.Net, SQL, XML/XSLT, HTML/JQuery/CSS, WCF, UML, C++,
l  Software:   Visual Studio 2003-2010, SQLServer, IIS, TFS, WebMatrix, MySQL
l  Tools:         NHibernate, Enterprise Library, LINQ, ASP.Net MVC, Entity Framework

Technical Experiences Details

2009.07-Now   Software Developer in the Commonwealth Scientific and Industrial Research Organisation (CSIRO), Land and Water Lab, Canberra
l  Working in a multi-disciplinary team of software developers and researchers. Working with large code base solutions in C# consisting multiple projects of libraries and components for various calibration, optimization, and simulation models, persistence of data. Familiar with the full software development life circle.
l  Daily responsibilities include developing new features for the enterprise level river modelling software according to plan. (C#, WCF, NHibernate)
l  Designed and developed standalone GUI calibration tools. (C#, SQLServer)
l  Product integration, bug fixing, performance tuning on existing code base
2007.10-2009.06 Software Developer in National ICT Australia (NICTA), Canberra
l  Constructed a customised software system for the Australian Institute of Sports as the core engineer. This multi-tier system collects data from device, analyses and stores results on central server, and allows coaches to manage and visualise athletes training sessions. It employed both Asp.Net and Windows Form technology, and used Web Service and SQLServer database as the backend.
l  Developed a GUI application to dynamically map GPS positions into formations for Defence Science Technology Organization.
l  Built various automation tools to support researcher team. Great attention to teamwork and customer service skills.
2006.01-2007.09 Part-time Programmer of Callidus Corp, Canberra, Australia
l  Created a multi-level backup utility with Web interface. (PHP, Python)
2005.01-2005.10 Technical director of FeedSky Corp, Beijing, China
l  Constructed Web2.0 site, Web Services, Web Crawler. (Asp.Net, XML/XSLT, JavaScript, SQLServer, IIS)
l  Supervised 6 software developers to deliver according to the business plan
2003.11-2004.12 Part-time Asp.Net Developer of Baihe Corp, Beijing, China
l  Developed a Quiz & Match module for the network site.(Asp.Net, SQLServer)
l  Maintained existing pages and applied bug fixes.

Education Background

2005.11-2007.09 Master by Research of Computer Science and Information Technology, Australian National University
l  Designed and constructed a Mind-Attention Software Interface, which includes data collection, processing and application plug-in modules. (C++)
l  Assisted in Virtual Reality demonstration applications development. (C#)
2001.09-2005.06 Bachelor of Computer Science, Tsinghua University, Beijing
l  No.4 in the college entrance exam to study at the best university in China.
l  Extensively studied subjects that form the basis of computer science, and actively utilised knowledge in industry during study.

Side Projects

2010            Reengineered archived projects by using ASP.NET MVC and Entity Framework
2009            Developed websites using Joomla Content Management System. (Html, CSS)
2008            Managed a team of 5 to build a Time Management system to validate my agile development knowledge. (.Net, Web Service, SQLServer)

Additional Experiences

2006-2007  Tutor in the Department of Computer Science, ANU
l  “New media and the Web” , “Automating Tools for New Media
2007            Apple's WebObjects technology Training, Sydney
2006            Volunteer of ANU Consulting Center “Get up and Go” program

Honours and Awards

2009-2010  Member of RiverManager Software Development team which won two “Team of the Year” Awards 
2007            Publication: “Mind-modulated music in the mind attention interface”, OZCHI
2007            ANU Miscellaneous Scholarship and Vice-Chancellor Travel Grants