Skip to content →

Author: Daoyuan Li

C a[i] vs i[a]

When following the MIT 6.828 open course, there’s one C source code discussing pointers in Exercise 4 of lab 1.

There’s one line of code in pointers.c:

3[a] = 302;

Looks weird at first sight; but TCPL says in Chapter 5.3:

In evaluating a[i], C converts it to *(a+i) immediately; the two forms are equivalent.

So: a[i] and i[a] are equvalent (if i is a constant). 🙂

Leave a Comment

i386-jos-elf toolchain on OS X Lion

Yesterday friend and I decided to follow the MIT Operating System Engineering course together in order to get a deep understanding of OS’s. And today I started setting up the cross compling environment for the labs. At first I wanted to get the toolchain from macports, but unluckily it didn’t successfully build binutils on my Mac. As a result, I started building the toolchain from the source code, following the instructions at http://pdos.csail.mit.edu/6.828/2011/tools.html.

The programs you need for the toolchain include binutils, gcc, and gdb. For compiling gcc you also need GMP, MPFR, and MPC. The source codes are available at:

wget http://ftpmirror.gnu.org/binutils/binutils-2.21.1.tar.bz2
wget ftp://ftp.gmplib.org/pub/gmp-5.0.4/gmp-5.0.4.tar.bz2
wget http://www.mpfr.org/mpfr-current/mpfr-3.1.0.tar.bz2
wget http://www.multiprecision.org/mpc/download/mpc-0.8.2.tar.gz
wget http://ftpmirror.gnu.org/gcc/gcc-4.5.1/gcc-core-4.5.1.tar.bz2
wget http://ftpmirror.gnu.org/gdb/gdb-6.8a.tar.gz

Unzip them in a directory and build binutils, gcc, and gdb one by one.

$ tar jxvf binutils-2.21.1.tar.bz2
$ cd binutils-2.21.1
$ ./configure --target=i386-jos-elf --disable-nls && make && sudo make install

In order to build gcc, GMP, MPFR and MPC needs to be built first.

$ mkdir -p libs/install
$ mv gmp-5.0.4.tar.bz2 mpfr-3.1.0.tar.bz2 mpc-0.8.2.tar.gz libs/
$ tar jxvf gmp-5.0.4.tar.bz2
$ mkdir gmp-build; cd gmp-build
$ ../gmp-5.0.4/configure --prefix=$(cd ../install && pwd)
$ make && sudo make install
$ cd ..
$ tar jxvf mpfr-3.1.0.tar.bz2
$ mkdir mpfr-build; cd mpfr-build
$ ../mpfr-3.1.0/configure --prefix=/Users/daoyuanli/Downloads/i386-elf-gcc/libs/install/ --with-gmp=/Users/daoyuanli/Downloads/i386-elf-gcc/libs/install/
$ make && sudo make install
$ cd ..
$ tar zxvf mpc-0.8.2.tar.gz
$ mkdir mpc-build; cd mpc-build
$ ./configure --prefix=/Users/daoyuanli/Downloads/i386-elf-gcc/libs/install/ --with-gmp=/Users/daoyuanli/Downloads/i386-elf-gcc/libs/install/ --with-mpfr=/Users/daoyuanli/Downloads/i386-elf-gcc/libs/install/
$ make ; sudo make install
$ cd ..
$ tar jxvf gcc-core-4.5.1.tar.bz2
$ mkdir gcc-build; cd gcc-build
$ ../gcc-4.5.1/configure --target=i386-jos-elf --disable-nls --without-headers --with-newlib --disable-threads --disable-shared --disable-libmudflap --disable-libssp --with-gmp=/Users/daoyuanli/Downloads/i386-elf-gcc/libs/install/ --with-mpfr=/Users/daoyuanli/Downloads/i386-elf-gcc/libs/install/ --with-mpc=/Users/daoyuanli/Downloads/i386-elf-gcc/libs/install/
$ make ; sudo make install

Note that it’s essential to build gcc in a directory different from the source code directory to avoid compiling errors.

Then make gdb:

$ tar zxvf gdb-6.8a.tar.gz
$ mkdir gdb-build; cd gdb-build
$ ../gdb-6.8/./configure --target=i386-jos-elf --program-prefix=i386-jos-elf- --disable-werror
$ make && sudo make install

QEMU is available in macports:

$ sudo port install qemu
15 Comments

