Wednesday, 13 August 2014

R cannot be resolved to a variable

Android开发过程中,碰到R cannot be resolved to a variable的报错信息,好像没有很确定的错误原因,一般来说,总结出几个可能的解决方法,希望试过以后管用。。。

1. 检查Android 的SDK是否丢失需要重新下载,检查build path
2.确保class没有import Android.R;
3,错误class引用的layout的xml文件没有错误
4.检查AndroidManifest.xml文件,里边的package,layout配置文件,strings.xml等的字符串全部书写正确
5.layout的xml文件中引用的strings.xml中的字符串拼写完全正确
6.在layout 的xml文件手写添加一个控件,看id能否在R.java中自动生成,如果不能,那很大可能就是这个layout 的xml文件有问题,查看格式是否使用正确,或者包含什么非法字符串,或者调用到了不正确的字符串,等等,可以使用排除法,挨个去掉控件,直到发现error message消失或者id能在R.java中自动生成。
7.删掉gen文件夹,使R.java重新自动生成一次,如果不能生成,继续检查layout的xml文件是否有如上不易发觉的问题
8.Clean project ,重新build,或者重新import project。
9.重启eclipse (restart eclipse)
10.重启电脑,解决Android 虚拟机的问题 (reboot the PC, maybe something wrong with the JAVA env )

Monday, 11 August 2014

error: cannot find -lsonivox



I copied libsonivox.so into /platforms/android-14/arch-arm/usr/lib/, my android.mk file is:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := midi
LOCAL_SRC_FILES := midi.c
LOCAL_LDLIBS    += -lsonivox
include $(BUILD_SHARED_LIBRARY)
but when I ran ndk-build I got this error:
.../ndk/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: error: cannot find -lsonivox

libsonivox.so can be loaded dynamically. You need to copy the .so from your android device and place it in $NDK-ROOT/platforms/android-14/arch-arm/usr/lib, "android-14" can be whatever version instead.

So I copied libsonivox.so to "android-18" and other "android-1X", and build it again, it worked!

Friday, 8 August 2014

Red exclamation mark eclipse android project

I saw a red exclamation mark today







Found some libraries are missing. So added them, solved this issue.














Thursday, 6 March 2014

error: stray ‘\302’ in program


Make and meet this error!

$ gcc -g -Wall -o test callback_simple.c
callback_simple.c:7:1: error: stray ‘\302’ in program
callback_simple.c:7:1: error: stray ‘\240’ in program
callback_simple.c:9:1: error: stray ‘\302’ in program
callback_simple.c:9:1: error: stray ‘\240’ in program
callback_simple.c: In function ‘sig_handler’:
callback_simple.c:13:5: error: stray ‘\302’ in program
callback_simple.c:13:5: error: stray ‘\240’ in program

\302 is the octal representation of the UTF-8 sequence 0xC2

You have invalid chars in the source. If you don't have any valid non ascii chars in your source, maybe in a double quoted string literal, you can simply convert your file back to ascii with the following command:
tr -cd '\11\12\15\40-\176' < old.c > new.c
It works!

Sunday, 19 January 2014

Address out of bounds 错误分析

遇到Address out of bounds 错误,原来是数组的大小超过了栈的大小!


栈大小是有限的

VC默认的分配给栈的空间是1MB~2MB,体积比较大的对象不适合在栈中分配.特别
要注意递归函数中最好不要使用栈对象,因为随着递归调用深度的增加,所需的栈
空间也会线性增加,当所需栈空间不够时,便会导致栈溢出,就会产生运行时错误.

如果真的需要的话,在数组定义前面加上static,将数组分配在静态内存中,静态内存相比起堆栈要大很多的.
或者直接把这个数组定义成全局的,这样也会将其分配在静态内存.

vc6/7 默认1M
不过这个可以修改的Project->Setting->Link,在Category   中选中Output,然后在Reserve中设定堆栈的最大值和commit   


看一下stack是否被限制,如果是unlimited,那么栈的大小只受内存大小限制,当然还有一个2G的上限。至于是否能达到2G上限,答案是否定的,因为除了栈,程序还有别的地方会用到内存。不过linux在某种方式下可以用到最高64G的内存,不知道栈是否也可以突破2G的限制?

Linux下也是可以修改的:
先用命令 ulimit -a 看看默认的stack size
user@ubuntu-64bit:~/mysql_study$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 15821
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 15821
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited

然后再用命令将其修改,这里,改大一点做测试。
user@ubuntu-64bit:~/mysql_study$ ulimit -s 9999999

改了后发现‘Address out of bounds’ 的错误消失, oh yeah.

用动态分配, malloc free 要好一些~~~~

Thursday, 16 January 2014

the vim cscope easy tutorial

The following steps to help you to set up cscope easily.

1. install cscope:
user@ubuntu-64bit:~$ sudo apt-get install cscope

2. Download the cscope_maps.vim file, put it to $HOME/.vim/plugin directory:
user@ubuntu-64bit:~$ mv Desktop/cscope_maps.vim .vim/plugin/  

3. Try setting the $CSCOPE_DB environment variable to point to a Cscope database you create:
    find /my/project/dir -name '*.c' -o -name '*.h' > /foo/cscope.files
   Then run Cscope in the same directory as the cscope.files file (or use 'cscope -i /foo/cscope.files'), then set and export the $CSCOPE_DB variable, pointing it to            the cscope.out file that results):
    cd /foo
    cscope -b 
    CSCOPE_DB=/foo/cscope.out; export CSCOPE_DB    


add the commands:
    " The following maps all invoke one of the following cscope search types:
    "
    " 's' symbol: find all references to the token under cursor
    " 'g' global: find global definition(s) of the token under cursor
    " 'c' calls: find all calls to the function name under cursor
    " 't' text: find all instances of the text under cursor
    " 'e' egrep: egrep search for the word under cursor
    " 'f' file: open the filename under cursor
    " 'i' includes: find files that include the filename under cursor
    " 'd' called: find functions that function under cursor calls


    " To do the first type of search, hit 'CTRL-\', followed by one of the
    " cscope search types above (s,g,c,t,e,f,i,d). 

MySQL C API programming tutorial 2nd

Multiple statements

It is possible to execute multiple SQL statements in one query. We must set the CLIENT_MULTI_STATEMENTS flag in the connect method.

if (mysql_real_connect(con, "localhost", "user12", "34klq*", 
        "testdb", 0, NULL, CLIENT_MULTI_STATEMENTS) == NULL) 
{
    finish_with_error(con);
}
The last option of the mysql_real_connect() method is the client flag. It is used to enable certain features. The CLIENT_MULTI_STATEMENTS enables the execution of multiple statements. This is disabled by default.
if (mysql_query(con, "SELECT Name FROM Cars WHERE Id=2;\
    SELECT Name FROM Cars WHERE Id=3;SELECT Name FROM Cars WHERE Id=6")) 
{
    finish_with_error(con);
}
The query consists of three SELECT statements. They are separated by the semicolon (;) character. The backslash character (\) is used to separate the string into two lines. It has nothing to do with multiple statements.
do {  
...    
} while(status == 0);
The code is placed between the do/while statements. The data retrieval is to be done in multiple cycles. We will retrieve data for each SELECT statement separately.
status = mysql_next_result(con); 
We expect multiple result sets. Therefore, we call the mysql_next_result() function. It reads the next statement result and returns a status to indicate whether more results exist. The function returns 0, if the execution went OK and there are more results. It returns -1, when it is executed OK and there are no more results. Finally, it returns value greater than zero, if an error occured.
if (status > 0) {
    finish_with_error(con);
}
We check for error.
$ ./multiple_statements 
Mercedes
Skoda
Citroen
Example output.

Inserting images into MySQL database

Some people prefer to put their images into the database, some prefer to keep them on the file system for their applications. Technical difficulties arise when we work with millions of images. Images are binary data. MySQL database has a special data type to store binary data calledBLOB (Binary Large Object).
mysql> CREATE TABLE Images(Id INT PRIMARY KEY, Data MEDIUMBLOB);
For our examples, we create a new Images table. The image size can be up to 16 MB. It is determined by the MEDIUMBLOB data type.

