Monday, March 28, 2011

VIM extension setting (syntax color, multiple files ...) on Mac OS

This article is about how to set configurations on Mac OS 10.6 to use extension option of vim.

Making an optimized configuration file

To allow for syntax highlighting, auto indentation, etc. in vim, open a new Terminal window and enter these commands to open vim’s configuration file:

cd /usr/share/vim

sudo vim vimrc

Press the ‘i‘ key to switch vim to Insertion Mode, then enter these lines below the ‘set backspace=2‘ line:

set ai " auto indenting
set ruler " show the cursor position
syntax on " enable syntax highlighting
set background=dark " make color suitable to dark background
set history=100
set hlsearch " highlight the last searched term
filetype plugin on " use the file type plugins

nmap <C-T> :tabprev<CR> " key mapping to move between files when open in tabs: Ctrl+T
nmap <C-B> :tabnext<CR>  " Ctrl+B


" When editing a file, always jump to the last cursor position
autocmd BufReadPost *
\ if ! exists("g:leave_my_cursor_position_alone") |
\ if line("'\"") > 0 && line ("'\"") <= line("$") |
\ exe "normal g'\"" |
\ endif |
\ endif

Press the Escape key to take vim out of Insertion Mode, then press ‘:‘ (colon) followed by ‘x‘ to save the file and exit.
Open/Create a script file with vim, for example:

vim hello.php

You’ll see that vim now automatically indents code, displays the cursor position, has syntax highlighting, etc.

To open multiple files in tabs, replace vi with vim

You can add the following line into your .profile or .bash_profile :

alias vi="vim -p"

Alias allows us to change the way of calling vim, when typing vi, bash shell will replace vi command with vim -p. Therefore, we can open multiple files in tabs.

After saving the file, run
source ~/.profile
vi file1 file2 file3

As we already added key mappings in .vimrc, you can switch between files with 'Ctrl+T' and 'Ctrl+B'.


The :tabf command allows you to search for a file in your current path and open it in a new tab. For instance, if you want to open a file called inventory.txt that's in your current path, you could run:

:tabf inven*

That will search for a file that matches the string inven and any number of characters after it. If only one file is found, Vim will open it in a new tab. If you have several files that match, Vim will complain that too many files match, and you'll have to narrow the search a little. The :tabn command will do autocompletion of file names in your path, so you can just type the first few characters of a filename and hit Tab to find the right file.

Reference to this link for more: Vim tips: Using tabs

To open multiple files in splits

If you are already editing a file in vim and want to split the screen and edit a second one, you can use either of these commands:

:sp filename Splits the screen horizontally and opens filename in the new area.
:vsp filename Splits the screen vertically and opens filename in the new area.

Any split can be further split -- you can edit as many files in a single instance of vim as you like.

Use the following commands to move back and forth through your files and manage the size of the splits.
The prefix for all the below commands is <c-w> -- that is, hold down Ctrl and type w. Press <c-w> before typing any of the below commands.

<C-W> Moves to the next split.
k Moves to the split above the current split.
Up Moves to the split above the current split.
j Moves to the split below the current split.
Down Moves to the split below the current split.
h Moves to the split on left side of the current split.
l Moves to the split on right side of the current split.
+ Increases the size of the current split by one line. (Try combining this with counts -- e.g. 5<C-W>+ will make the split five lines bigger.)
- (Minus sign) Decreases the size of the current split by one line.
_ (Underscore) Maximize the current split (that is, make it take up as much room as possible.)

We can add the below key maps to .vimrc file to make working with splits easier:

map <C-J> <C-W>j<C-W> "go to the split below the current one
map <C-K> <C-W>k<C-W> "go to the split above the current one
map <C-H> <C-W>h<C-W> "go to the split on left of the current one
map <C-L> <C-W>l<C-W> "go to the split on right of the current one


Saving and quitting

When working with multiple files, each tab / split acts something like an individual instance of vim -- so :w and :q work on the current file. If you want those commands to apply to all the files instead of just the current one, add 'a' to them -- for instance, :wa saves all the open files, :qa quits all open files (and exits vim), and :wqa saves and then closes all open files.

Friday, January 07, 2011

Pogoplug and WDTV sharing via NFS

Finally I get Pogoplug and WDTV linked. Yahoo!!

NFS Server (Pogoplug)
Reference to 'Running an NFS Server' in http://openpogo.tumblr.com/

ipkg install nfs-server
vi /opt/etc/exports
# add following line 
/tmp/.cemnt/mnt_sdb1/download 192.168.1.0/255.255.255.0(rw,async,no_root_squash) 
 
Because nfs-server depends on the portmapper, we must verify that portmapper is running before start nfs-server.

# start nfs server
/opt/etc/init.d/S56nfsd

# make sure nfsd started
ps -w


NFS Client (WDTV)
Devices I have:
* WDTV: gen 1 with B-Rad's unofficial firmware WDLXTV 0.5.8.1
* Wireless adapter: Rosewill RNX-EasyN1 (Chipset Ralink 3070)
* USB drive: a very old timer -- Apacer 32M. Yes, and don't laugh. It is 32M. You read it correctly. It came back to life again. :)

- Config network with Wireless adaptor

Fortunately Pogoplug has web interface wireless support in my.pogoplug.com. So I first plug RNX-EasyN1 into pogoplug and set it up in the web interface. Then simply copy /etc/Wireless/RT2870STA/RT2870STA.dat out from pogoplug to root of the start up USB drive.

Download wireless app wireless-mod-rt.app.bin (search in WDTV Forum) and put in root of usb drive.

- Add NFS app
download nfs.app.bin-0.3 and copy to root of USB drive.

-Config NFS Client
Edit net.mounts and put into usb drive root.
xmount 192.168.1.3:/tmp/.cemnt/mnt_sdb1/download Pogo nfs udp,soft,rsize=32768,wsize=32768


Evertything is ready now. 'Restart' WDTV.
There are 2 ways to restart WDTV:
- Pull out power adaptor and wait a while (let's say 20 sec) and plug in
or
- Telnet/SSH into WDTV if you have network setup successfully already. Run reboot.

Check if NFS share is success from your WDTV GUI. If there is problem, telnet/ssh into wdtv and check mount, /etc/fstab... My link is not stable at first, after several reboot, it's there finally. Cheers!

Thursday, January 06, 2011

[Pogoplug] Install Transmission

Based on Installing OpenPogo + Transmission on dockstar

- SSH into Pogoplug.
        
    # makes filesystem read-write
    mount -o rw,remount / 
    ipkg install nano transmission
    # Run the following 2 commands to generate a configuration file for Transmission
    transmission-daemon --config-dir /opt/etc/transmission-daemon 
    killall transmission-daemon
    # modify the settings.json file
    # go to line 44 and make “rpc-whitelist-enabled”: false, save it
    vi /opt/etc/transmission-daemon/settings.json
    transmission-daemon --config-dir /opt/etc/transmission-daemon 
    mount -o r,remount /


Now you should be able to browse the web interface with http://pogoplug_ip-addr:9091 and change settings in the preference page. You can also go into the setting.json and modify any of the other settings.

To set an init script to make transmission run on boot create a script:

vi /opt/etc/init.d/S88transmission 

#!/bin/bash
# Starts up transmission
#

start() {

 echo -n "starting up transmission:"
 if [ -n "`pidof transmission-daemon`" ]; then
  killall `pidof transmission-daemon`
 fi

 /opt/bin/transmission-daemon --config-dir /opt/etc/transmission-daemon --blocklist

}

stop () {

   echo -n "stopping transmission:"
   killall transmission-daemon

}

restart () {

   stop
   start
}

case "$1" in

   start)
   start
   ;;

   stop)
   stop
   ;;

   restart)
   restart
   ;;

   *)
   echo "usage: $0 {start|stop|restart)"
   exit 1
   ;;

 esac


Be sure to set the downloads directory from the interface to the real directory identified by the pogoplug ie. '/tmp/.cemnt/mnt_sdb1/downloads' you should see the field getting populated in the setting.json file, now whenever you reboot transmission should start up too.

[Pogoplug] Install/Uninstall PlugApps to a USB flash drive

- Make sure all the wires are linked ( network, power, usb )
- Get IP address of pogoplug from router/modem
- Log into my.pogoplug.com to enable SSH access and set a password.
- SSH into pogoplug as root with putty.

- Partition/format the USB Drive on which you will install PlugApps
cd /tmp
wget http://plugapps.com/os/pogoplug/mke2fs
chmod 755 mke2fs
killall hbwd # This will turn off my.pogoplug.com functionality temporarily and unlock the USB drive for PlugApps installation.
/sbin/fdisk /dev/sda # delete all existing partitions and create a new one
./mke2fs /dev/sda1
/sbin/reboot


- Unplug usb and reboot and plugin usb when restarted

- Install PlugApps

On your PC navigate to the Pogoplugged Development download page http://www.pogoplugged.com/download/list?cat=36 and download the "opt.tar.gz" file to your computer. Then upload it into the root of usb drive via my.pogoplug.com.

SSH again.

cd /tmp/.cemnt/mnt_sda1
# wget http://openpogo.com/base/openpogo-usb.tar.gz
# tar -xzvf openpogo-usb.tar.gz
tar -xzvf opt.tar.gz
mount -o rw,remount /
ln -s /tmp/mnt_opt/.opt /opt

# When booting the mount_opt script looks for openpogo on any of the 4 usb ports and then creates another link to the physical device as /tmp/mount_opt/.opt. So a link pointing to a link pointing to a physical disk because we do not know what order the drives get mounted after reboot.