Port already in use issue of Arduino for Eclipse plugin

When uploading with avrdude the plugin give a error prompt saying “Port already in use” (while no other application is using the port). After clicking OK it actually uploads the program to Arduino board.

port_in_use

After reading issue #6 I check the librxtxSerial.jnilib in eclipse:

.cp$ file librxtxSerial.jnilib
librxtxSerial.jnilib: Mach-O universal binary with 4 architectures
librxtxSerial.jnilib (for architecture x86_64): Mach-O 64-bit bundle x86_64
librxtxSerial.jnilib (for architecture i386): Mach-O bundle i386
librxtxSerial.jnilib (for architecture ppc7400): Mach-O bundle ppc
librxtxSerial.jnilib (for architecture ppc64): Mach-O 64-bit bundle ppc64

While in my Arduino application the librxtxSerial.jnilib output is:

llibrxtxSerial.jnilib: Mach-O universal binary with 2 architectures
librxtxSerial.jnilib (for architecture i386): Mach-O bundle i386
librxtxSerial.jnilib (for architecture ppc): Mach-O bundle ppc

So I just copied the Arduino.app//Contents/Resources/Java/librxtxSerial.jnilib file to eclipse/configuration/org.eclipse.osgi/bundles/419/1/.cp/librxtxSerial.jnilib It works after restarting eclipse. No error prompts are shown.

Leave a Comment

iCal crashes with iCal Reply Checker uninstalled

My iCal crashes everytime when someone sends me an invitation and I try either to accapt or decline it. After some investigation I found out it is the problem with “iCal Reply Checker” at http://www.nhoj.co.uk/icalreplychecker

After unstalled this app, it resets the Mail.scpt file to an empty file. To solve the problem: get another copy of Mail.scpt from another Mac, preferably from the same OS X version; and put it inside the folder: /Applications/iCal.app/Contents/Resources/Scripts

Lesson learnt: take care when trying amature software.

9 Comments

Cycling from Espoo to Lapland

An overview of the whole route:

Route to Lapland

7.1 Sunny Temperature 28 – 42+ °C

Route: Otaniemi, Leppävaara, Vantaa via Route 145 and 140 to Kerava and Lahti, around 130 km

day1

Today is the first day of my trip to hunt Santa Clause (because I haven’t recieved any gifts from him for the last 24 years). We (me and my French friend Gaëtan) started at 8:30 in the morning. The weather was a bit hot: around 28 °C even in the morning. It was until we arrived at Leppävaara when I realized I forgot to bring my bottle and tooth brush with me. Since it was not good to go back and fetch them, I decided to ride on and buy the necessary stuff in
Lahti.

We went via a road close to Vantaa Airport, where we saw planes around 50 meters above us. There were fields full of rape flowers, astoundingly beautiful under the sunshine.

We stop at around 12:30 for lunch, about 75 km from my home. After lunch we rested a bit and restarted at 14:00. It was even hotter in the afternoon; the temperature reached more than 42 °C at 5 pm. There were some slopes when entering Lahti; some slopes as well in the city. One
cyclist encouraged us with a thumb up; while one guy in a car at Lahti downtown showed us his middle finger. I guess some Finns don’t like foreigners. We bought some food in Lahti and refilled our bottles at a bar next to a gas station. At around 6 pm we arrived at a lake and found a camping place among the trees. We put up the tent on a small road leading to a farm field and went to swim, because there were too many mosquitoes in the woods. Unfortunately the bottom of the lake is
covered my mud; but it was OK just near the shore. The temperature of the water is just perfect. So we washed ourselves and then had dinner. There were a lot of fish in the lake. Some of them have red wings and tails and they were standing with their heads down in the water.

It was around 8 pm when we tried to have a rest in the tent. However, it was too hot. The temperature was around 28 °C and the sun was still hanging in the sky baking the tent. Outside the tent it was not
so hot, but there were mosquitoes trying to kill us. I stayed in the tent and it was until an hour later when the temperature was comfortable. Besides the high temperature, the humidity was also high. It was difficult even to breathe. There were kids playing in the water and making a lot of noises till 11:00 pm. Finally I felt asleep after 12:30 am. It was not a good sleep. My sleeping bag kept me too warm and there were mosquitoes in the tent.

7.2 Sunny/Cloudy/Overcast Temperature 28 – 42+ °C