char chunk[2*size+1];
mysql_real_escape_string(con, chunk, data, size);
The mysql_real_escape_string() function adds an escape character, the backslash, \, before certain potentially dangerous characters in a string passed in to the function. This can help prevent SQL injection attacks. The new buffer must be at least 2*size+1 long.
char *st = "INSERT INTO Images(Id, Data) VALUES(1, '%s')";
size_t st_len = strlen(st);
Here we start building the SQL statement. We determine the size of the SQL string using thestrlen() function.
char query[st_len + 2*size+1]; 
int len = snprintf(query, st_len + 2*size+1, st, chunk);
The query must take be long enough to contain the size of the SQL string statement and the size of the image file. Using the snprintf() function, we write the formatted output to query buffer.
if (mysql_real_query(con, query, len))
{
    finish_with_error(con);
};
We execute the query using the mysql_real_query() function. The mysql_query() cannot be used for statements that contain binary data; we must use the mysql_real_query() instead.



It should support the size of the picture less than 16M.
there's an error when I am using a 5M picture.
Why I got the <Address out of bounds> error???????????

101 char chunk[2*size+1];
(gdb) p size
$1 = 5791109
(gdb) s
102 mysql_real_escape_string(con, chunk, data, size);
(gdb) p chunk
$2 = 0x7ffffef6c840 <Address 0x7ffffef6c840 out of bounds>
(gdb) p data
$3 = 0x7fffffa78360 "\377\330\377\341)\376Exif"
(gdb) p size
$4 = 5791109
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400f40 in main (argc=1, argv=0x7fffffffe288) at insert_images.c:102
102 mysql_real_escape_string(con, chunk, data, size);



Selecting images from MySQL database

In the previous example, we have inserted an image into the database. In the following example, we will select the inserted image back from the database.

if (mysql_query(con, "SELECT Data FROM Images WHERE Id=1"))
{
    finish_with_error(con);
}
We select the Data column from the Image table with Id 1.
MYSQL_ROW row = mysql_fetch_row(result);
The row contains raw data.
unsigned long *lengths = mysql_fetch_lengths(result);
We get the length of the image.
fwrite(row[0], lengths[0], 1, fp);

if (ferror(fp)) 
{            
    fprintf(stderr, "fwrite() failed\n");
    mysql_free_result(result);
    mysql_close(con);

    exit(1);      
}  
We write the retrieved data to the disk using the fwrite() function call. We check for the error indicator with the ferror() function.
int r = fclose(fp);

if (r == EOF) {
    fprintf(stderr, "cannot close file handler\n");
}
After we have written the image data, we close the file handler using the fclose() function.

MySQL C API programming tutorial

Request: need to study it.

pronunciation:
MySQL (/m ˌɛskjuːˈɛl/ "My S-Q-L",[4] officially, but also called /m ˈskwəl/ "My Sequel")

MySQL C API programming tutorial


看这篇文章,学习。
use 
$ sudo apt-get install libmysqlclient-dev
To be able to compile C examples, we need to install the MySQL C development libraries. The above line shows how we can do it on Debian based Linux.

First example

Our first example will test one MySQL function call.

编译错误,找不到头文件?原来是没有加编译选项(头文件路径)
user@ubuntu-64bit:~/mysql_study$ find / -name my_global.h 2>/dev/null
/usr/include/mysql/my_global.h
$ gcc version.c -o version  `mysql_config --cflags --libs`
user@ubuntu-64bit:~/mysql_study$ ./version 
MySQL client version: 5.5.34

Creating a database

The next code example will create a database. The code example can be divided into these parts:
  • Initiation of a connection handle structure
  • Creation of a connection
  • Execution of a query
  • Closing of the connection
我说为什么创建了的database看不到,原来需要指定user为root才能看见root创建的database.
user@ubuntu-64bit:~/mysql_study$ gcc createdb.c -o createdb -std=c99  `mysql_config --cflags --libs`

user@ubuntu-64bit:~/mysql_study$ mysql -u root -p -h localhost
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 56
Server version: 5.5.34-0ubuntu0.12.04.1 (Ubuntu)

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
| test22db           |
| testdb             |
+--------------------+
6 rows in set (0.04 sec)

Creating and populating a table

Before we create a new table, we create a user that we will use in the rest of the tutorial.
mysql> CREATE USER user12@localhost IDENTIFIED BY '34klq*';
We have created a new user user12.
mysql> GRANT ALL ON testdb.* to user12@localhost;
Here we grant all priviliges to user12 on testdb database.
The next code example will create a table and insert some data into it.

user@ubuntu-64bit:~/mysql_study$ gcc createtable.c -o createtable -std=c99 `mysql_config --cflags --libs`