cp /etc/init.d/rcS /etc/init.d/rcS.original
echo '# code added below for OpenPogo /opt on USB with init on boot' >>  /etc/init.d/rcS
echo '/etc/init.d/mount_opt' >>  /etc/init.d/rcS
echo '/opt/etc/init' >>  /etc/init.d/rcS

echo '#!/bin/bash' > /etc/profile
echo '# New profile added for OpenPogo /opt on USB' >> /etc/profile
echo '#' >> /etc/profile
echo 'export PATH=/opt/bin:/opt/sbin:/usr/bin:/usr/sbin:/bin:/sbin' >> /etc/profile

cp /tmp/.cemnt/mnt_sda1/.opt/mount_opt /etc/init.d/
rm /tmp/.cemnt/mnt_sda1/openpogo-usb.tar.gz
chmod 755 /etc/init.d/mount_opt

/sbin/reboot


- SSH again after restart

Change to the original repository


Since OpenPogo is no longer maintained you should change to the original repository:

Change to the ipkg configuration directory
cd /opt/etc/ipkg

Check the name of the conf file
ls

You should see some filename with .conf in the ending, then edit this file
vi or nano filename.conf (probable armel-feed.conf)

Comment out current repo
"src cross http://openpogo.com/repo" 
to 
"#src cross http://openpogo.com/repo"

Then add the new repo underneath
src cross http://ipkg.nslu2-linux.org/feeds/optware/cs08q1armel/cross/stable

Exit from your editor, then reboot your system
sync
sync
reboot

Once rebooted, log back in to your system and do an update
ipkg update


Congratulations! OpenPogo should now be successfully installed and you are all ready to go. Just log back in using ssh again.

UNINSTALL

In case you need to uninstall PlugApps, SSH into pogoplug first:
mount -o rw,remount /
mv /etc/init.d/rcS.original /etc/init.d/rcS
rm /etc/profile
rm /etc/mount_opt
rm /opt
mount -o r,remount /
rm -r  /tmp/.cemnt/mnt_sda1/.opt
/sbin/reboot

Reference:
How-to-Install-or-remove-OpenPogo-on-Your-Pogoplug-Attached-USB-Drive/

[Pogoplug] Hacking Pogoplug Gray version

Around 2 months ago, I got a Pogoplug gray version when BB had it on sale.

The exciting thing about this box is:
- It's linux based which means you can hack in it and add on packages you want.
- It's small, low noise, energy saving.

I've been looking for a low budget NAS for a long time. So the chance is here.

The software with this box provides online access and Windows/Mac/Linux drive driver. But it's not enough for me. I also need it to be able to download, and link to my WDTV as a media center. To modify this pogoplug into my ideal NAS, I searched online and read a lot articles about it. PlugApps is the most complete and successful one I found so far. Here is what I did.

First I installed PlugApps to a USB flash drive based on
OpenPogo:Installing Base Package - USB
and
How to Install (or remove) OpenPogo on Your Pogoplug-Attached USB Drive.

It provides additional features to the existing Pogoplug software by creating an opt folder on the USB drive that allows installation of Optware ipkg applications.

** Since Pogoplug disabled ssh by default, ssh must be enabled from the settings page of my.pogoplug.com before starting this installation.

What I used:
- I downloaded putty to my Asus EeePC (Windows XP) to SSH into pogoplug and execute all the commands;
- a 8GB Kingston USB flash drive formatted to ext2 attached to pogoplug.

When the basic stuff are in place, I added more packages such as: Samba (file sharing), Transmission(BT download), Lighttpd Web Server with PHP , MySQL and PHPMyAdmin ...

Then the most important part, install NFS server to share media to WDTV.

OK. That's it. I'll put more details in later posts.

Monday, February 23, 2009

Regular Expression

from JAVA Programming Cookbook

  • Quantifiers
+ Match one or more
* Match 0 or more
? Match 0 or 1

- Greedy, Reluctant, and Possessive Quantifiers

A greedy quantifier matches the longest matching sequence.
A reluctant quantifier (also called a lazy quantifier) matches the shortest matching sequence.
To create a reluctant quantifier, follow it with a ?.
A possessive quantifier matches the longest matching sequence and will not matching a shorter sequence even if it would enable the entire expression to succeed.
To create a possessive quantifier, follow it with a +.

E.G.
"simple sample"
The pattern s.+e will match the longest sequence, which is the entire string because the greedy quantifier will match all characters after the first s, up to the final e.
The pattern s.+?e will match 'simple', which is the shortest match. This is because the reluctant quantifier .+? will stop after the finding the first matching sequence.
The pattern s.++e will fail, because the possesive quantifier .++ will match all characters after the initial s. Because it is possessive, it will not release the final e to enable the overall pattern to match. Thus, the final e will not be found and the match fails.

  • JAVA's Regular Expression API
- Pattern
The Pattern class defines no constructors. Instead, a Pattern is created by calling the compile() factory method.
- Matcher
Matcher class has no constructors. Instead, a Matcher is created by calling the matcher() factory method defined by Pattern.

  • Character Classes
\d, \D -- digits 0-9, all non-digits
\s, \S -- whitespaces, all non-whitespaces
\w, \W -- Characters that can be part of a word, all non-word characters

Java supplies a large number of other character classes which have the following general form:
\p{classname}
i.e. \p{Lower} , \p{Upper}, \p{Punct}. \p{Alpha}

To create a class that contain the intersection of two or more sets of characters, use the && operator. i.e. [\w && [^A-Z]]

  • Boundary Matchers
^, $
\A Start of string
\b Word boundary
\B Non-word boundary
\G End of prior match
\Z End of string (Doesn't include line terminator.)
\z End of string (Includes line terminator.)

Thursday, April 03, 2008

MySQL query performance

The following 2 queries are used for the same purpose to get data in a range, but the time cost is quite different.

$query_1 = "SELECT import_id, amount FROM import_tbl WHERE ABS(amount-99.99)<0.001 AND import_id>=$start AND import_id<=$end ORDER BY import_id";
Empty set (2.05 sec)

$query_2 = "select import_id, amount from import_tbl where ABS(amount-99.99)<0.001 limit $cnt, $offset";
Empty set (27.71 sec)

When using EXPLAIN in mysql, you can see that query_2 scans all the rows in the table, while query_1 just search the rows fall in the range.

EXPLAIN Syntax

EXPLAIN tbl_name

Or:

EXPLAIN [EXTENDED] SELECT select_options

The EXPLAIN statement can be used either as a synonym for DESCRIBE or as a way to obtain information about how MySQL executes a SELECT statement:

* EXPLAIN tbl_name is synonymous with DESCRIBE tbl_name or SHOW COLUMNS FROM tbl_name.
* When you precede a SELECT statement with the keyword EXPLAIN, MySQL displays information from the optimizer about the query execution plan. That is, MySQL explains how it would process the SELECT, including information about how tables are joined and in which order.


EXPLAIN
Quote:

http://dev.mysql.com/doc/refman/5.0/en/explain.html


or PROFILE
Quote:

http://dev.mysql.com/doc/refman/5.0/en/show-profiles.html

Friday, July 13, 2007

Java Package Tutorial

Java Package Tutorial (English version)

It took me 2 hours to get rid of the exceptions I got as the following. Just because I didn't use the fully-qualified class name.



Suppose we have a file called HelloWorld.java, and we want to put this file in a package world.

One thing you must do after creating a package for the class is to create nested subdirectories to represent package hierachy of the class.

Next, we have to introduce the world package into our CLASSPATH.

When compiling HelloWorld class, we just go to the world directory and type the command:

C:\world\javac HelloWorld.java


If you try to run this HelloWorld using java HelloWorld, you will get the following error:

C:\world>java HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name:
world/HelloWorld)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:442)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:101)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
at java.net.URLClassLoader.access$1(URLClassLoader.java:216)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:191)
at java.lang.ClassLoader.loadClass(ClassLoader.java:290)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)


The reason is right now the HelloWorld class belongs to the package world. If we want to run it, we have to tell JVM about its fully-qualified class name (world.HelloWorld) instead of its plain class name (HelloWorld).

C:\world>java world.HelloWorld


Note: fully-qualified class name is the name of the java class that includes its package name

Wednesday, October 05, 2005

PHP Tips -- MAGIC QUOTES

Copied from a webpage, can't remember the link...

It's recommend that developers do their own string escaping, as if magic quotes is off, and use the below code to strip the additional slashes resulting from a PHP installation where magic quotes is on.

//----------------------------------------------------
// Is magic quotes on?
if (get_magic_quotes_gpc()) {

// Yes? Strip the added slashes

$_REQUEST = array_map('stripslashes', $_REQUEST);
$_GET = array_map('stripslashes', $_GET);
$_POST = array_map('stripslashes', $_POST);
$_COOKIE = array_map('stripslashes', $_COOKIE);
}
//----------------------------------------------------


//----------------------------------------------------
Mysql blob data

In PHP, you can insert data into the database like so:

$data = addslashes(fread(fopen($_FILES['doc']['tmp_name'], "r"), $_FILES['doc']['size']));

Then insert the $data element into the blob field.

This is useful if the documents need to be kept secure, for example if you need each user to be able to only access one file but not another. Beats out trying to work out multiple htaccess directories, which otherwise the links can be passed around.


//------------------

string htmlentities(string string);
and
string htmlspecialchars(string string);
will convert special characters "&'<>.." to HTML string, such as "...
?>


<tr><td>
Last Name:
</td>
<td><input name="rlname" value="" type="text" maxlength=20 size="20"> </td>
</tr>

PHP Tips -- Send Email


<?php
//This is the location of your sendmail variable
$mail_path = "/usr/sbin/sendmail -i -t";

//The email address to be receiving emails from this form
$mail_to = $email1 . ','. $email2;

//the subject of the email sent by the form
$mail_subject = "Confirm email";

/* To send HTML mail, you can set the Content-type header. */
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: ABC\r\n";
$headers .= "Reply-to: contact@mycom.com\r\n";
$headers .= "Bcc: logs@mycom.com\r\n";

//the name of the buisness or website that the form contacts
$message = "<html><head></head><body>";
$message .= "<p>Dear $name, <br /> <br /> Your order is successfully created. <br />".
"Please go to the following link to track the status of your order: <br />".
"<br /><a href='http://www.mycom.com/cgi-bin/ordtrk.php?ordnum=$order_num'>
http://www.mycom.com/cgi-bin/ordtrk.php?ordnum=$order_num
</a><br /><br />".
"Thank you.

";
$message .= "</body></html>";

//ini_set("sendmail_from", $mail_from);
ini_set("sendmail_path", $mail_path);

if( mail($mail_to, $mail_subject, $message, $headers) )
{
echo 'Email was sent to' . $email;
}else{
echo "There was an error in the email address";
}
?>


The general format of a multipart MIME message will be the following:
---------------- Begin -------------------

To: whoever@someplace.com
Subject: MIME test
Content-type: multipart/mixed; boundary="theBoundaryString"

--theBoundaryString

Plain text message goes in this part. Notice that it
has a blank line before it starts, meaning that this
part has no additional headers.

--theBoundaryString
Content-Type: text/html
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
Content-Base: "http://somewebsite.com/"

<body><font size=4>This</font> is a
<i>test</i>.
--theBoundaryString--

---------------- End -------------------
Notice each of the blank lines above. Each one is important because it separates the header from the body in each part of the multipart document. First, the standard email headers are listed. The string theBoundaryString is used to separate each part of the multipart document. For the plain text area, there are no additional headers. Thus, it simply has a blank line before the actual content starts. After that, the HTML file with its headers starts.

The an important header there is Content-Base. It specifies the relative address for links within the HTML document. In other words, the following hyperlink:

<a href="apage.html">

will be interpreted relative to http://somewebsite.com/. Therefore, its full URL is:

http://somewebsite.com/apage.html

If you use full URLs in the HTML document, then there will be no need to specify Content-Base. For more information on this, see RFC 2110.

PHP Tips -- Form

** get Multi-select data in a form

<tr>
<td valign="top">Area code:</td>
<td>
<select id="area" name="area[]" size=6 multiple>
//Use area[] for php to get more value
<script>
frm = this.document.formname;
frm.area.options[frm.area.length] = new Option("--", "", false, false);
</script>
<?php

$id = @mysql_connect($host, $user,$dbpasswd) or
ErrMsg("Cannot connect to MySQL server");
@mysql_select_db($dbname,$id) or ErrMsg("Cannot open database");
$query = "select * from area where id=$uid;";
$result = mysql_query($query, $id);

while ($uarray = mysql_fetch_array($result)){
$area = $uarray["area"];
echo "<option value='$area'>$area";
}

mysql_free_result($result);
mysql_close($id);
?>
</select>

</td>
</tr>

<?php
// Get Multi-select data in a form

foreach($_POST['area'] as $value){
if ($value != ''){
$query = "insert into area (uid, area) values($uid, '$value');";
$result = mysql_query($query, $id) or ErrMsg("Query Error: $query");
}
}


/* To get multi check in a form:
Give the group of check box the same name, end with [],
PHP compiles the user input for this field into an array.
*/
?>
<input type='checkbox' name="codes[]" value='aaa'>
//Use codes[] for php to get more value as an array
<input type='checkbox' name="codes[]" value='bbb'>
//if didn't set value, php will get 'on' when checked
//else php get the value when checked.
//If unchecked, php get null no matter value is set.
<input type='hidden' value='' name='codesarray'>

<script>
function validate()
{
// Get checkbox array before submit
codearray = document.Formname.elements['codes[]'];

for (i=0; i {
if (codearray[i].checked == true)
{
document.Formname.codesarray.value += codearray[i].value + ",";
}
}
}
</script>

<?php
if (!isset($_POST['codes']))
{
$codesarray = '';
}else{
// Get an array of codes
$codes = $_POST['codes'];
$codesStr = implode(",", $codes); // combine entries into a string
}
echo "\n";
?>

PHP Tips -- DB Functions

MySQL Functions
<?php
$host="localhost:3306";
$user="root";
$dbpasswd="passwd";
$dbname="mydb";

$id = @mysql_connect($host, $user, $dbpasswd) or die(mysql_error());

@mysql_select_db($dbname,$id)
or die("DBCannot open database" . mysql_error());

$query = "select * from mycontact;";
$result = mysql_query($query, $id)
or die("mysql_query: $query" . mysql_error());

// Retrieves the number of fields from a query.
$num_fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
if ($rows === false) return false;

$i=0;
while($i<$num_fields)
{
$fname[$i] = mysql_field_name($result,$i);
$i++;
}

while ($accarray = mysql_fetch_row($result))
//No. 1 fast, but difficult to remember column number.
while ($accarray = mysql_fetch_assoc($result))
//No. 2 fast, with associated array, recommend
while ($conarray = mysql_fetch_array($result))
//No. 3 fast
while ($conarray = mysql_fetch_array($result, MYSQL_NUM))
//No. 4 fast
while ($conarray = mysql_fetch_array($result, MYSQL_ASSOC))
//No. 5 fast
while ($conarray = mysql_fetch_array($result, MYSQL_BOTH))
//The slowest
{
foreach($conarray as $k=>$v) $message .= $v. " ";
$fname = $conarray['firstname'];
}

mysql_data_seek($result, 0);

mysql_close($id);
?>


ODBC Functions

<?php
//connect to database
$connectionstring = odbc_connect("myapp", "user", "pswd");

//SQL query
$Query = "delete from company where id=$jid";
$Query = "update company set description='$description', company='$company', Website = '$web', name='$name', tel='$tel', fax='$fax', email='$email', address='$address', date='$date' where id=$jid";
$Query = "SELECT *, DATEPART('yyyy',date) AS mydate FROM company where id=$jid";

//execute query
$queryexe = odbc_do($connectionstring, $Query);
if (odbc_fetch_row($queryexe))
{
//collect results
$position = odbc_result($queryexe, "position");
}

//disconnect from database
odbc_close($connectionstring);
?>

PHP Tips -- File & Output Buffer Functions

File
/* Creates a file with a unique filename in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.
*/
string tempnam ( string dir, string prefix)

/* Given a string containing a path to a file, this function will return the base name of the file. If the filename ends in suffix this will also be cut off.
*/
string basename ( string path [, string suffix])

/* Given a string containing a path to a file, this function will return the name of the directory.
*/
string dirname ( string path)

bool file_exists("file_name");

is_file("file_name");
is_dir("dir_name");
is_readable();
is_writable();
is_executable();
int filesize(); // bytes
timestamp fileatime("file_name"); // when a file was last accessed
timestamp filemtime("file_name"); // when a file was last modified
timestamp filectime("file_name"); // when a file was last changed(unix) / created(other platform)

//Deletes filename
bool unlink ( string filename [, resource context]);

// Attempts to set the access and modification
// time of the file named by filename to the value given by time.
// If the file does not exist, it is created.
bool touch ( string filename [, int time [, int atime]])

// Reading ends when length - 1 bytes have been read,
// on a newline (which is included in the return value),
// or on EOF (whichever comes first).
// If no length is specified, the length defaults to 1k(1024 bytes).
string fgets ( resource handle [, int length]);

string fread ( resource handle, int length);

flock( $fp, LOCK_SH/LOCK_EX/LOCK_UN);

Output Buffer
bool ob_start ( [callback output_callback [, int chunk_size [, bool erase]]])

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

Example:

<?php
// Buffer the current html page so we can write it to file later
ob_start();
$var = "Generated html script";
?>

<html>
<head>
<title>HTMLGEN</title>
</head>
<body>
Loading.... <br />
<?php echo $var; ?>
More contents!<br />
</body>
</html>

<?php
// Write the buffered HTML file
$fp = fopen($htmlFile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
?>

PHP Tips -- String & Time Functions

String Functions

string trim($str);
string ltrim($str);
string rtrim($str);
int strlen($str)

string strtoupper($str);
string strtolower($str);
// make the first letter of $str uppercase
string ucfirst($str);
// make the first letter of every word in $str uppercase
string ucwords($str);

string nl2br($str);
string wordwrap($str[, $maxlinelen, $linebrkStr, $bBreakLongWord]);

false/string strstr($srcstr, $substr);
//case sensitive, return false if $substr not in $srcstr
// return the portion of the source string begining with the substring.
// Ex. strstr("abcd","bc") return "bcd"

false/string stristr($srcstr, $substr);
//not case sensitive, return false if $substr not in $srcstr

false/int strpos($srcstr, $substr, $index=0);

string substr($str, $index[, $len]);
string substr_replace($str, $rplace_str, $index, $len);
string str_replace($search_str(or a str array), $rplace_str(or a str array), $source_str(or a str array)); //replace all

$str_array = explode($delimiter, $str);

string/flase strtok([$str,] $delimiters)
Ex:

$test = "http://www.test.com/test.php?op=window&ver=5.0&db=sql&dev=php+mysql";
$delims = "?&";

$word = strtok($test, $delims);
//first time call, give the string as a para, the string will be catched.

// if $test contain empty string in it, should pass here
while(is_string($word)) {
if($word) { //not an empty string
echo "$word
";
}
// After the first time call, only give the delimiters
$word = strtok($delims);
}


string strip_tags()
$test = "<p>test: this <b>paragraph</b><br /> will return a line</p>";
echo "<pre>before: $test </pre>";
echo strip_tags($test, "<br />");


$billnum = "TAASD000012";
sscanf($billnum, "%1s%10s", $w1,$w2);
$counter = $w2 + 0;
// when $w2 isn't a number("AASD000012"), $counter will be 0


* ----------------------------------------------------- *
number_format -- Format a number with grouped thousands
Description
string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] )

number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

If two parameters are given, number will be formatted with 'decimals' decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with 'decimals' decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

Only the first character of thousands_sep is used. For example, if you use foo as thousands_sep on the number 1000, number_format() will return 1f000.
* ----------------------------------------------------- *

PHP Tips -- Array & Class

Array
* Create a numerical array with more than one elements:
$colors = array("red", "yellow", "black", "green");

* Create a associative array with more than one elements:
$member = array(
"name" => "Bob",
"age" => 30,
"occupation" => "superman",
);

* Array functions:
array_merge();
// different with ( $array1 + $array2 ).
// the later will completely preserve the arrays and just append them to each other

$arrA+$arrB : combine two arrays

array_unique();
// Two elements are considered equal if and only if
// (string) $elem1 === (string) $elem2.
// In words: when the string representation is the same.


$codes = implode(",", $codesarray);
// Join array elements with a string

$codesarray = explode(',',$codes);
// Split a string by string

$num1=count($codes);
// Count elements in an array, or properties in an object

split -- split string into array by regular expression
array split ( string pattern, string string [, int limit] )


Class

class myclass{
var $name;

function myclass($n) { $this->name =$n; }

function sayhi(){
echo "Hi! My name is ". $this->name;
}
}

class childclass extends myclass {

function myclass($n)
{
parent::myclass($n);
}

function sayhi(){
echo "Hi! My name is ". $this->name .". How are you?";
}

}

$obj1 = new childclass("Bob");
$obj1->sayhi();

PHP Tips -- Constant, Variable & Operator

Constant

Predefined constants
__FILE__ : The name of the file that the PHP engine is currently reading, contains the full path and filename of the current (i.e. included) file.

__LINE__ : The line number of the file.

PHP_VERSION : Current PHP version

How to Define Constants

if (!defined("NO")) define("NO", 0);
if (!defined("YES")) define("YES", 1);


Use constant

if ($answer == YES) return true;


VARIABLE

integer, double, string, boolean, object, array,
NULL, Resource(reference to a third-party resource(a db,for example))

Some related functions:

gettype($var)
settype($var, 'typestr'); // changes the original data type
(datatype)$var //use cast, like in C, doesn't change the original data type