Route: Lahti to Asikkala via Route 24 and Roads 3131 and 313, to Virtaa and Otamo via Road 314, to Sysmä via Road 410, to Luhanka via Road 612, to Putkilahti via Road 610, around 125 km

day2

We started again at
8:30 am today. It was as hot as yesterday. There was a field full of rape flowers again. The road began to be bumping. There were a lot of slopes since we were entering Middle-Finland (Keski-Suomi). There were a lot of lakes as well. On the way to Sysmä there was a part (around 5 km) of a road with water on both sides.

water-both-sides

We had lunch on a dock for motorboats near a gas station. There were lotus leaves and flowers on the water. Not surprisingly, the bottom of the water was also covered with mud. Gaëtan didn’t mind and swam in the water twice, once before lunch and once after. There were people driving there motorboats to the dock in order to refuel at the gas station. I noticed especially on old couple in their 50s. When the husband was refueling the tank, the wife stood on the dock and
watched her man with a constant smile on her face. They didn’t speak much but you could feel their love for each other. We rested a bit after lunch and started again a few minutes past two.

In the afternoon it was even hotter. Besides the high temperature, the slopes also made it difficult to cycle. When we were approaching Luhanka, the newly paved asphalt roads nearly melted and it was extremely difficult to move on. Anyway we had to because we have to buy food ahead in
Luhanka. Luckily we arrived at Luhanka 40 minutes before the shop closed (6:00 pm for Saturdays). The price was a bit expensive but we felt lucky to find one shop. The town was tiny: in Luhanka center there were one shop, two restaurants, one gas station, and a parking space for around 10 cars. When we were leaving, one guy in the restaurant waved goodbye and gave us a thumb up.

We had dinner somewhere beside Road 612 and moved on shortly, since there were mosquitoes. We did
another 10 km before we found a place to camp. We put up our tent beside a big lake and swam in it. The water was perfectly clean and the temperature was quite OK. It rained before we arrived at the place, as a result, almost no mosquitoes were found. When I was about to go into the tent, there was a motorbike fleet passing by on Road 610. There were almost 50 motorbikes. It seems that Finns are fond of noisy motorbikes.

7.3
Overcast/Rainy Temperature 15 – 25 °C

Route: Putkilahti to Korpilahti via Road 610 and Route E63, to Petäjävesi via Road 607 and Road 604, to Multia and Karstula via Route 58 (European Highway E18) , around 150 km

day3

The road became more bumping. There were a lot of slopes
and I reached my top speed in my biking career: around 60 km/h. We were diving more into the country side and around 20 km of Road 607 was not paved. This was the “take-me-home”-kinda country road. There was a lady walking her dogs with her apron on. There were a lot of sings warning uneven road. Gaëtan was half serious: “it’s funny that they don’t know what is flat”.

src=”images/stories/blog/BikeToLapland/uneven.png” alt=”uneven” width=”235″ height=”164″ />

We didn’t rest a bit after lunch because it was too cold. I was wearing my jacket and wasn’t sweating. We stopped at around 7:00 pm and put up the tent beside a field. It was so cold that we had dinner in the tent.

7.4 Overcast/Sunny Temperature 15 – 25 °C

Route: Karstula to Kivijärvi, Kinnula, Yli-Lesti Route 58 (European Highway E18), to Reisjärvi via Road 7594, to Sievi via Road 760, around 155 km

day4

It was still cold in the morning and I was wearing my jacket. We did around 85 km before lunch and arrived at Kinnula. This small city even has a small stadium
with less than 100 seats. Two high school girls were teaching a bunch of 5 year olds to play Finnish baseball. We had lunch watching them play and had a rest on the bench for half an hour after lunch. When we were about to leave, one girl came to talk with us. She told us there are roughly 1800 inhabitants in the city and they have a high school as well. Their high school has 55 students. She also told us Finnish baseball is more popular than football in Kinnula, when I asked why the seats
are arranged on the baseball field instead of the football field.

We changed our route to Road 7594 to Reisjärvi instead of following Route 58 to Lestijärvi since we thought that would be a shorter route. It was shorter, but Road 7594 was not paved. The road condition was better than Road 607 yesterday, but it was still a bit bumping. At some point my mattress fell off from my bike, fortunately a truck driver coming towards us saw it and notified Gaëtan with
gestures. Gaëtan didn’t know what the driver meant at first, but he followed back and found the mattress. I was lucky! We were in the country side but there were houses every half a kilometer. Most families have two cars and their houses are mostly made of wood. School buildings are made of concrete though.

Afraid of not being able to get to Sievi in time, we bought some food in Reisjärvi. They are paving roads with asphalt there, and there are people in the
intersections holding “STOP” signs in order to warn vehicles. We arrived at Sievi at around 8 pm and Gaëtan went to buy some more food. He was tired and didn’t want to go further. So we found a place to camp. When I stopped, I felt something on my legs. At first I thought it might be grass, so I moved my legs a bit. It was still there. I looked down and found around 20 mosquitoes on my legs and more were coming. We jumped onto the bikes again and stopped at another place.
There were still many mosquitoes. We were jumping while trying to get our mosquito protection spray. It was better after we had applied the spray. But it was really scaring to think about those crazy mosquitoes. They probably were able to kill someone!

Gaëtan said he was impressed because we were totally one day ahead of schedule and we were already close to Oulu.

7.5 Overcast/Sunny Temperature 25 – 35
°C

Route: Sievi to Ylivieska via Route 63, to Oulainen, Vihanti, and Liminka via Route 86, around 140 km

day5

We started at 8:00 in the morning and had lunch near a gas station in Vihanti. Route 86 was a bit dangerous since there were many cars and trucks on the road. They
generally ran somewhere 80 to 100 km/h. There were also many caravans in both direction to the north and the south. Maybe some people were heading for a vacation while others had finished their vacation. There were a lot of bus stops on every road. I almost ran over a squirrel, but it escaped from death by a 30 cm margin. However, there were usually dead squirrels, rabbits, or even birds on the road. Humans are a great thread to animals’ lives.

After lunch we had a
rest on the grass. It was sunny and warm and I fell asleep. I even had some dreams in my 30 minute sleep. We bought food in Liminka and planned to camp by the sea shore. However on our way we found a place indicating a swimming place in the other direction. Strangely, there were no lakes or rivers around. Gaëtan went there to figure what that was and came back very excited: “I found a paradise for camping!” I followed him there in Tupos and it turned out to be a swimming
pool. There was even artificial beach and a toilet! But when we arrived there were a lot of kids swimming there. We changed and jumped into the pool. I was too shy to take out my lotion to wash my body, but Gaëtan took his soap, went to the other side of the pool where no one was swimming, and washed himself and even his shirt.

tent

I wanted to wash
myself when no one was there. So I had dinner first. There were a lot of mosquitoes. In order to protect myself, I buried my legs in the sand. Gaëtan thought of something more novel: he had dinner standing in the water! Still there were mosquitoes trying to attack my arms and head. I killed around 50 mosquitoes in half an hour. I waited until almost everyone had left and the washed myself with lotion. It was already around 9 pm and it was a little cold.

style=”background-color: #ffff00;”>7.6 Overcast/Sunny/Cloudy/Rainy Temperature 25 – 35 °C

Route: Tupos to Oulu, Haukipudas, Ojakylä via Road 847, to Ii, Olhava, Simo via Highway 4/E8/E75, to Ranua via Road 924, around 160 km

day6

I woke up feeling uncomfortable in
my throat. We went through Oulu and it was difficult to find our way in the city. We went on Highway number 4 before Ojakylä. There was about 1 meter’s space left for us, but it was not safe since vehicles were running at 100 km/h.

highway

We entered Lapland from Simo and bought food there. After that we went on Road 924 towards Ranua. There
were not many people in Lapland. There was a part of the road where we biked more than 10 km without seeing any houses.

plane

There was a sign showing a plane that confused me. We were far away from any airports and I was like WTF when I saw the sign. After a while the road became extremely wide, to around 30 meters. Then I thought that they
might be building a new airport. (The Finnish sentence below the plane translates to “road will be closed shortly”)

airport

runway

We saw a triple rainbow at the “airport”, though in the
picture only two are apparent, the lower one is actually made up of two rainbows.

rainbow

We kept cycling because we are afraid of bears and wolves, since there were no people living by the road. We felt extremely tired when we finally found some houses. It started raining immediately after we got off our bikes.

7.7 Sunny Temperature 25 – 35 °C

Route: Ranua to Rovaniemi via Road 924 and Route 78, around 110 km

day7