mysql> USE testdb;
mysql> SHOW TABLES;
+------------------+
| Tables_in_testdb |
+------------------+
| Cars             |
+------------------+
1 row in set (0.00 sec)
We show tables in the database.
mysql> SELECT * FROM Cars;
+------+------------+--------+
| Id   | Name       | Price  |
+------+------------+--------+
|    1 | Audi       |  52642 |
|    2 | Mercedes   |  57127 |
|    3 | Skoda      |   9000 |
|    4 | Volvo      |  29000 |
|    5 | Bentley    | 350000 |
|    6 | Citroen    |  21000 |
|    7 | Hummer     |  41400 |
|    8 | Volkswagen |  21600 |
+------+------------+--------+
8 rows in set (0.00 sec)
We select all data from the table.

Retrieving data from the database

In the next example, we will retrieva data from a table.
Steps:
  • Create a connection
  • Execute query
  • Get the result set
  • Fetch all available rows
  • Free the result set
if (mysql_query(con, "SELECT * FROM Cars")) 
{
    finish_with_error(con);
}
We execute the query, that will retrieve all data from the Cars table.
MYSQL_RES *result = mysql_store_result(con);
We get the result set using the mysql_store_result() function. MYSQL_RES is a structure for holding a result set.
int num_fields = mysql_num_fields(result);
We get the number of fields (columns) in the table.
MYSQL_ROW row;

while ((row = mysql_fetch_row(result))) 
{ 
    for(int i = 0; i < num_fields; i++) 
    { 
        printf("%s ", row[i] ? row[i] : "NULL"); 
    } 
        printf("\n"); 
}
We fetch the rows and print them to the screen.

user@ubuntu-64bit:~/mysql_study$ gcc retrieve_data.c -o retrieve_data -std=c99 `mysql_config --cflags --libs`
user@ubuntu-64bit:~/mysql_study$ ./retrieve_data
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
6 Citroen 21000
7 Hummer 41400
8 Volkswagen 21600 

Last inserted row id

Sometimes, we need to determine the id of the last inserted row. We can determine the last inserted row id by calling the mysql_insert_id() function. The function only works if we have defined an AUTO_INCREMENT column in the table.

A new table is created. Three rows are inserted into the table. We determine the last inserted row id.
char *sql = "CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name TEXT)";
The Id column has an AUTO_INCREMENT type.
int id = mysql_insert_id(con);
The mysql_insert_id() function returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement.
$ ./last_row_id 
The last inserted row id is: 3

Column headers

In the next example, we will retrieve data from the table and its column names.
We print the first three rows from the Cars table. We also include the column headers.
MYSQL_FIELD *field;
The MYSQL_FIELD structure contains information about a field, such as the field's name, type and size. Field values are not part of this structure; they are contained in the MYSQL_ROW structure.
if (i == 0) 
{              
    while(field = mysql_fetch_field(result)) 
    {
        printf("%s ", field->name);
    }
    
    printf("\n");           
}
The first row contains the column headers. The mysql_fetch_field() call returns a MYSQL_FIELD structure. We get the column header names from this structure.
$ ./headers 
Id Name Price 
1  Audi  52642  
2  Mercedes  57127  
3  Skoda  9000 

Thursday, 2 January 2014

Failed to load session “ubuntu” problem


I could not login to my Ubuntu Desktop after having some new theme related packages installed on.

got this error message "Failed to load session"

google it, found it may be related with the compiz packages
uninstall all related compiz packages, then retry after reboot. It works.

Boot Ubuntu as normal
on log-in screen, try to Ctrl - Alt - F1
Then login to the console using the account and password.
Then try the following commands:

  sudo apt-get update
  sudo apt-get remove compiz*
  sudo apt-get install unity-2d
  sudo apt-get install compizconfig-settings-manager
  sudo apt-get install compiz-plugins-extra
  sudo shutdown -r now


after the reboot, It is OK to login again.

Move Minimize, Maximize and Close Buttons to right – Ubuntu 12.04LTS

sudo apt-get install gconf-editor
After it has finished downloading and installing, you should have your normal prompt in the terminal again (the prompt where you can type without unleashing funky characters!). You can now open gconf-editor by typing/copying…
gconf-editor
Now how do I get these buttons on the right?
In the directory tree on the left navigate through the following:
  • apps
  • metacity
  • general
Now in the panel on the right, locate and double click on button_layout
Change the value from “close,maximize,minimize:” to “:minimize,maximize,close

the original article: