Blog Archive

Wednesday, November 24, 2010

Matlab foder and file read in loop & Struct

function speakerData=DirFileRead(dirName, sentenceNumPerSpeaker);
% speakerDataRead: Read wave file info for speaker identification from a given directory.
% Usage: speakerData=DirFileRead(dirName, sentenceNumPerSpeaker);
% dirName: root directory that contains subdirectory of each speaker, in which the wave files reside.
% senenceNumPerSpeaker: How many sentences to read for each speaker
% speakerData: the retrieved data structure
% Adapted from Roger Jang


if nargin<1
fprintf('We will make a demo here');
fprintf('First we will create fake folder with one file saved under temp_demo/dir1/1a1 ');
mkdir('temp_demo/dir1/1a1');
mkdir('temp_demo/dir1/1a2');
mkdir('temp_demo/dir2/2b1');
mkdir('temp_demo/dir2/2b2');
save temp_demo/dir1/1a1/space.txt;
dirName='temp_demo'; sentenceNumPerSpeaker=1;
fprintf('read dir and file');
speakerData=DirFileRead(dirName, sentenceNumPerSpeaker)

fprintf('Display result:');
fprintf('Total %d files/folders are under %s', length(speakerData), dirName);
fprintf('File/Folder 1 is: %s', speakerData(1).name );