My mattress was not inflated when I woke up. But fortunately today was the last day for me. I was planning to give it to Gaëtan since
his broke down in the first day of our trip.

My knees were painful but I had to move on. On Road 924 we saw some animal standing in the middle of the road about 200 meters away from us. It was not afraid when a car was coming to it. Finally when the car was just 20 meters from it and was trying to slow down, it slowly jumped off road. We rode forward and found out it to be a reindeer. What was she doing in the middle of the road? Sun-bathing? It was not afraid of us at all. By the
side of Route 78 we also saw many reindeers.

When I was about 50 km from Rovaniemi, I started thinking why I was doing this (biking to Lapland) in the first place. This was my typical behavior. What did this week bring to me? Has all of this been meaningful? Then I became sad, just as every time when I think about what I have been doing. However, as I thought and thought, I realized that there might not be meaning for everything one do, at least for the moment when he’s
doing that. The point is to try to finish the things I have started in a graceful way, regardless they’re meaningful or not. It does not take much to finish something when it’s 99% done. All you need to do is to keep fooling/believing yourself as what you have been doing before. Maybe this is the most important lesson I’ve learnt during this trip.

rovaniemi

We did 90 km in the morning and arrived at the railway station of Rovaniemi before lunch. I bought the ticket and paid. Then I realized I didn’t ask for a student discount. So I showed the lady my student card and she gave me back 40 euros. Maybe I was just too tired or too excited.

We had lunch on the grass beside the railway station. Then I handed over my tent, tools, and Gaëtan’s bottle to him. We went to Santa Clause Village
together and took some pictures beside the Arctic Circle – Mission almost accomplished, except that I was too tired to hunt Santa Clause anymore; maybe next time! Gaëtan continued further north. Wish him luck.

arctic

The whole route.

Leave a Comment

Back on bike

I haven’t cycled much since my previous bicycle was stolen in Stockholm last year, which ruined my plan of cycling from Stockholm to Helsinki. Now I’m planning something similar: I’m cycling from Helsinki to Lappland — not so big deal compared with the previous plan, but still better than nothing.

In order to prepare for the journey, a French friend and I went to Porvoo, a small city around 50
km to the east of Helsinki. It started well, the weather was not perfect but except for the drizzling part it was all right. Then it started raining heavily and we got somewhere in Helsinki. After we were finally able to locate our position it turned out a part of the route was closed due to construction. Fortunately we managed to find out another path and rode all the way to the destination. In total the 60 km journey took us 4 hours, including the time wasted in Helsinki, not bad at
all.

My friend’s new raincoat was in pieces one hour after he put it on. This may be too obvious: it was made in China.

Immediately after we arrived at a park near the city center of Porvoo, a young lady approached me and said ‘moi’. I ‘moi’ed back and then she started speaking Finnish to me. She talked for around one minute and stopped, looking at me. I replied, “Anteeksi, en puhu suomea.” She seemed embarrassed and asked if I speak English. It turned out she was
writing an article about the park and wanted to know my opinion on it. I felt flattered (come on, a journalist was interviewing me :D) and complimented on the park. We talked a bit about the park and she asked our names and took some pictures of us. I couldn’t help to be excited when I thought of I’d appear on some newspapers or magazines — first time indeed.

After lunch we spent half an hour visiting the old town. There’s not much to note down, except that I met an American
in the church and he speaks Chinese. Around 1:30 we got on our bikes again and headed back. It was much more difficult since we were riding too fast in the morning and felt tired once we got on the bike. Headwind made it harder. But I was motivated by a cyclist on the road. He stopped us asking the road to Porvoo. I gave him my map and asked where he was from. He said he was from Hanko and had been riding for 20 hours… How crazy was that? Anyway it took us more than 5 hours to get
back. And I couldn’t feel my ass after I arrived at home…

It was really quite an experience. We survived the rain, unfamiliar route, headwind and physical exhaustion. In the following weeks I’d do more exercises, if I want to survive the 1000 km journey.

PS. Porvoo is quite, as anyone would expect for a city with a population of 35,000 (source: the journalist).

porvoo

Leave a Comment

Bug in Waspmote API v0.15

I found a bug in Waspmote API v0.15 when I was trying to set XBee link keys. The API failed to set the key as specified in the code. The bug lies in function gen_data()” in lines 4355-4403. Details below. However, it was corrected in v0.18.