A variable declared in a function remains local to that function ( not available to outside the function or within other functions.

A variable declared outside a function will not automatically be available within it.
To access for a global variable, you need to use the global statement in the function.

Use static to declare a static variable in a function
Ex.

$var1 = 1;
$var2 = 3;
function a()
{
static $svar1 = 0;
global $var1, $var2;

$svar++;
}




=== : Identical, Left is equivalent to right and they are the same type.

Ex:

$x = 4;
$x === 4; //true
$x === '4'; //flase

$teststr = "mz00xyz";
if (strpos($teststr, "mz") === 0) {
// returns index 0, which could be resolve to false.
// Use "===" can work around this,
// the condition will be true (false and 0 are diffrent data type)
echo"Hello mz";
}


Have a browse of the PHP Cheat Sheet

PHP Tips -- SUPER GLOBALS

$GLOBALS---An array of all global variables (Like the global keyword, this allows you to access global variables inside a function---for example, as $GLOBALS[#myvariable#].)

$_SERVER---An array of server environment variables contains information such as headers, file paths, and script locations.

Ex:
header("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/" . "mypage.php?msg=1");
$WEB_HOST = "https://" . $_SERVER['HTTP_HOST'];
header("Location: " . $WEB_HOST . dirname($_SERVER['PHP_SELF']) . "/" . "mypage.php?msg=1");

$_GET---An array of variables passed to the script via the GET method

$_POST---An array of variables passed to the script via the POST method

$_COOKIE---An array of cookie variables

$_ENV---An array of the server environment variables

$_REQUEST---An array of all user input including the contents of input including $_GET, $_POST, and $_COOKIE

$_SESSION---An array of currently registered session variables

------------- initial -------------
session_start();
/* When this script is run for the first time from a browser, a session ID is generated by session_start(). session_start() attempts to set a cookie when initiating a session for the first time. If the page is reloaded, the same session ID is allocated to the user. This action assumes that the user has cookies enabled. You must call this function before output anything to the browser. If 'session.cookie_lifetime' is not set in php.ini, the cookie is no longer stored when the user restart the browser. It's not sure that the client's browser will accept cookies. The safe way is to use SID (PHP makes a name/value pair for a session ID)
Ex. <a href="apage.html?<?php echo SID; ?>"> Go Here</a>

// to set or get a session id
session_id();

//return the current dir to which session files are saved or set the dir.
session_save_path([path]);

Ex.

if(!session_id()){
session_start();
}

$_SESSION['loginname'] = $_POST['loginname'];


------------- destroy -------------
$_SESSION=array();
session_destroy();

****** It seems that $varname and $_SESSION['varname'] use the same memory address.
When modify $varname, $_SESSION['varname'] changes at the same time.



$_FILES---An array of variables related to file uploads
$_FILES['fileupload']['name']: Original name of uploaded file
$_FILES['fileupload']['tmp_name'] Path to temporary file
$_FILES['fileupload']['size'] Size of uploaded file(in bytes)
$_FILES['fileupload']['type'] MIME type of uploaded file (where given by client) -> [image/gif]

Ex.
// HTML forms that include file upload fields must include an ENCTYPE argument:
<p>
<form action="dfa" enctype="multipart/form-data" method="post">
<!-- max file size: 50K, must be 'MAX_FILE_SIZE' for PHP to work with -->
<input type='hidden' name='MAX_FILE_SIZE' value='51200' />
<p> File to Upload: <input type="file" name="fileupload" id="name"> </p>
</form>
</p>
// Accept file


<?php
$file_dir = "/path/to/upload/dir";

foreach($_FILES as $file_name => $file_array)
{
echo "path: $file_array['tmp_name'] < br /> /n";
echo "name: $file_array['name'] < br /> /n";
echo "type: $file_array['type'] < br /> /n";
echo "size: $file_array['size'] < br /> /n";
}

if (is_uploaded_file($file_array['tmp_name']))
{
move_uploaded_file($file_array['tmp_name'], "$file_dir/$file_array['name']") or die("Couldn't copy");
echo "file was moved";
}
?>

Tuesday, October 04, 2005

HTTP Essentials

Digest from "HTTP Essentials" By Stephen A.Thomas

* URI
http://user:passwd@www.example.com:80/html.filepath/filename.html?query1=1#Fragment

* TCP Connection

Client ---------------> Server
1) TCP SYN
<---------------
2) TCP SYN, ACK
--------------->
3) TCP ACK (3-way handshake)

--------------->
4) HTTP Request
<---------------
5) HTTP Response

<---------------
6) TCP FIN
--------------->
7) TCP FIN, ACK

* Persistent

With persistent connections, a client can issue many HTTP requests over a single TCP connection.

* Pipelining

With Pipelining, a client dosen't have to wait for a response to one request before issuing a new request on the connection.

Client ---------------> Server
1) TCP SYN
<---------------
2) TCP SYN, ACK
--------------->
3) TCP ACK (3-way handshake)

--------------->
4.1) HTTP Request1
--------------->
4.2) HTTP Request2
<---------------
5.1) HTTP Response1
<---------------
5.2) HTTP Response2

<---------------
6) TCP FIN
--------------->
7) TCP FIN, ACK


* User Operations

GET

Client ---------------> Server
1) GET URI
<---------------
2) 200 OK, DATA (if error, return other status code.)


POST

Client ---------------> Server
1) POST URI (action URI), DATA
<---------------
2) 200 OK[, DATA] (if error, return other status code.)


PUT (File Upload)

Client ---------------> Server
1) PUT URI (where to put object), DATA
<---------------
2) 200 OK[, DATA] (if error, return other status code.)


DELETE (File Deletion)

Client ---------------> Server
1) DELETE URI (remove object), DATA
<---------------
2) 200 OK[, DATA] (if error, return other status code.)


* Behind the Scenes

OPTIONS
Discover what capabilities a server supports. Such information would let the client adjust how it interacts with the server or how it actually requests a specific object.

Client ---------------> Server
1) OPTIONS URI/*(General options)
<---------------
2) 200 OK, OPTIONS


HEAD
Just like the a GET operation, except that the server doesn't return the actual object request. It can be used to verify that an obj exists.

Client ---------------> Server
1) HEAD URI
<---------------
2) 200 OK


TRACE
Check the network path to a server.

Client ---------------> Intermediate Server ---------------> Ultimate Server
1) TRACE 2) TRACE, Via
<--------------- <---------------
4) 200 OK, message 3) 200 OK, message


* Cooperating Servers

Virtual Hosts
The 'HOST' header in HTTP 1.1 lets clients explicitly identify the Web site they are accessing, so the virtual hosting Web server can return the right content.

Client ---------------> Server --|--------- www.company1.com
1) GET /news.html |
Host:www.company1.com |--------- www.company2.com
<---------------
2) 200 OK, DATA (if error, return other status code.)


Redirection

Client ---------------> Server1
1) GET URI
<---------------
2) 301 Moved, NewURI
---------------> Server2
3) GET NewURI
<---------------
4) 200 OK