end
if (dirName(end)~='/') | (dirName(end)~='\'); dirName=[dirName, '/']; end

% dirName='E:\SI_Ref\data_digit\waveFile';
% ====== Collect feature from all wave files
speakerData = dir(dirName);
speakerData(1:2) = []; % Get rid of '.' and '..'
speakerData=speakerData([speakerData.isdir]); % Take directories only
speakerNum=length(speakerData); % speakerNum=28
for i=1:speakerNum
waveFiles = dir([dirName, speakerData(i).name, '/*.wav']); % this is euqal to waveFiles = dir('dirName\speakerData(i).name/*.wav');
% eg; [dirName, speakerData(i).name, '/*.wav']=E:\SI_Ref\data_digit\waveFile\10028/*.wav
% This line works the same as the next line.
% waveFiles = dir([dirName, '\',speakerData(i).name, '/*.wav']);
waveNum=length(waveFiles);
% fprintf('%d/%d: Reading %d wave files recorded by %s\n', i, speakerNum, waveNum, speakerData(i).name);
for j=1:waveNum, % wavNum=20
if j>sentenceNumPerSpeaker, break; end % sentenceNumPerSpeaker=2
speakerData(i).sentence(j).path = [dirName, speakerData(i).name, '/', waveFiles(j).name];
% fprintf('\t%d/%d: Processing %s...\n', j, waveNum, speakerData(i).sentence(j).path);
speakerData(i).sentence(j).text=waveFiles(j).name(1:end-4); % "end-4" means truncate the part of ".wav"
% =10028-0b, ie, the name of the wave file without the extention name
end
end

speakerData=rmfield(speakerData, 'isdir'); % get rid of 'isdir' field
speakerData=rmfield(speakerData, 'bytes'); % get rid of 'bytes' field


%self_demo
%wav_dir='E:\SI_Ref\Data_Demo';speakerDataRead(wav_dir,1);

Monday, November 22, 2010

Matlab text file read example and tutorial

function myFileRW(input)


% 确定此文件有多少行(numline)
fid = fopen(input,'r');
numline = 0;
disp('total line')
fid
while feof(fid) ~= 1
currentLine = fgetl(fid);
numline = numline + 1;
end
fclose(fid);





fid = fopen(input,'r');
numline = 0;
while feof(fid) ~= 1
currentLine = fgetl(fid);
sprintf('Show the line of NO. %d',numline)
currentLine
numline = numline + 1;
end
fclose(fid);

Apple最新发布!第四代苹果手机:iPhone 4全面介绍 - 苹果fans-中文Apple Blog

Apple最新发布!第四代苹果手机:iPhone 4全面介绍 - 苹果fans-中文Apple Blog: "Retina"

Saturday, November 20, 2010

C语言结构体赋值

C语言结构体赋值

1 对成员赋值.
1.1 {}形式.
struct st1 st1 = {1,2,3);
1.2 linux kernel
风格.
struct st1 st1 = {
.a = 1;
.b = 2;
};

2
对整体赋值.
struct st1 a, b;
b = a;

3
结构体作为函数返回值对另一个结构体赋值.
struct st1 func1();
struct st1 a = func1();

举例:
[ctest]# vi t.c

#include

struct st1 {
int e1;
int e2;
};

struct st1 func1()
{
struct st1 h = { 77, 88};
return h;
}

int main()
{
struct st1 a = { 33, 44};
struct st1 b = {
.e1 = 55,
};
struct st1 c;
struct st1 d;
c = a;
d = func1();
printf("e1 e2 is %d %d\n", a.e1, a.e2);
printf("e1 e2 is %d %d\n", b.e1, b.e2);
printf("e1 e2 is %d %d\n", c.e1, c.e2);
printf("e1 e2 is %d %d\n", d.e1, d.e2);
return 0;
}
"t.c" 29L, 420C written
[ctest]# gcc -o a t.c
[ctest]# ./a
e1 e2 is 33 44
e1 e2 is 55 0
e1 e2 is 33 44
e1 e2 is 77 88

Friday, November 19, 2010

myFeng: SVMlight使用简介

myFeng: SVMlight使用简介: "http://www.cs.cornell.edu/People/tj/svm_light/#References"

shogun | A Large Scale Machine Learning Toolbox

shogun | A Large Scale Machine Learning Toolbox: "The SHOGUN Machine Learning Toolbox"

The comparation between libsvm and SVM light

libsvm和svm-light比较 【zz】

发信人: CnF (帮我开机器-程序跑起来没有?), 信区: AI
标 题: Re: 有没有大侠比较过libsvm和svm-light?
发信站: BBS 水木清华站 (Mon May 12 01:04:12 2003), 转信

不会吧? 我以为libSVM是目前最快的SVM训练软件呢. SVM-light2.0是98年出来的,
挺土的,因为那时候还刚开始探索decomposition algorithm.它的算法详见
Joachims, T. (1998). Making large-scale SVM learning practical. In B. Scholk
opf, C. J. C. Burges, and A. J. Smola (Eds.), Advances in Kernel Methods - S
upport Vector Learning, Cambridge, MA. MIT Press.
同年出现的还有Platt的SMO算法. SVM-light还没有用上SMO的二维二次规划问题的
解析解法(虽然它也用的两个样本的working set). 但是可能由于它的其他得力机制,如
shrinking和Kernel Cache,在比较中才比SMO快的.(SVMlight用了80M内存,SMO没有用,光
这一点就不平等,我怀疑Joachims的算法实际上没有SMO快的.)
LibSVM2.3是2001年才出来的,其算法详见
Chang, C.-C. and C.-J. Lin (2001c). LIBSVM: a Library for Support Vector Mac
hines (Version 2.3). http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf (Ju
ne 2001)
它综合了SVM-light和SMO的算法,而且还是被Keerthy改正过的SMO, 在很多地方比J
oachims的算法考虑得精细得多(比如shrinking机制,确实想得够妙了), 当然Joachims提
出了这些机制的思想,虽然实现得比较粗糙,但对于后来算法的发展有重要意义.
我觉得LibSVM不太可能比SVMlight慢吧,不过我只是这么一想,没做过试验. 你比的
是它们的什么版本? LibSVM出来2.4了,不过核心算法还是2.32的没变. SVMlight我不知
道后来又出新版本没有. 要试验比较的话, 注意让它们在同等条件下比较,包括解同样的
问题(这个其实不用说了,数据集,样本数,C值,核函数参数都要一样), 同样的Kernel Ca
che大小(也就是内存使用),同样的终止条件(这里注意LibSVM默认用的双边KKT违反tole
rance=0.001的终止条件,而SVMlight用的单边tolerance,默认大概也是0.001,也就是比
LibSVM松了一倍.) 后面二者对速度影响会很大的. 另外还有它们用的浮点数类型是否一
样, LibSVM默认用float而不是double型存放核函数矩阵的元素, 等于可用内存大了一倍
, 但结果的有效位数会下降.
至于分类效果好坏, 应该跟用哪种解二次规划的算法没什么关系吧. 只要它们用一
样的终止条件卡着, 结果应该都是精确的. 但是支持向量个数及alpha值,b值都会差一点
,这个不奇怪,就是吧样本顺序重排一遍再算结果也会有少许区别的. 如果试验中两个算
法用的一样的终止条件, 分类效果总是一个明显比另一个好,那就实在太奇怪了, 只能说
明我的理解不对了.

【 在 alamarik (走向成熟) 的大作中提到: 】
: 最近弄了一阵子svm,发现libsvm和svm-light两个工具
: 听不错的。其中,libsvm似乎是从svm-light基础上发展起来的
: 但是在解二次规划的方法上,没有完全沿用svm-light的方法。
: 我做了些简单的实验,发现普遍来说,svm-light比libsvm快,而且效果
: 好一些。不知道有没有大侠对他们有研究,比较一些如何?
: 不过,libsvm很容易使用,很容易被集成在自己的cpp工程中,svm-light
: 似乎很麻烦吧,呵呵。
: 期待大家的回复。。。。。。


--
主楼不关门,是我永远的梦想
实验室不断电,是我最大的愿望
每天早上帮我按一下Power,是我唯一的请求

有没有办法来电自动开机呢?如果知道请给我写信,谢谢!


※ 修改:・CnF 于 May 12 01:08:20 修改本文・[FROM: 166.111.151.78]
※ 来源:・BBS 水木清华站 smth.org・[FROM: 166.111.151.78]
发表者 Tintin 以 03:57

Perl Programming Tutorial: Data Structures

Perl Programming Tutorial: Data Structures

Data Structures: Scalars, Arrays, Hashes

In this section, we'll discuss the basic data structures available in Perl. Make sure you practice some of the examples discussed here!
Data Structures :: Scalars

A scalar is a number or a string. You can apply the usual manipulations on numbers, +, -, *, /, %, but Perl also has an exponentional operator. So how would you write 2 cubed?
2**3
Powerful? Yes.
What about string operations? String concatenation for example:
"hello" . "world"
The above would result in a single word, "helloworld". You can string multiple concatenations into one operation.
There is a string repetition operator: x. For example:
"w00t" x 3
would yield "w00tw00tw00t".
The standard logical operators are present and can be used on strings too! The following table (Schwartz 37) illustrates the Logical operators on scalars:
Comparison Numeric String
Equal == eq
Not Equal != ne
Less Than < lt
Greater Than > gt
Less Than or Equal To <= le
Greater Than or Equal To >= ge
Other operators include ++, --, !, &&, ||, ?:, *= += -=, ->, \. See Schwartz pgs. 38-39.
One of the powerhouses of Perl is the automatic type conversion between numbers and strings. It technically isn't even a type conversion because numbers and strings are both scalars.
(4**2 + 3 / 2) . " is the result of the expression 4^2 + 3/2"
This would result in a string "17.5 is the result of the expression 4^2 + 3/2".
So how do we store these scalars into actual variables we can use? Simple:
$result = (4**2 + 3 / 2) . " is the result of the expression 4^2 + 3/2";
Now the string is stored in the variable result.
You can do many cool things with variables in Perl, for example:
($x, $y) = ($y, $x);
swaps variables x and y. A far cry from C...
To remove trailing newlines from strings, you can use either chop or chomp. chop always removes the last character from the string, while chomp only removes newlines. So be safe and use chomp to remove newlines from input (more on input later).
Data Structures :: Arrays

An array variable is signified by the @ character.
A list literal is defined by parentheses and separated by commas:
@arr_1 = (1, 2, 3);
@str_arr = ("hello", "cruel", "world");
@arr_42 = qw(the meaning of life doesn\'t exist);
@arr_gen = (0 .. 5);
str_arr is an array of strings. What is arr_42? It is the shorthand method of writing a list of strings using the qw or quote word function. arr_gen is the same as the list (0, 1, 2, 3, 4, 5).
What about adding into an array or deleting from an array?
@arr_gen = (-1, @arr_gen, 6); # adds -1 to the front, 6 to the back of list
($a, @arr_gen) = @arr_gen; # removes -1 from @arr_gen to $a
$length = @arr_gen; # length is 7
($first) = @arr_gen;
These aren't the only ways to add or remove from a list (see below). What does the fourth statement do? Whenever you set an array to a scalar, Perl automatically takes the length of the array and sets that value to the scalar. The last statement gets the first element of arr_gen or 0. But how do we access different elements in the array?
Element access in arrays are much like any other programming language:
$arr_gen[3] = 42;
@arr_gen[0,1] = (10, 11);
In the first line, we access the fourth element in the array and change the value to 42. In the second line, we change the first two elements in the array to 10 and 11 by slicing. You can easily reverse lists using slicing also (see Schwartz pg. 53), but there is an even easier method below for list reversals.
Another powerful feature of arrays in Perl is negative indexing:
@arr_gen = (0 .. 5);
$a = $arr_gen[-2]; # $a gets assigned 4
$last = $#arr_gen; # last == 4
What does the last statement do? It gives last the last index value of the array (not the length).
So how do we add/remove from lists with ease? Simple, treat them like stacks or queues:
@arr = (1 .. 3);
$new_rvalue = 4;
$new_lvalue = 0;
push(@arr, $new_rvalue); # @arr == (1, 2, 3, 4)
unshift(@arr, $new_lvalue); # @arr == (0, 1, 2, 3, 4)
$x = pop(@arr); # $x == 4, @arr == (0, 1, 2, 3)
$y = shift(@arr); # $y == 0, @arr == (1, 2, 3)
Instant stacks and queues. Nice!
How about reversing a list? Simply call the reverse function:
@rev_a = reverse(@a);
Simple enough... how about sorting a list?
@mylist = (1, 2, 4, 0, 32, 22, 17, 53, 42);
@sorted = sort(@mylist);
@sorted is 0, 1, 17, 2, 22, 32, 4, 42, 53. Wait! That isn't sorted... well technically it is. The sort function performs an ASCII sort, not a numeric sort. More on sorting numerically later.
Data Structures :: Hashes

A hash is a data structure that holds scalars, but is indexed by a key value or another scalar.
Hash variables are declared with %. Elements in the hash are referenced by $key. For example:
$myhash{"key1"} = "555-111-29391-secret-key!"
$myhash{"key2"} = "333-123-33904-secret-key!"
$key = "key2";
print "$myhash{$key}"; # Prints the value in the hash of key2
There are some useful hash functions:
keys - lists all current keys in the hash (order doesn't matter. Why? So a useful way to use the keys function call is to loop through each key in the hash perhaps:
foreach $key (keys (%myhash)) {
print "$myhash{$key}\n";
}
This would loop through the %myhash hash and print each key. More on foreach later...
values - returns a list of all values in the hash.
each - each works much like keys does, but returns a list of both the key and the hash value.
delete - deletes a value out of the hash:
delete $myhash{"key1"}; # Deletes the key key1 and it's value
Hashes can be sliced also! For example:
@keys = qw(key3 key4 key5);
@myhash{@keys} = ("665-345-09284-secret-key!", "958-544-94950-secret-key!",
"448-39403-secret-key!");
@myhash{@keys} is the same as @myhash{"key3", "key4", "key5"} = ("665-345-09284-secret-key!", "958-544-94950-secret-key!", "448-39403-secret-key!");
Data Structures Review

Scalars are just numbers or strings. It's a fundamentally supported data type in Perl!
Arrays are collections of scalars indexed by integers much like other programming languages, but Perl has powerful extras added in.
Hashes are like arrays, but with scalar indexes.
There are other data structures, custom records and self-referential types.

Wednesday, November 17, 2010

NCE4-L41 Training elephants

Lesson 41 Training elephants

Two main techniques have been used for training elephants, which we may call respectively the tough and the gentle. The former method simply consists of setting an elephant to work and beating him until he does what is expected of him. Apart from any moral considerations this is a stupid method of training, for it produces a resentful animal who at a later stage may well turn man-killer. The gentle method requires more patience in the early stages, but produces a cheerful, good-tempered elephant who will give many years of loyal service.

The first essential in elephant training is to assign to the animal a single mahout who will be entirely responsible for the job. Elephants like to have one master just as dogs do, and are capable of a considerable degree of personal affection. There are even stories of half-trained elephant calves who have refused to feed and pined to death when by some unavoidable circumstance they have been deprived of their own trainer. Such extreme cases must probably be taken with a grain of salt, but they do underline the general principle that the relationship between elephant and mahout is the key to successful training.

The most economical age to capture an elephant for training is between fifteen and twenty years, for it is then almost ready to undertake heavy work and can begin to earn its keep straight away. But animals of this age do not easily become subservient to man, and a very firm hand must be employed in the early stages. The captive elephant, still roped to a tree,plunges and screams every time a man approaches, and for several days will probably refuse all food through anger and fear. Sometimes a tame elephant is tethered nearby to give the wild one confidence, and in most cases the captive gradually quietens down and begins to accept its food. The next stage is to get the elephant to the training establishment, a ticklish business which is achieved with the aid of two tame elephants roped to the captive on either side. When several elephants are being trained at one time it is customary for the new arrival to be placed between the stalls of two captives whose training is already well advanced. It is then left completely undisturbed with plenty of food and water so that it can absorb the atmosphere of its new home and see that nothing particularly alarming is happening to its companions. When it is eating normally its own training begins. The trainer stands in front of the elephant holding a long stick with a sharp metal point. Two assistants, mounted or tame elephants, control the captive from either side, while others rub their hands over his skin to the accompaniment of a monotonous and soothing chant. This if supposed to induce pleasurable sensations in the elephant, and its effects are reinforced by the use of endearing epithets, such as 'ho ! my son', or 'ho ! my father', or 'my mother', according to the age and sex of the captive. The elephant is not immediately susceptible to such blandishments, however, and usually lashes fiercely with its trunk in all directions. These movements are controlled by the trainer with the metal-pointed stick, and the trunk eventually becomes so sore that the elephant curls it up and seldom afterwards uses it for offensive purposes.

__LINE__ equivalent for Linux shell: $LINENO

The $LINENO variable returns the line in which that variable is used.


Perl Linux
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__FILE__ $0
__LINE__ $LINENO

Tuesday, November 16, 2010

LingPipe: Language Identification Tutorial

LingPipe: Language Identification Tutorial: "ing language identification from a pre-built model. This can be carried out from the co"

Good Internet resources for Speech Processing

Course:


http://www.is.cs.cmu.edu/11-751

The technology to allow humans to communicate with machines by speech and the technology to enable machines to understand when humans communicate with each other is rapidly maturing. This course provides an introduction to the theoretical background as well as the experimental practice that has made the field what it is today. We will cover theoretical foundations, essential algorithms, major approaches, experimental strategies and current state-of-the-art systems and will introduce the participants to ongoing work in representation, algorithms and interface design. The course will be completed by a brief overview of multilingual speech recognition dealing with various languages.

This course is primarily for graduate students in LTI, CS, Robotics, ECE, HCI, Psychology, or Computational Linguistics. Others by prior permission of instructor. No prior experience with speech recognition is necessary. The course is suitable for graduate students with some background in computer science and electrical engineering, as well as for advanced undergraduates.

The course involves written and programming assignments. Some reading of papers may also be required.

Monday, November 15, 2010

《数据结构》考试大纲

《数据结构》考试大纲

适用专业:计算机科学与技术、计算机软件工程
数据结构课程是一门实践性强的课程,需要进行大量的练习,数据结构课程的习题类型一般分为三类:一类是概念题,常见的形式包括是非判断题、简答题、选择题(单选或多选)与填空题几种;另一类是算法题,包括算法设计与算法填空两种形式;还有一类介于这两类题型之间,称为综合题或者问题求解题,这类题概念性一般不强,也不是写算法,可能是一种方法的具体应用,希望在复习中,多做一些相关的习题。

一、考试内容
1.数据结构的基本概念和术语
2.线性表
应掌握有关线性表基本概念,了解线性表基本操作有哪些;还要掌握线性表顺序存储结构与链式存储结构的构造原理和特点,在这两种存储结构上对线性表实施的一系列操作所对应的算法设计原理和方法,如线性链表、循环链表与双向链表的插入、删除算法的设计等。
3.数组与广义表
在程序设计语言中,通常将数组定义为具有相同类型的数组元素的集合,数组的基本操作有存、取、修改、查找和排序等。掌握常用操作的算法设计。本章的目的是介绍多维数组的逻辑结构特征及其存储方式,特殊矩阵和稀疏矩阵的压缩存储方法及广义表的概念,要求熟悉这些内容。本章重点是熟悉多维数组的存储方式、矩阵的压缩存储方式、广义表的定义及其表头表尾的运算,难点是稀疏矩阵的压缩存储表示下转置运算。
4.堆栈与队列
堆栈与队列是计算机领域非常重要的数据结构,从逻辑上看,堆栈与队列都是线性结构,掌握堆栈与队列的基本概念、常用操作的算法设计等。

5.串
本章的目的是介绍串的逻辑结构、存储结构及其串上的基本运算。本章重点是掌握串的基本概念和三种表示方法,这也是难点。

6.树与二叉树
了解树型结构的基本概念,掌握其名词术语,如:结点的度、树的度、叶结点、分支结点、树的层次、树的深度、树林、树的有序性等。掌握二叉树的定义、类型、性质;二叉树的存储结构、二叉树的遍历;二叉排序树的定义、建立、删除、查找等。了解Huffman树的概念。
7.图
图是非线性结构中比树结构还要复杂的结构,掌握图的定义、名词术语,如:顶点的度、路径、子图、图的连通、生成树与最小生成树、拓扑排序等;掌握图的存储结构、基本操作并了解图的其一些算法的设计。
8.查找
查找是顺序表和链表的基本应用,应理解查找的基本概念,熟练掌握顺序表查找的基本方法(顺序查找、二分查找),掌握静态索引结构以及查找、构造的基本算法。,理解散列的概念,了解散列函数的构造、解决冲突的方法。重点是熟练掌握顺序表查找的算法并理解静态/动态索引结构的特点。
9.内排序
排序是一种十分基本和重要的操作,了解排序的基本概念,掌握各种内排序方法,会设计内排序的算法。重点掌握插入排序(直接插入排序)、选择排序(直接选择排序、堆排序)、交换排序(气泡排序、快速排序)、归并排序等典型的排序算法及性能分析。

二、考试题型(分值,按100分计)
1、 选择题(单选)(8分)
2、 填空题(30分)
3、 运算题(30分)
3、 程序分析题(8分)
4、 算法设计题(24分)

三、参考书
[1] 《 数据结构(C语言版)》, 严蔚敏主编, 清华大学出版社
[2] 《数据结构题集(C语言版)》, 严蔚敏,吴伟民编著,清华大学出版社
四、考试时间:120分钟


==========

清华计算机专业课考研复习高效攻略

清华计算机专业课暑期复习高效攻略每年都有很多超自信的同学雄赳赳气昂昂的冲刺清华的计算机专业,同样每年也都有很多同学挥泪洒别清华计算机专业的考场。清华计算机专业排名全国第一,又是中国数一数二的名校,其角逐的激烈程度可想而知,专业课的考察的难度也是众所周知。如何在如此激烈的竞争中杀出一条血路金榜题名于2011,优化专业课备考的各个环节事半功倍的复习是关键。专业课教研室对同学们如何在暑期高效备考提供以下建议,供大家参考。复习总体指导思想谈到暑期的复习计划,由于各人的基础和学习背景不同,无法做一个统一的安排,但会有一个总体的指导思想。大家在暑期阶段要看完《数据结构(面向对象方法与C++描述)》、《计算机组成与设计》、《计算机系统结构》、《操作系统概念》这四本书。这一遍不用太细,但要知道大体内容的位置,翻书的时候知道到何处去查找。另外看这四本书的时候可以结合《数据结构习题解析》做一些题目。这里面的题目质量都很好,而且老师喜欢在里面出题,毕竟这是清华老师自己写的书。专业参考书目解析

01 《数据结构(面向对象方法与C++描述)》(第二版) 殷人昆等 清华大学出版社

02 《数据结构习题解析》 殷人昆等 清华大学出版社

03 《计算机组成与设计》(第二版) 王诚、刘卫东、宋佳兴 清华大学出版社

04 《计算机系统结构》(第二版) 郑纬民,汤志忠 清华大学出版社

05 《操作系统-精髓与设计原理》(第五版) William Stallings,陈渝译 电子工业出版

社(2006年2月)

06 《操作系统概念》(第六版) 郑扣根 译 高等教育出版社

这几本书都要买,都要看,没有轻重主次之分。除了这些书之外,还要给大家强烈推荐一本书。《计算机专业研究生入学考试全真题解》,共分5册,分别是:数据结构与程序设计分册。离散数学分册。操作系统分册。编译原理分册。硬件分册(包括数字逻辑、计算机组成原理、计算机系统结构)。这5册内容基本覆盖了计算机专业研究生入学考试涉及的7大部分。书中对知识点和考点之间的关系进行了深入挖掘,对典型例题进行了深入剖析,以求达到举一反三的目的。本书为硬件分册,包括如下几部分内容:试题分析和解题方法。这部分体现了全书的指导思想。主要内容概述。常考知识点及复习方法建议。真题详细解析。这部分是本书重点,汇集了近年来全国20余所著名院校计算机专业研究生入学考试的试题,对其进行了细致、深入的分析、解答和扩展。本书适合报考计算机专业研究生的考生有针对性地进行专业课的复习,也适合希望深入学习计算机专业知识的高校学生作为辅导书参考。同时,本书还可以作为习题集使用。

Thursday, November 11, 2010

Try goto in linux

# script name: try1.sh
# usage: tcsh try1.sh

# output:
#Try goto in linux
#This is Line 3
#This is Line 7

#!/bin/bash
echo "Try goto in linux"
echo "This is Line 3"
goto START
echo "This is Line 5"
START:
echo "This is Line 7"

Howto: Linux Rename Multiple Files At a Shell Prompt

Linux批量重命名文件会涉及到改变一个字母、改变一些相连字母、改变某些位置的字母、在最前面加上某些字母、或者改变字母的大小写。完成这里五个方法基本上就会解决了Linux批量重命名的工作。

1、我想把它们的名字的第一个1个字母变为"q",其它的不变

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo $i | sed 's/^./q/'`; done

或者写个脚本,显得更加清晰:

for file in `ls`
do
newfile =`echo $i | sed 's/^./q/'`
 mv $file $newfile
done


2、修改前面5个字母为zhaozh

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo $i | sed 's/^...../zhaozh/'`; done

3、修改后面5个字母为snail

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo $i | sed 's/.....$/snail/'`; done

4、在前面添加 _hoho_

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo "_hoho_"$i`; done

5、所有的小写字母变大写字母

[root@pps mailqueue]# for i in `ls`; do mv -f $i `echo $i | tr a-z A-Z`; done

上面是五中完成有关Linux批量重命名方法。



====


Howto: Linux Rename Multiple Files At a Shell Prompt


How do I rename multiple files at a shell prompt under Linux or UNIX operating systems?

Renaming multiple files at a shell prompt is always considered as a black art by many UNIX gurus.

To be frank if you understand regex then it is not a black art anymore. A regular expression is a string that describes or matches a set of strings, according to certain syntax rules (see regex @ wikipedia for more information). Linux (and *BSD) comes with handy utility called rename. As a name suggest 'rename' renames the filenames supplied according to the rule specified (syntax):

rename "regex-rule" files
Rename command syntax

rename oldname newname *.files
For example rename all *.bak file as *.txt, enter:
$ rename .bak .txt *.bak

Examples: Linux Rename Multiple Files

Convert all mp3 filenames to more readable and usable format. Most of the time MP3 got multiple blank spaces, which may confuse many command line based Linux utilities and mp3 players

$ ls
Output:

06 - Gorillaz - Feel Good Inc.mp3
DDR - Kung- Fu Fighting (bus stop).mp3
AXEL CRAZYFROG.mp3
Remove all blank space with rename command:
$ rename "s/ *//g" *.mp3
$ ls

Output:

06-Gorillaz-FeelGoodInc.mp3
DDR-Kung-FuFighting(busstop).mp3
AXEL-CRAZYFROG.mp3
Linux Shell script to rename files

Before using the rename command I was using the following shell script to rename my mp3s:

#!/bin/bash
# To remove blank space
if [ $# -eq 0 ];
then
echo "Syntax: $(basename $0) file-name [command]"
exit 1
fi
FILES=$1
CMD=$2
for i in $FILES
do
# remove all blanks and store them OUT
OUT=$(echo $i | sed 's/ *//g')
if [ "$CMD" == "" ];
then
#just show file
echo $OUT
else
#else execute command such as mv or cp or rm
[ "$i" != "$OUT" ] && $($CMD "$i" "$OUT")
fi
done
To remove .jpg file extension, you write command as follows:

$ rename 's/\.jpg$//' *.jpg

To convert all uppercase filenames to lowercase:

$ rename 'y/A-Z/a-z/' *

Read the man page of rename command for more information:
man rename

Wednesday, November 10, 2010

C Programming - Use of the ftime() Function

C Programming - Use of the ftime() Function

[C Language] Use of the ftime() Function

Use of the ftime() Function



Program FTIME.C illustrates how to continually fetch the time of the system clock so as perform a task for a specified period of time. In this simple example, a dot is printed for 5000 ms. Struct timeb consists of, among other things, a long integer, "time" which is the number of seconds since Jan 1, 70 and a short integer, "millitm", which is the fractional number of milliseconds.

At the beginning of the task, line 9, the start time is fetched. The task is then performed, in this case, the simple printing of a dot and the current time is fetched off the system clock in line 14. This is repeated until the current time is 5000 ms larger than the start time.

The advantage of this approach over using the TurboC delay function is that while executing the delay function, nothing else is being done. Thus, although the delay function has its place, it is unusable in many applications, where something dynamic must be done for a specified period of time.

/*
** Program FTIME.C
**
** Illustrates the use of ftime function to perform a task for a period
** of time. Prints dots for 5000 msecs.
**
** H. Paul Roach, MSU, 5 August, '96
*/

#include /* 1 */
#include /* 2 */
#include /* 3 */
/* 4 */
void main(void) /* 5 */
{ /* 6 */
struct timeb t_start, t_current; /* 7 */
int t_diff; /* 8 */
ftime(&t_start); /* 9 */
do /* 10 */
{ /* 11 */
printf("."); /* 12 */
ftime(&t_current); /* 13 */
t_diff = (int) (1000.0 * (t_current.time - t_start.time)/* 14 */
+ (t_current.millitm - t_start.millitm)); /* 15 */
} /* 16 */
while(t_diff < 5000); /* 17 */
} /* 18 */

[C Language] exit function

// algo1-4.cpp 说明exit()函数作用的程序
#include"c1.h"
int a(int i)
{
if(i==1)
{
printf("退出程序的运行\n");
exit(1);
}
return i;
}
void main()
{
int i;
printf("请输入i:");
scanf("%d",&i);
printf("a(i)=%d\n",a(i));
}

当输入为1 时,执行exit()语句,退出程序的运行,不执行主程序的printf()语句;而
当输入为2 时,不执行exit()语句,返回主程序后,执行printf()语句

Handling Binary Files in Perl

http://www.tutorialspoint.com/perl/perl_read.htm


Syntax

read FILEHANDLE, SCALAR, LENGTH, OFFSET

read FILEHANDLE, SCALAR, LENGTH


Definition and Usage

Reads, or attempts to read, LENGTH number of bytes from the file associated with FILEHANDLE into BUFFER. If an offset is specified, the bytes that are read are placed into the buffer starting at the specified offset.

Return Value

  • The number of bytes read or the undefined value.

Example

Try out following example:

#!/usr/bin/perl -w

my($buffer) = "";
open(FILE, "/etc/services") or
die("Error reading file, stopped");
while(read(FILE, $buffer, 100) )
{
print("$buffer\n");
}
close(FILE);

It will produce following result. This is just sanpshot of the result

kerberos_master 751/udp  # Kerberos authentication
kerberos_master 751/tcp # Kerberos authenti
cation


passwd_server 752/udp # Kerberos passwd server


Handling Binary Files in Perl
For some reason, there exists a common misconception that there is no cross-platform, built-in way in Perl to handle binary files. The copy_file code snippet below illustrates that Perl handles such tasks quite well. The trick is to use "binmode" on both the input and output files after opening them. "Binmode" switches files to binary mode, which for the input file means it won't stop reading at the first "end of text file" character (^Z in win/dos); for the output file binmode means it won't translate '\n' (LF) into '\r\n' (CRLF) when printing. In this way the files get copied byte for byte.

sub copy_file {
my ($srcfile, $destfile) = @_;
my $buffer;

open INF, $srcfile
or die "\nCan't open $srcfile for reading: $!\n";
open OUTF, ">$destfile"
or die "\nCan't open $destfile for writing: $!\n";

binmode INF;
binmode OUTF;

while (
read (INF, $buffer, 65536) # read in (up to) 64k chunks, write
and print OUTF $buffer # exit if read or write fails
) {};
die "Problem copying: $!\n" if $!;

close OUTF
or die "Can't close $destfile: $!\n";
close INF
or die "Can't close $srcfile: $!\n";
}



How to solve: error C2065: 'cout' : undeclared identifier

Solution:

#include   using namespace std; 

Development for Beginners | C++ Beginner's Guide | MSDN

Development for Beginners | C++ Beginner's Guide | MSDN

How to compile a C program on Visual Studio 2010

Walkthrough: Compiling a C Program on Visual Studio 2010



Visual C++ 2010 includes a C compiler that you can use to create everything from basic C programs to Windows API applications.

This walkthrough shows how to create a basic C program by using a text editor, and then compile it on the command line.

You can use your own C programs instead of typing the sample programs shown in this walkthrough. You can also use any C code sample programs that are included in the Help topics.

By default, the Visual C++ compiler treats all files that end in .c as C source code, and all files that end in .cpp as C++ source code. To force the compiler to treat all files as C regardless of file name extension, use the /Tc compiler option.

Prerequisites

You must understand the fundamentals of the C++ language. If you are just getting started learning C++, we recommend the C++ Beginner's Guide by Herb Schildt, which is available on the MSDN Web site.

To create a C source file and compile it on the command line

  1. Click Start, point to All Programs, Microsoft Visual Studio 2010, and Visual Studio Tools, and then click Visual Studio 2010 Command Prompt.

    Depending on the version of Windows on the computer and the system security configuration, you might have to right-click Visual Studio 2008 Command Prompt and then click Run as Administrator to successfully run the application that you create by following these steps.

    NoteNote

    The Visual Studio 2010 Command Prompt automatically sets the correct path of the C compiler and any required libraries. Use it instead of the regular Command Prompt window. For more information, see Setting the Path and Environment Variables for Command-Line Builds.

  2. At the command prompt, type notepad simple.c and press ENTER.

    Click Yes when you are prompted to create a file.

  3. In Notepad, type the following lines.

    #include   int main() {     printf("This is a native C program.\n");     return 0; } 
  4. On the File menu, click Save to create a C source file.

  5. Close Notepad.

  6. At the command prompt, type cl simple.c and press ENTER.

    The cl.exe compiler generates an executable program, Simple.exe.

    You can see the executable program name in the lines of output information that the compiler displays.

    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00 for 80x86 Copyright (C) Microsoft Corporation.  All rights reserved.  simple.c Microsoft (R) Incremental Linker Version 10.00 Copyright (C) Microsoft Corporation.  All rights reserved.  /out:simple.exe simple.obj 
  7. To see a list of all files in the \simple\ directory, type dir simple.* and press ENTER.

    The .obj file is an intermediate format file that you can safely ignore.

  8. To run Simple.exe, type simple and press ENTER.

    The program displays this text and exits:

    This is a native C program.

  9. To close the Command Prompt window, type exit and press ENTER.

Essential DOS Commands and Concepts

http://www.lsi.upc.edu/~robert/teaching/foninf/doshelp.html#dir

Quick Example Tutorial:
cd /d \TargetDir
ren OldName NewName

Essential DOS Commands and Concepts

Introduction

DOS (an acronym for Disk Operation System) is a tool which allows you to control the operation of the IBM PC. DOS is software which was written to control hardware. IDRISI, Atlas*GIS, Microstation, AutoCAD, CPS/PC, and ARC/INFO are, in turn, application software which run under DOS. By this we mean that, although IDRISI, Atlas*GIS, Microstation, AutoCAD, CPS/PC, and ARC/INFO were written to accomplish a single task or application (in this case manipulation of spatially related data), they must use DOS to pursue its work.

DOS can be used for a wide range of tasks far beyond the requirements of this class. You will be able to manage well if you master only a small subset of DOS commands and functions. These relate almost exclusively to file and directory management and are introduced in this handout.

This tip sheet assumes that you have learned how to turn on the PCs as they are configured in room 230 and that you have familiarized yourself with their keyboards (no small task in itself). It also assumes that you understand the meaning of the concept of a file and the elements of a file specification (drive, filename, and extension). The microcomputers you will be using are equipped with two floppy disk drives. The A-drive is the 3.5" (1.44MB) drive and the B-drive is the 5.25" (360KB) drive. The microcomputers also contain a C-drive, a hard disk drive of 130MB or 200MB capacity.

You will quickly find that the best way to learn how to use a computer is through experimentation. That is, once you have learned a command, try some variations until they don't work, then start over. Often there are five or six ways for you to accomplish a particular task. Usually, I will introduce you to only one, leaving it up to you to discover the rest. Don't hesitate to consult the DOS Reference Manual; copies can be found on the bookcase in room 230. Finally, don't be unduly disturbed by error messages. With computers, one of the best ways to learn is by making mistakes.

Most of the common DOS commands you need to use for this class (copy, rename, delete) are available to you in Windows through the Filemanager icon. And, since you can move back and forth between DOS and Windows, it doesn't matter which option you employ. Some commands are faster in invoke in Windows, some in DOS. If you haven't worked with Windows previously, go to the Windows tutorials in the help area.

Backup Files

It is possible to lose files by mistake, although the more you practice the less likely it becomes. For your own peace of mind, it is good practice to make backup copies of your most valuable files on a separate diskette. Store your backup disk in a safe place and don't carry it through a metal detector. Use the COPY command to create the backup.

There is no need to backup every file you create, only the ones in which you've invested much work. Also, prune your backup diskette every week or two using the ERASE command. Backup files which have been made redundant by subsequent additions will simply create clutter on your backup diskette. An effective file naming convention is essential to keeping track of your backups.

Change the Default Drive

To change the default drive, simply type the letter of the your choice. The new default will be listed in subsequent DOS prompts.

Example:

  • C> A: [enter]
  • Changes the default drive from C to A.
  • A> C: [enter]
  • Changes the default drive from A to C.
[enter] means that you must press the Enter Key before the format command will execute. [Enter] is required after any DOS command, it is assumed in all commands found below.

CHDIR (CD) Change Directory Command

Once you have located the directory you want, you may move from directory to directory using the CD command (change directory)

Example:

  • C> cd furniture
  • Moves you to the directory called 'FURNITURE'
  • C> cd \furniture\chairs
  • Moves you to the directory called 'CHAIRS' under the directory called 'FURNITURE'.
  • C> cd ..
  • Moves you up one level in the path.
  • C> cd \
  • Takes you back to the root directory (c: in this case).

COPY Command

The COPY command can be used both to copy files from disk to disk or to create a second copy of a file on a single disk. (There are many more uses of the COPY command, but only the basic operation is discussed here.)

Example:

  • C> copy c:kermit.exe a:
  • Copies the file 'KERMIT.EXE' from the C drive to the A drive and gives it the same name.
  • C> copy a:brazil1.dat b:\south\brazil2.dat
  • Creates a copy of 'BRAZIL1.DAT' from drive A on drive B, putting it in the 'SOUTH' subdirectory and renaming it 'BRAZIL2.DAT'.
The key to use this command correctly is to remember that the first file specified after the COPY command is the source file, the second is the target:ehp1 file. The source is the file to be copied. The targetwill be the location and name of the new file. If the file name and extension are omitted after the target's drive specification, the new file will have exactly the same name as the source file.

Example:

  • C> copy a:myfile.txt b:
  • C> copy c:command.com b:com.com
  • C> copy b:golly.gee a:whao.boy
  • C> copy command.* a:
  • C> copy a:mymap.dwg c:\maps
Note: it is always good practice to us the complete file specifications for both source and target files, Be very sure of yourself before you accept defaults or employ wild-card characters. Otherwise you may end up with some interesting results. Incomplete or incorrect source names may result in errors, such as the command: copy edlin a:myomy.bat. Try it and see what happens.

DIR (Directory) Command

The DIRECTORY command lists the names and sizes of all files located on a particular disk.

Example:

  • C> dir a:
  • Shows directory of drive A
  • C> dir b:
  • Shows directory of drive B
  • C> dir \agis
  • Shows files in a subdirectory on drive C (default)
  • C> dir
  • Shows directory of drive C
  • C> dir /w
  • Shows directory in wide format, as opposed to a vertical listing.
All the files are listed at the screen, you can stop the display by typing CTRL-BREAK. If you ask for a directory on the A or B drives, be sure there is a diskette in the drive and that the diskette has been formatted. If the drive is empty, or if the diskette is unformatted, the DOS will respond with an error message.

DIR Options

Two little characters, '*' and '?', will make your life with computers much easier. Their use is illustrated below.

Example:

  • C> dir a:*.ex
  • Lists all files on the A drive with an extension of 'EXE'.
  • C> dir b:kermit.*
  • Lists all files on the B drive with a filename of 'KERMIT'.
The asterisk is a wild-card character which allows the user to enter only a limited part of a file specification to find a file. It is useful when you wish to locate a group of files with the same filename or the same extension. On other occasions you may have forgotten part of a file specification. You can use '*' in place of the parts of the specification you have forgotten. Similarly, '?' permits wild-card searches keyed to single characters.

Example:

  • C> dir a:labe?.com
  • Lists all five-letter files with the first four letters 'LABE' and an extension of 'COM'.
  • C> dir b:format.c??
  • Lists all files with a filename of 'FORMAT' and an extension beginning with 'C'.
Wild-card characters can be used in combination.

Example:

  • C> dir a:labe?.*
  • Lists all five-letter files with the first four letters 'LABE' and any extension.
  • C> dir c:*.ex?
  • Lists all files with an extension beginning with 'EX'.
Experiment with '*' and '?' to improve your ability to find files quickly. These wild-card characters can also be used with several other DOS commands.

ERASE Command

The ERASE command deletes specified files.

Example:

  • C> erase a:myfile.txt
  • Erases the file MYFILE.TXT from the diskette in the A drive. If no drive specification is entered, the system looks to delete the specified file form drive C (in this case).
IMPORTANT WARNING: This command is easy to use, but it is the most dangerous one you will encounter in DOS (apart form FORMAT). If you aren't careful, you may delete a file which you--or someone else--needs. And, unless you have saved a backup of that file, the erased file is gone for good. For this reason it is good practice to use only complete file specifications with the ERASE command (and to keep backups of your most valuable files). As a safety precaution, never use the wild-card characters '*' and '?' in ERASE commands.

BEWARE: I will rescind your laboratory privileges for a full week if you ever knowingly use either the command: erase c:*.*, or the command: erase *.*. Guess what happens?

File-Naming Conventions

Careful file naming can save time. Always choose names which provide a clue to the file's contents. If you are working with a series of related files, use a number somewhere in the name to indicate which version you have created. This applies only to the filename parameter; most of the file extension parameters you will be using are predetermined (or reserved by DOS for certain types of file).

Example:

  • WORLD.DAT
  • An ATLAS*GRAPHICS file containing data for a world map. The DAT extension is required by ATLAS*GRAPHICS.
  • BRAZIL.BNB
  • A boundary file of Brazil in binary form.
  • BRIT1.DAT
  • BRIT2.DAT
  • BRIT3.DAT
  • Three versions of a data file for a map of Britain.

FORMAT Command

You must format new disks before using them on the IBM computers. The format command checks a diskette for flaws and creates a directory where all the names of the diskette's files will be stored.

Example:

  • C> format a:
  • Formats the diskette in the A drive.
  • C> format b:
After entering this command, follow the instructions on the screen. When the FORMAT operation is complete, the system will ask if you wish to FORMAT more diskettes. If you are working with only one diskette, answer N (No) and carry on with you work. If you wish to FORMAT several diskettes, answer Y (Yes) until you have finished formatting all your diskettes.

BEWARE: Executing the format command with a diskette which already contains files will result in the deletion of all the contents of the entire disk. It is best to execute the format command only on new diskettes. If you format an old diskette make sure it contains nothing you wish to save.

MKDIR (MD) Make Directory Command

This command creates a new directory.

Example:

  • C> mkdir mine
  • Creates a directory called 'MINE'

Rebooting the computer (Ctrl-Alt-Del)

In some cases, when all attempts to recover from a barrage of error messages fails, as a last resort you can reboot the computer. To do this, you press, all at once, the control, alternate and delete.

BEWARE: If you re-boot, you may loose some of your work--any data active in RAM which has not yet been saved to disk.

RENAME (REN) Command

The RENAME command permits users to change the name of a file without making a copy of it.

Example:

  • C> ren a:goofy.txt pluto.txt
  • Changes the name of 'GOOFY.TXT' on the A drive to 'PLUTO.TXT'.
This command is very simple to use, just remember two points: the file name and extension must be complete for the source file and no drive specification is given for the target. Renaming can only occur on a single disk drive (otherwise COPY must be used).

RMDIR (RD) Remove Directory Command

This command removes a directory. It is only possible to execute this command if the directory you wish to remove is empty.

Example:

  • C> rd mine
  • Removes directory called 'MINE'.

Stop Execution (Ctrl-Break)

If you wish to stop the computer in the midst of executing the current command, you may use the key sequence Ctrl-Break. Ctrl-Break does not always work with non-DOS commands. Some software packages block its action in certain situations, but it is worth trying before you re-boot.




Converted 20 July 1994. KEF.