/*
 Function: Generates the API frame to send to the XBee module
 Parameters:
 	data : The string that contains part ofthe API frame
 	param : The param to set
 Returns: Nothing
 Values: Stores in 'command' variable the API frame to send to the XBee module
*/
void WaspXBeeCore::gen_data(const char* data, uint8_t* param)
{
	uint8_t inc=0;
	uint8_t inc2=0;
		
	clearCommand();
	it=0;
	while(data[it] != '\0') {
		inc++;
		it++;
	}
	inc/=2;
	
	while(inc211) 
	{
		for(it=0;it<8;it++)
		{
			command[inc-9+it]=param[it];
		}
	}
	else if(inc==11)
	{
		for(it=0;it<3;it++)
		{
			command[inc-4+it]=param[it];
		}
	}
	else if(inc==10)
	{
		for(it=0;it<2;it++)
		{
			command[inc-3+it]=param[it];
		}
	}
	else command[inc-2]=param[0];
}

The function in v0.18 is as follows:

/*
 Function: Generates the API frame to send to the XBee module
 Parameters:
 	data : The string that contains part of the API frame
 	param : The param to set
 Returns: Nothing
 Values: Stores in 'command' variable the API frame to send to the XBee module
*/
void WaspXBeeCore::gen_data(const char* data, uint8_t* param)
{
    uint8_t    inc=0;
    uint8_t inc2=0;
		
    clearCommand();
    it=0;
    while(data[it] != '\0') {
        inc++;
        it++;
    }
    inc/=2;
	
    while(inc2

Leave a Comment

Generating UML diagram from Java source code

Sometimes we may need to generate UML diagrams from source codes. Here’s what I do for Java code: graphviz + ant + UMLGraph. Details below:

1. Install graphviz and ant, download UMLGraph from http://www.umlgraph.org/

2. Place UMLGraph.jar in your project, for example, under
lib/

3. Write or modify your ant script, for example:


   
   The specification for the Java-based umlgraph build processes.

 
   
   
   
   
   
   
   
 
   
       
       
       
       
       
       
  
 
   
       
           
               
               
                   
               
          
           
       
   
 
   
       
           
               
               
                
               
               
               
               
               
               
               
          
       
  
 

4. Run this ant script.

ant javadocs

5. You will get the UML class diagram as expected in the generated Java docs. Here’s one example (click to enlarge):

com.andryy.hccdroid

Leave a Comment

码农

最近看系统编程准备面试,顺便找点儿小算法练练手。在面试书上看到写冒泡排序的面试题,心血来潮也来练练手。闭着眼睛敲完代码,编译竟然没有错误,运行了一下结果也竟然是对的。

于是重新打开代码,怀着无比复杂的心情来审视自己的代码,郁闷的是看不懂自己5秒钟之前写的代码。我一边很囧的看着书上给出的代码,一边对着自己的代码检查。迷迷糊糊五分钟过去之后还是看不出来自己的代码是不是冒泡排序……

无奈之下拿出笔在草稿上画图一步一步推,终于验证了自己代码的正确性……30秒写完代码,300+秒来读自己写了什么,确实够囧的,
不知道是大一的时候代码背的太熟了的缘故……

估计以后当了码农会经常出现这种状况吧:噼里啪啦的一顿敲代码,敲完之后对着显示器一顿发愣,TMD刚才都敲了些啥?就像真正的农民种田一样,种久了之后做事情完全不过脑,偶尔思考一下的时候就会感慨:我靠,我这块地为啥要撒这么多种子,用这么多化肥啊。第二天睡觉前恍然大悟:就应该放这么多才对!之前折腾个什么劲儿阿!

Leave a Comment

Qt画图

Qt提供了一个QPainter来画图,可以用来绘制矢量图,也可以用来装载图片。今天实现的是一个给照片加边框的功能,为了练习,将PicFrame构造成一个继承自QWidget的自定义Widget。这时QPainter不能直接在自己定义的Widget中使用,而需要在paintEvent(QPaintEvent *event)中实现,否则会有类似于“QPainter::begin: Paint
device returned engine == 0, type: 1”的错误消息出现。

void PicFrame::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QRect rect(0, 0, image.width()*(1+frameSize), image.height()*(1+frameSize));
    painter.fillRect(rect,color);
    QPoint point(frameSize*image.width()/2, frameSize*image.height()/2);
    painter.drawImage(point, image);
}

=============================心情分割线=============================

今天NordSec2010开始,又见到了很多老朋友。再聚首总是有很多要交流的,大家都在为毕设发愁,都在为前途迷茫。从来没有像现在这样反感学术,当初不去美国的决定似乎是对的。

Leave a Comment

千里之行

用Qt写计算器,花了我一个晚上终于写出来一个能用的了,能赶上大二学Java时写计算器的速度了。

用Qt Designer设计界面比较方便,用熟之后效率会更高。把界面设计好之后可以通过继承的方式给自己的类添加逻辑。如果设计的界面保存为mycaculator.ui的话,uic将会自动将这个XML文件转换成ui_mycaculator.h,其中的namespace为Ui。

#include"ui_mycaculator.h"
class Caculator : public QMainWindow, public Ui::MyCaculator

另外,Qt对字符串的处理简直跟Java一样了:

QString s1 = expStr.split(QRegExp("[+-*/]"))[0]; 
QString s2 = expStr.split(QRegExp("[+-*/]"))[1];
double d1 = s1.toDouble();
double d2 =s2.toDouble();
resStr = QVariant(d1+d2).toString();
expStr.append(resStr);

总算是迈出了第一步,再接再厉。

更新:上面的正则表达式不对,因为’+’, ‘-‘和’*’在正则表达式中有特殊意义。应该为如下:

QString s1 = expStr.split(QRegExp("[\\+\\-\\*/]"))[0];
QString s2 =expStr.split(QRegExp("[\\+\\-\\*/]"))[1];
double d1 = s1.toDouble();
double d2 = s2.toDouble();
resStr = QVariant(d1+d2).toString();
expStr.append(resStr);
Leave a Comment

Minun tavallinen päivä Suomessa

Minä opiskelen TKK:ssa, Suomessa. Työpäivänä aamulla herätyskello soi kello 7, ja minä herään. Minä nousen ja käyn suihkussa. Sitten minä juon maitoa ja joskus syön omenaa. Minä pyöräilen kurssille, koska minulla on uusi polkupyörä ja asun Otaniemessä. Päivällä minä olen kurssilla TKK:ssa. Lounasta minä syön ystävän kanssa Tietokonetalossa tai Päätalossa. Minä syön usein riisiä, leipää ja lihaa ja syön paljon. Iltapäivällä minä olen myös kurssilla tavallisesti. Minä en pidä kurssista, mutta minun täytyy mennä kurssille. Illalla minulla ei ole kurssia, mutta minun täytyy tehdä kotitehtävät. Minä menen kotiin noin kello 18 ja sitten teen illallisen. Minä osaan tehdä hyvää kiinalaista ruokaa, mutta en tykkää laittaa ruokaa. Kello 20 minä alan tehdä kotitehtävät. Minä en katso televisiota, koska minulla ei ole televisiota. Mutta joskus minä katson filmiä tietokoneella. Normaalisti minä nukun noin kello 24.

Viikonloppuna minä olen Solvallassa. Minä opiskelen suomea siellä. Minä opiskelen suomea, koska haluan olla työssä Suomessa. Perjantaina minä käyn Solvallassa ystävän kanssa. Me menemme taksilla. Me opiskelemme suomea noin kaksi tuntia, sitten me syömme illallisen ravintolassa. Siellä ruoka on aina hyvää ja minä syön usein paljon. Joskus me käymme saunassa kello 20. Minä pidän saunasta paljon! Minä uin usein järvessä siellä. Lauantaina ja sunnuntaina meillä on myös suomen kurssi. Opettaja on hyvä ja minä opiskelen hyvin paljon suomea siellä Solvallassa.

Me tulemme Otaniemeen iltapäivällä sunnuntaina. Sitten minä käyn kaupassa ja ostan ruokaa. Minä soitan kotiin Kiinaan tietokoneella joka viikko. Äiti ja isä ovat aina iloisia, kun soitan.

Minä tykkään Suomesta hyvin paljon ja haluan asua Suomessa ikuisesti!

Leave a Comment

Suomeksi

Daoyuan Li on opiskelija TKK:ssa, Espoossa, Suomessa. Hän opiskelee suomea nyt koska hän haluaa työtä täällä. Suomen kieli on vaikea, mutta hän aikoo puhua hyvin suomea. Hiljaa hyvä tulee!:)

 

Leave a Comment

Qt学习:简介和信号与槽机制

以前以为Qt比较麻烦,今天看了一下,发现它其实不比Java难。

首先Qt有非常详细的文档。这个对于开发者来说是十分重要的,纵览现在的流行开发平台,不管是Java,还是微软的平台,都有为开发人员提供详实的文档和指南。如果没有文档支持,开发过程会相当痛苦。这一点我深有体会,前段时间用libpcap写点儿小程序,这个库的所有文档就是一页man page,我甚至不知道某个函数的参数到底是什么类型。

其次,Qt的跨平台性能不输Java。Qt现在支持大多数桌面平台,Windows,Linux和Unix,Mac,手机平台上面的应用也已经成熟。开发者不用更改一行代码,就可以使自己的应用程序运行在每一个操作系统中。

还有,Qt被Nokia收购之后推出了配套的IDE,Qt Creator。这个IDE强大且美观,包含方便的图形界面设计工具,图形化调试工具,手机界面模拟器以及多样化的版本控制工具支持。

总体来说,Qt的易用性是不错的,易于上手,易于开发;但是至于性能,包括速度和安全性,我目前还没有一个清晰地认识。但我相信Nokia里面的那帮人会不断想方设法的提升Qt性能的,毕竟Nokia现在手里的王牌也只有这个了。

Qt之中提供了方便的消息传递机制:信号和槽机制(Signals and Slots),这也是Qt的核心机制,用于对象之间的通信。他的格式如下:

connect(Object1, SIGNAL(signal), Object2, SLOT(slot));

当Object1的信号被触发时,Object2的相应槽就会给以相应。当然,上面只是信号与槽的一种连接方式,其他方式还可能是:
一个信号与另外一个信号相连,即一个信号触发另外一个信号:

connect(Object1, SIGNAL(signal1), Object2,
SIGNAL(signal2));

一个信号与多个槽相连:

connect(Object1, SIGNAL(signal), Object2, SLOT(slot1));
connect(Object1, SIGNAL(signal), Object3, SLOT(slot2));

同样的,一个槽也可以响应多个信号:

connect(Object1, SIGNAL(signal1), Object2, SLOT(slot));
connect(Object3, SIGNAL(signal3), Object2, SLOT(slot));

简单的例子:

#include
#include

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QPushButton b("Quit");
    b.show();
    QObject::connect(&b, SIGNAL(clicked()), &app, SLOT(quit()));
    return app.exec();
}
Leave a Comment

UML Review

Input and output of different stages in software development:

StageInputsOutputs
Requirement AnalysisStackeholders, goals, existing bussiness processesBusiness models, use case models, prototypes
Systems
Analysis
 Business models, use case models, prototypes Use case definitions, object model, prototypes
Design Use case definitions, object model, prototypes Object model, data model, component model, architectural view, interface specifications
Implementation Object model, data model, component model, architectural view, interface
specifications
Source code, complied code, database, interfaces, deployment plan
Testing Business models, use case models, use case definitionsFault report, acceptance

Activity diagrams are used to describe flows in a variety of situations, they are flow diagrams and can be used in business modelling, requirements modelling, systems analysis and design.

Use case diagrams are used to show the presentation of functionality of a system and its interaction with the outside world. The diagrams show the boundaries of software systems but do not specify functionalities. They can be used in business modelling and requirements modelling.

Class diagrams show the static structure of a system, with classes and relationships between classes. They are used in business modelling, requirements modelling, systems analysis and design.

Statechart diagrams are used for modelling the internal state changes of and object and are a variant of activity diagrams with largely the same notation. They are used in business modelling, requirements modelling, systems analysis and design.

Sequence diagrams provide a time-ordered mapping of steps in the execution of a scenario into interactions between objects. They are one of the primary tools ofr elaborating use cases in analysis and design. They are used in systems analysis and design.

Collaboration diagrams provide a mapping of steps in the execution of a scenario into interactions between objects, drawn in two dimension in a similar way to class diagrams. They are used for similar purposes to sequence diagrams, but present the information in a different way.

Component diagrams show the implementation structure of the application and are used by the designer to indicate where the objects are implemented and how the components interact.

Reference: Ken Lunn, Software Development with UML, Palgrave Macmillan, New York, 2003, pp362-376

Leave a Comment