Thursday 27 March 2008

Two examples of matlab implement java

Example 1: print a line
===================
import java.lang.System;
System.out.println('zhengxin');

% in Java environment, java.lang.* is automatically imported, so no need to import it when programming with java. But in Matlab, this package/classes must be imported manually.


Example 2: show a dialog
===================
import java.awt.*;
import javax.swing.*;

title = 'Frame Title';
frame = JFrame(title);
comp = JTextArea();
frame.getContentPane.add(comp, BorderLayout.CENTER);
width = 300;
height = 300;
frame.setSize(width, height);
frame.show();

Thursday 20 March 2008

London 饭店 订餐电话

川渝
地址: 37 Chalton street London NW1 1JD
电话: 0207-388-0808

安瑞丝
地址: Kilburn tube station
电话:020 7625 8686

老地方
地址: 261 bethnal green road
电话: 02077298388

香满楼
02076260126
ec3r 7pp

老北京涮肉馆
订餐电话:020 8202 1078/0789 668 4570,
KTV包间预定电话:07701088988 / 0773 815 1643/ 020 8202 3690
8/9 Sentinel Square, Brent Street, London NW4 2EL,最近地铁站为伦敦北三区的HENDON CENTRAL 地铁站 (黑线),公共汽车停靠站有326路,143路,240路,183路,83路等。

五月花
68-70, Shaftesbury Avenue, London, W1D 6NA
Tel: 020 7734 9207

Wednesday 19 March 2008

How Apple Got Everything Right By Doing Everything Wrong

From: http://www.propeller.com/viewstory/2008/03/19/how-apple-got-everything-right-by-doing-everything-wrong/?url=http%3A%2F%2Fwww.wired.com%2Ftechbiz%2Fit%2Fmagazine%2F16-04%2Fbz_apple&frame=true

Jobs' fabled attitude toward parking reflects his approach to business: For him, the regular rules do not apply. Everybody is familiar with Google's famous catchphrase, "Don't be evil." It has become a shorthand mission statement for Silicon Valley, encompassing a variety of ideals that — proponents say — are good for business and good for the world: Embrace open platforms. Trust decisions to the wisdom of crowds. Treat your employees like gods.

It's ironic, then, that one of the Valley's most successful companies ignored all of these tenets. Google and Apple may have a friendly relationship — Google CEO Eric Schmidt sits on Apple's board, after all — but by Google's definition, Apple is irredeemably evil, behaving more like an old-fashioned industrial titan than a different-thinking business of the future. Apple operates with a level of secrecy that makes Thomas Pynchon look like Paris Hilton. It locks consumers into a proprietary ecosystem. And as for treating employees like gods? Yeah, Apple doesn't do that either.

But by deliberately flouting the Google mantra, Apple has thrived. When Jobs retook the helm in 1997, the company was struggling to survive. Today it has a market cap of $105 billion, placing it ahead of Dell and behind Intel. Its iPod commands 70 percent of the MP3 player market. Four billion songs have been purchased from iTunes. The iPhone is reshaping the entire wireless industry. Even the underdog Mac operating system has begun to nibble into Windows' once-unassailable dominance; last year, its share of the US market topped 6 percent, more than double its portion in 2003.

It's hard to see how any of this would have happened had Jobs hewed to the standard touchy-feely philosophies of Silicon Valley. Apple creates must-have products the old-fashioned way: by locking the doors and sweating and bleeding until something emerges perfectly formed. It's hard to see the Mac OS and the iPhone coming out of the same design-by-committee process that produced Microsoft Vista or Dell's Pocket DJ music player. Likewise, had Apple opened its iTunes-iPod juggernaut to outside developers, the company would have risked turning its uniquely integrated service into a hodgepodge of independent applications — kind of like the rest of the Internet, come to think of it.

And now observers, academics, and even some other companies are taking notes. Because while Apple's tactics may seem like Industrial Revolution relics, they've helped the company position itself ahead of its competitors and at the forefront of the tech industry. Sometimes, evil works.

.............................

All this plays to Steve Jobs' strengths. No other company has proven as adept at giving customers what they want before they know they want it. Undoubtedly, this is due to Jobs' unique creative vision. But it's also a function of his management practices. By exerting unrelenting control over his employees, his image, and even his customers, Jobs exerts unrelenting control over his products and how they're used. And in a consumer-focused tech industry, the products are what matter. "Everything that's happening is playing to his values," says Geoffrey Moore, author of the marketing tome Crossing the Chasm. "He's at the absolute epicenter of the digitization of life. He's totally in the zone."

Tuesday 18 March 2008

阿巴斯的诗

(部分转自 mindmeters)



阿巴斯的短诗,清静,深沉,还有短。

01
  白色马驹
  浮出雾中
  转瞬不见
  回到雾里
  
  
  02
  小小一片积雪――
  漫长冬日给早春的
  留念……
  
  
  03
  白首妇人
  望一树樱花:
  莫非已是我暮年的春天?
  
  
  04
  红苹果
  在空中
  翻转千次
  落入
  顽童手心
  
  
  05
  月光
  融化了
  老河上的薄冰
  
  
  06
  秋日午后
  无花果树叶
  轻轻落下
  停在
  自己的影子上
  
  
  07
  奶牛呀
  一步一晃悠
  恰如身后农夫
  两桶奶在手
  
  
  08
  村童哟
  勇猛无惧
  瞄准草人头
  
  
  09
  一群樱桃树
  就一棵,孤零零
  半朵花不开
  
  
  10
  老狗
  看守着
  一堆
  废轮胎
  不取分文


Blocking China

The last few days there are so many connections to our mirror server
from China that I started to block certain subnets. There are usually
around 10 clients connecting via HTTP and each is opening over 50
connections to our server. They are downloading mainly ISO images and
other big files. I can see that each client is starting to download
lots of different things. From Fedora 3 to Fedora 7 ISO images, Ubuntu ISO images,
openSUSE ISO images and other old and large files.


I started to block individual IP addresses but there are just too many so
that I started to block whole subnets. I am using the following command to get
an overview about which clients are opening many connections at once:



lynx -dump -width=2000 http://localhost/server-status | awk -F\ '{ print $11} ' | sort -n | uniq -c | sort -n.

The output looks something like this:

21 122.48.129.75
23 210.21.106.229
24 218.17.228.216
26 220.175.101.252
27 222.67.18.227
30 222.27.89.136
39 123.116.101.186
52 121.231.17.153
63
63 ::1

With the following command I am calculating the netmask which will be blocked:

$ whois 121.231.17.153 | grep inetn | sed -e "s, - ,:,g" | awk ' { print "netmask "$2 }' | sh

121.224.0.0/12

And then I am using a simple iptables rule to drop any traffic coming from that network:

iptables -A INETIN -s 121.224.0.0/12 -j DROP

Currently this is the only idea I have how to get rid of those ~500 connections which seem to be some kind of abuse.

Monday 17 March 2008

Facebook application: Invitation page


<?php

require_once 'facebook.php';



$appapikey = '1111111111111111111111111';

$appsecret = '111111111111111111111111111';

$facebook = new Facebook($appapikey, $appsecret);

$user = $facebook->require_login();



// Build your invite text

$invfbml = <<<FBML

You have been invited to join YQLM notifier.

<fb:name uid="$user" firstnameonly="true" shownetwork="false"/> wants you to add YQLM googlegroups Notifier. so that you can join

<fb:pronoun possessive="true" uid="$user"/>London YQLM GoogleGroups! <fb:req-choice url="http://www.facebook.com/add.php?api_key=$appapikey" label="Add this application" />

FBML;

?>



<fb:request-form type="YQLM Notifier" action="./index.php" content="<?=htmlentities($invfbml)?>" invite="true">

<fb:multi-friend-selector max="20" actiontext="Select your friends to add this application!" showborder="true" rows="3">

</fb:request-form>


Friday 14 March 2008

Facebook application: Rss notifier


<?php //create 1 hour life cookie to prevent duplicate news



feed story.

/*

session_start();

if(isset($_SESSION['views']))

  $_SESSION['views']=$_SESSION['views']+1;

else

  $_SESSION['views']=1;

echo "Total Visits: ". $_SESSION['views'];

//*/

////////// session or cookie /////////////////

if (isset($_COOKIE["updatetime"])){

}

else{

setcookie("updatetime", time(), time()+3600);

}



?>





<?php

require_once 'facebook.php';



$appapikey = '3d3fabe3276d1dd50ddf78353c719af4';

$appsecret = 'fe4754d97d24392ba9e40105f0ea0a08';

$facebook = new Facebook($appapikey, $appsecret);

$user_id = $facebook->require_login();



// Greet the currently logged-in user!

echo "<p>Hello, <fb:name uid=\"$user_id\" useyou=\"false\"



/>!<br/>"." There are new messages on the YQLM group.</p>";

?>



<?php

// Parse the Rss feed.

$doc = new DOMDocument();

$doc->load



('http://groups.google.co.uk/group/londonppl/feed/atom_v1_0_ms



gs.xml');

//$doc->load



('http://feeds.feedburner.com/YqlmLondonGoogleGroup');

$arr = array();

foreach ($doc->getElementsByTagName('entry') as $node) {

$itemRSS = array (

'author' => $node->getElementsByTagName



('name')->item(0)->nodeValue,

'email' => $node->getElementsByTagName



('email')->item(0)->nodeValue,

'date' => $node->getElementsByTagName



('updated')->item(0)->nodeValue,

'link' => $node->getElementsByTagName('link')



->item(0)->getAttribute("href"),

'title' => $node->getElementsByTagName



('title')->item(0)->nodeValue,

'desc' => $node->getElementsByTagName



('summary')->item(0)->nodeValue);

array_push($arr, $itemRSS);

}

?>





<?php

// Show Rss contents in facebook canvas.

$dashbutton = <<<EndHereDoc

<fb:dashboard> <fb:create-button



href="http://www.facebook.com/apps/application.php?



id=11393681690">Add/Remove this application</fb:create-button>



</fb:dashboard>

EndHereDoc;

echo $dashbutton;



for ($i=0;$i<10;$i++){

echo '<br/>'.'==================='.'<br/>';

$item = $arr[$i];

$author = ($item['author']=="")?$item['email']:$item



['author'];

$content = '<b>'.$author.'</b><i> said on </i>'.$item



['date'].'<br/>'.'<a href="'.$item['link'].'">'.$item



['title'].'</a><br/><li>'.$item['desc'].'</li>';

echo $content;

}



?>





<?php

// Generate short contents in users' profile file.

$profilecontent = '<a



href="http://apps.facebook.com/googlegroupsnotifier">YQLM



Group</a><br/>';

for ($i=0;$i<2;$i++){

$pitem = $arr[$i];

$author = ($pitem['author']=="")?$pitem



['email']:$pitem['author'];

$profilecontent =



$profilecontent.'==================='.'<br/><b>'.$author.'</b>



<i> said on </i>'.$pitem['date'].'<br/><i>'.$pitem



['title'].'</i><br/><li>'.$pitem['desc'].'</li><br/>';

}

?>









<?php

///*

// This is for fbml_setRefHandle

$fbml = <<<EndHereDoc

<fb:wide>

$profilecontent

<fb:editor



action="http://apps.facebook.com/googlegroupsnotifier">

<fb:editor-button value="More messages"/>

</fb:editor>

</fb:wide>

<fb:narrow>

$profilecontent

<fb:editor



action="http://apps.facebook.com/googlegroupsnotifier">

<fb:editor-button value="More messages"/>

</fb:editor>

</fb:narrow>

EndHereDoc;



$facebook->api_client->fbml_setRefHandle



("googlegroupsnotifier",$fbml);

// */





$refinprofile = '<fb:ref handle="googlegroupsnotifier" />';

$facebook->api_client->profile_setFBML



($refinprofile,$user_id);



?>





<?php



// This is for news feed/mini feed.

$title_template = "{actor} viewed the group";

$title_data = null;

$body_template = null;

$body_data = null;



$fitem = $arr[0];

$author = ($fitem['author']=="")?$fitem



['email']:$fitem['author'];

$feedcontent = '<br/>'.$author.' said



<br/><b>'.$fitem['desc'].'</b><br/> in the topic of



'.'<i>'.$fitem['title'].'</i>';



$body_general = 'The latest post : <br/>'.$feedcontent;



//print_r($_COOKIE);

//echo time()-$_COOKIE["updatetime"];

if (time()-$_COOKIE["updatetime"]>3600){

echo "<br/><i>A new news feed will be published in the



next 1 hour.</i>";

try{

$facebook->api_client-



>feed_publishTemplatizedAction



($title_template,$title_data,$body_template,$body_data,$body_g



eneral);

}catch(Exception $e) {

//this will clear cookies for your app and



redirect them to a login prompt

echo "<br/><br/><i>"."Update the news feed too



many times, no news will appear today."."</i>";

$facebook->set_user(null, null);

}

}

else

echo "<br/><i>No news feed will be published in the



next 1 hour.</i>";

?>








Tuesday 11 March 2008

on bicycle is enjoyable

Once in a while we come across an invention that's so ludicrously chauvinist, even our testosterone-fueled rants sputter to speechlessness. Just check out the NSFW photos (and plenty of 'em) after the jump.

Bid for your own bitchcruiser on eBay. You have until March 16th to open the auction for $2,303.81...you know, if your fantasy is riding around on the most tacky bicycles ever invented before being pulled to the ground and kicked in the testicles, repeatedly.

Sex and books: London's most erotic writers

London has always been a palace of sexual varieties: both the hub of Britain’s sex trade and the chamber in which, since the advent of the printed word, debates about liberty, repression and obscenity have raged and (occasionally) been resolved. It’s the country’s erotic centre – its G-spot, if you will. Which is why Time Out decided it was high time to consider the ways in which sex has been celebrated by London writers down the centuries.

Our Top 30 chart of London’s rudest writers collects, in a single heaving but well-ventilated space, the authors we feel have contributed the most to our understanding of the city’s complex sexual psychology. What do we mean by ‘rude’? Boldly transgressive as well as pornographic (after all, anyone can be pornographic), seductive and titillating as well as obscene and, always, well written.

One of the functions of nostalgia is to purge the past of elements that don’t chime with our limited sense of how people once lived. So it’s salutary, and oddly bracing, to be reminded that dildos were around in the sixteenth century (Thomas Nashe) and that ‘cunt’ (okay, ‘queynte’) was a slang term for female genitalia in Chaucer’s day.

But don’t just take our word for it. Our saucy scribblers come endorsed by some of London’s finest contemporary writers, including Martin Amis, Sarah Waters, Will Self and Jilly Cooper.

So put down your whip, unbuckle that gimp mask and let’s begin…

1 Walter, aka Henry Spencer Ashbee
2 Alan Hollinghurst
3 Kenneth Tynan
4 Algeron Charles Swinburne
5 Thomas Nashe
6 John Wilmot, Second Earl of Rochester
7 William Shakespeare
8 Geoffrey Chaucer
9 Gerald Kersh
10 John Cleland
11
Havelock Ellis
12 Hanif Kureishi
13 Sigmund Freud
14 Henry Fielding
15 James Boswell
16 William Wycherley
17 Daniel Defoe
18 Mark Ravenhill
19 Geoff Nicholson
20 Maxim Jakubowski

21 Oscar Moore
23 Sebastian Horsley
24 Molly Parkin
25 Stewart Home
26 Mary Robinson
27 Patrick Marber
28 JG Ballard
29 Lady Caroline Lamb
30 Anthony Neilson

Thanks to Jane Edwardes, Rachel Halliburton, Nina Caplan, Jonathan Derbyshire. Portraits Simian Coates and Rob Greig

Accessing an SMB Share With Linux MachinesAccessing an SMB Share With Linux Machines

Linux (UNIX) machines can also browse and mount SMB shares. Note that this can be done whether the server is a Windows machine or a Samba server!

An SMB client program for UNIX machines is included with the Samba distribution. It provides an ftp-like interface on the command line. You can use this utility to transfer files between a Windows 'server' and a Linux client.

Most Linux distributions also now include the useful smbfs package, which allows one to mount and umount SMB shares. More on smbfs below.

To see which shares are available on a given host, run:


    /usr/bin/smbclient -L host

where 'host' is the name of the machine that you wish to view. this will return a list of 'service' names - that is, names of drives or printers that it can share with you. Unless the SMB server has no security configured, it will ask you for a password. Get it the password for the 'guest' account or for your personal account on that machine.

For example:


    smbclient -L zimmerman

The output of this command should look something like this:


Server time is Sat Aug 10 15:58:27 1996
Timezone is UTC+10.0
Password:
Domain=[WORKGROUP] OS=[Windows NT 3.51] Server=[NT LAN Manager 3.51]

Server=[ZIMMERMAN] User=[] Workgroup=[WORKGROUP] Domain=[]

Sharename Type Comment
--------- ---- -------
ADMIN$ Disk Remote Admin
public Disk Public
C$ Disk Default share
IPC$ IPC Remote IPC
OReilly Printer OReilly
print$ Disk Printer Drivers


This machine has a browse list:

Server Comment
--------- -------
HOPPER Samba 1.9.15p8
KERNIGAN Samba 1.9.15p8
LOVELACE Samba 1.9.15p8
RITCHIE Samba 1.9.15p8
ZIMMERMAN

The browse list shows other SMB servers with resources to share on the network.

To use the client, run:


    /usr/bin/smbclient service 

where 'service' is a machine and share name. For example, if you are trying to reach a directory that has been shared as 'public' on a machine called zimmerman, the service would be called \\zimmerman\public. However, due to shell restrictions, you will need to escape the backslashes, so you end up with something like this:


    /usr/bin/smbclient \\\\zimmerman\\public mypasswd

where 'mypasswd' is the literal string of your password.

You will get the smbclient prompt:


Server time is Sat Aug 10 15:58:44 1996
Timezone is UTC+10.0
Domain=[WORKGROUP] OS=[Windows NT 3.51] Server=[NT LAN Manager 3.51]
smb: \>

Type 'h' to get help using smbclient:


smb: \> h
ls dir lcd cd pwd
get mget put mput rename
more mask del rm mkdir
md rmdir rd prompt recurse
translate lowercase print printmode queue
cancel stat quit q exit
newer archive tar blocksize tarmode
setmode help ? !
smb: \>

If you can use ftp, you shouldn't need the man pages for smbclient.

Although you can use smbclient for testing, you will soon tire of it for real work. For that you will probably want to use the smbfs package. Smbfs comes with two simple utilties, smbmount and smbumount. They work just like mount and umount for SMB shares.

One important thing to note: You must have smbfs support compiled into your kernel to use these utilities!

The following shows a typical use of smbmount to mount an SMB share called "customers" from a machine called "samba1":


[root@postel]# smbmount "\\\\samba1\\customers" -U rtg2t -c 'mount /customers -u 500 -g 100'
Added interface ip=192.168.35.84 bcast=192.168.255.255 nmask=255.255.0.0
Got a positive name query response from 192.168.168.158 ( 192.168.168.158 )
Server time is Tue Oct 5 10:27:36 1999
Timezone is UTC-4.0
Password:
Domain=[IPM] OS=[Unix] Server=[Samba 2.0.3]
security=user

Issuing a mount command will now show the share mounted, just as if it were an NFS export:


[root@postel]# mount                                                                                                   
/dev/hda2 on / type ext2 (rw)
none on /proc type proc (rw)
none on /dev/pts type devpts (rw,mode=622)
//SAMBA1/CUSTOMERS on /customers type smbfs (0)

Please see the manual pages for smbmount and smbumount for details on the above operation.

Monday 10 March 2008

A simple ajax example


A simple ajax example



<html><body>



<script language="javascript" type="text/javascript">

var inputs = 0;



function addContact(){

var table = document.getElementById('contacts');

var tr = document.createElement('TR');

var td1 = document.createElement('TD');

var td2 = document.createElement('TD');

var td3 = document.createElement('TD');

var inp1 = document.createElement('INPUT');

var inp2 = document.createElement('INPUT');

///////////////

var link = document.createElement('a');

var U = document.createElement('u');

var text = document.createTextNode('del');

link.onclick = function(){

removeContact(tr);

//inputs--;

}

U.appendChild(text);

link.appendChild(U);

td1.appendChild(link);

///////////////

inp1.setAttribute("Name", "Name" +inputs);

inp2.setAttribute("Name", "Email"+inputs);

table.appendChild(tr);

tr.appendChild(td1);

tr.appendChild(td2);

tr.appendChild(td3);

td2.appendChild(inp1);

td3.appendChild(inp2);

inputs++;

}



function removeContact(tr){

tr.parentNode.removeChild(tr);

}



</script>



<table>

<tbody id="contacts">

    <tr>

        <a href="javascript:addContact();">Add a Contact</a>

    </tr>

    <tr>

        <td></td>

        <td>Name</td>

        <td>Email</td>

        </tr>

</tbody>

</table>



<script type="text/javascript">

    addContact();

</script>



</body></html>




Sunday 9 March 2008

develop, deploy and run java servlet

///////////1. Java Class ///////////////////////////
If you are not using Java EE SDK, you must download Java Servlet Api:servlet-2_5-api.jar, than put it in the classpath.

// HW.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HW extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<-html->");
out.println("<-head->");
out.println("<-title->Hello World!<-/title->");
out.println("<-/head->");
out.println("<-body->");
out.println("<-h1->Hello World!<-/h1->");
out.println("<-h1->By Cross<-/h1->");
out.println("<-/body->");
out.println("<-/html->");
}
}


/////////// Deploy it ///////////////////////////////
Put the class in \Tomcat\webapps\ROOT\WEB-INF\classes
Edit web.xml by append following 'xml' element.

// web.xml in \Tomcat\webapps\ROOT\WEB-INF
<-servlet->
<-servlet-name->myHelloWorld<-/servlet-name->
<-servlet-class->HW<-/servlet-class->
<-/servlet->
<-servlet-mapping->
<-servlet-name->myHelloWorld<-/servlet-name->
<-url-pattern->/myHello<-/url-pattern->
<-/servlet-mapping->

////////// Run it ///////////////////////////////////
Start Tomcat, then run it like this:
http://localhost/myHello

P.S.: use '<' and '>' to replace '<-' and '->' to escape Blogspot parsing html tag.
How getParameters from request, see here:
http://java.sun.com/developer/technicalArticles/RMI/rmi/
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/Servlets/Q_22996074.html?eeSearch=true

Friday 7 March 2008

retrive XML in ajax way: xmlhttprequest


Following codes is the minimum 4 steps for XMLHttpRequest.



<script language="javascript">



////////////////// initial xmlhttprequest ///////////////////////////

// 1. new XMLHttpRequest()

if (window.XMLHttpRequest) {

req = new XMLHttpRequest();

}

else{

try {

req = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

alert('Old Microsoft.XMLHTTP activexobject before IE 5.5');

try {

req = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {}

}

}





////////////////// configure and get xmlhttprequest ///////////////////////////

try{// this try/catch is only for firefox: if you installed firebug,disable it.

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");

//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

}catch (e){}

// 2. request.open()

try{

//req.open("GET", "http://crosszheng.spaces.live.com/feed.rss", true);

req.open("GET", "feed.rss", true);

//alert('get successfully');

}

catch(e){

alert(e.toString());

}

// 3. define request.onreadystatechange function, which is a event handler.

req.onreadystatechange = function() {

try

{

if((req.readyState == 4) && (req.status == 200))

{

try{

xmlobject = (new DOMParser()).parseFromString(req.responseText, "text/xml");

}catch(e){

xmlobject=new ActiveXObject("Microsoft.XMLDOM");

xmlobject.async="false";

xmlobject.loadXML(req.responseText);

}

// get a reference to the root-element "rss"

var root = xmlobject.getElementsByTagName('rss')[0];

// get reference to "channel" element

var channels = root.getElementsByTagName("channel");

// now get all "item" tags in the channel

var items = channels[0].getElementsByTagName("item");

// in the "item" we have a description, so get that

var descriptions = items[0].getElementsByTagName("description");

var desc = descriptions[0].firstChild.nodeValue;

document.write(desc);

document.close();

}

}

catch(e){

alert(e.toString());

}

}

// 4. request.send(null)

req.send(null);



</script>





more details on:http://developer.apple.com/internet/webcontent/xmlhttpreq.html




Thursday 6 March 2008

shower wow

I want to take shower use this weapon.

document.write flush your page or can not append new contents

Html actually is multithread.

Let's talk about onclick and setTimeout in html code and javascript.

The function invoked by onclick of form button and setTimeout of javascript all start a new thread to do jobs. If you run command "document.write(SOMETHING)" in the function invoked by above two ways, the SOMETHING will flush your current page, then use SOMETHING to rewrite the page. Namely, this "document" are not the original "document".

More details are on:
http://www.howtocreate.co.uk/tutorials/javascript/writing




Wednesday 5 March 2008

javascript's OO and function as object as well



Functions stored in variables



Just
to make sure you're completely clear on how all this works, make sure you fully
understand the difference between these two pieces of code:



function MyFunc() {
    alert('hi');
}


and, by comparison, this:



MyFunc2 = function() {
    alert('there');
}


The first of these creates a function called MyFunc. The second of these
creates a function, but doesn't give it a name, and then stores the function in
the MyFunc2 variable. From there, you can call either using MyFunc() and
MyFunc2().



Next, think about how a function is, in fact, an object. Consider this code,
which uses the preceding MyFunc2 variable:



MyFunc3 = MyFunc2;
MyFunc3.somemember = 10;
alert(MyFunc3.somemember);


This first line of this code copies the value of MyFunc2 to MyFunc3. Since
the value of MyFunc2 is the unnamed function, the value of MyFunc3 is this same
function. The second line adds a new member to the function called somemember,
and sets its value to 10. Although I'm using the MyFunc3 variable to do this,
the two variables refer to the same function object. Thus, in the third line,
when I do an alert on the MyFunc3 value's somemember, I'll see the 10 that I
assigned. Thus, these two variables refer to the same single function object.
Changing one changes the "other", since they're both, in fact, the
same object.



Now let's continue our discussion. Note: To create the examples for this
article, I used FireFox and the FireBug tool, simply because it's easy to
quickly try out JavaScript code.





JavaScript and Prototypes



To fully understand the object
system, however, it's important to understand the whole architecture behind it.
JavaScript uses an approach called a prototype architecture.



First, remember that JavaScript is
run line-by-line. Prior to the declaration of the Counter1 function above, the
function does not exist. Also remember that nearly everything in JavaScript is
an object. Thus, Counter1 is itself an object.



But what type are the objects stored
in my obj1 and obj2 variables? Their type is object and nothing more.
These objects are not instances of Counter1, although in our own minds
it's okay to think of them as such. Counter1 is not a class; rather, it's
simply a function that, when used in conjunction with the new keyword, creates
a new object.



If you want to give the members to
the objects created by the Counter1 function, you can do so inside the Counter1
function, as I did with this line:



this.value
= 0;



However, there's another way to do
this. Objects in JavaScript can optionally include a member called prototype.
This member is itself an object, and as its name implies, it provides a
prototype for objects created based on the object.



That's a mouthful, so let's look at
an example. Consider the Counter1 function. When you created this function (via
the function keyword), you created a function object, which automatically came
with a member object called prototype. If you're trying out the code in
FireBug, you can inspect this member. Try an alert:



alert(Counter1.prototype)



This will open an alert box
displaying the words [object Object], which simply means it's an object.
Initially, this object doesn't contain anything. But if you add members to this
object, the objects you create by calling new Counter1 will get copies of
these members
.



Let's try another example with the
help of a new function called Counter2. Here's the code:



function
Counter2() {



}



Not much there... yet. Follow with
this code:



Counter2.prototype.value
= 0;



Counter2.prototype.increment
= function() {



this.value++;



}



This adds two members to the
Counter2 function's prototype object, one called value and one called increment.
When you create a new object using the new keyword and calling this Counter2
function, your new object will automatically inherit copies of the members of
this prototype. Try it out:



c1
= new Counter2();



c1.increment();



c1.increment();



alert(c1.value);



When the alert box opens, you'll see
the value 2; thus, c1 has the value and increment members. In FireBug, you can
inspect the object using FireFox's built in dir function:



&gt;&gt;&gt;
dir(c1)



value 2



increment function()



But now try inspecting the Counter2
function's prototype object:



&gt;&gt;&gt;dir(Counter2.prototype)



value 0



increment function()



Prototypes are an important part of
JavaScript as they provide a handy means by which objects can be given members.
Remember, however, the prototype member is just an object itself, a member of
the Counter2 object.





Browsers comparison: read external file/data

1

Using following js code. In the html codes, one of script uses src= following js file, the other script calls the function defined in js file:

////////////////////////////////////////////////////////////////////////
function ieparse(){
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
try{// with this config, firefox can retrive remote xml file.
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}catch(e){}
xmlDoc.async=false;
var address = "http://crossonline.spaces.live.com/feed.rss";
alert(address);
xmlDoc.load(address);
//xmlDoc.load("1.rss");
}
catch(e) {alert(e.toString())}

try{
var xmlobject = xmlDoc;
// get a reference to the root-element "rss"
var root = xmlobject.getElementsByTagName('rss')[0];
// get reference to "channel" element
var channels = root.getElementsByTagName("channel");
// now get all "item" tags in the channel
var items = channels[0].getElementsByTagName("item");
// in the "item" we have a description, so get that
var descriptions = items[0].getElementsByTagName("description");
// we also get the "pubDate" element in the "item"
var links = items[0].getElementsByTagName("link");

// get the actual description as string
var desc = descriptions[0].firstChild.nodeValue;
// same for the pubDate
var l = links[0].firstChild.nodeValue;

// now we have the RSS data we want as strings - do something now :-)
document.write(desc);
alert(l);

document.write("xmlDoc is loaded, ready for use");
}
catch(e) {alert("wrong when processing the xmlstring")}
}
////////////////////////////////////////////////////////////////////

COmparison:

  • IE 7:
    • local file and remote file;
  • Firefox:
    • local file-work; remote file NOT,saying:
      [JavaScript Application]

      Permission denied to call method XMLDocument.load
  • Opera:
    • local file-work; remote file NOT,saying: "
      &lt;localhost&gt;

      [Error:
      name: Error
      message: Security violation
      ]".
  • Safari:
    • Both NOT, saying:
      Java Script

      TypeError: Value undefined (result of expression xmlDoc.load) is not object.

Conclusion:
1. Security and convenience can not exist together.
2.
new ActiveXObject("Microsoft.XMLDOM") is a little bit out of date, while XMLHttpRequest (for universal browser) and Msxml2.XMLHTTP (for IE) is much better, with XMLHttpRequest firefox and safari works, Opera seems not so universal. My another post is about XMLHttpRequest to solve such a calling remote XML file.



first glance at PHP vs JavaScript

So far, I did some javascript programming, and found out something javascript really can not do.

  1. javascript is a technique for web"page". So all it can control are only 'window' and 'document'. So its output normally are only 'alert' and 'document.write()'. In this case, no way to redirect any inforamtion to anywhere else.
  2. PHP is a kind of programming language, quite unix like. It can work in the way of command line, this means, it can redirect its variables to another variable or stream to anywhere else. It use 'echo' to output and as a return for command line programming, this is how so many websites using php pluse some parametres as src of javascript. Because PHP can redirect formatted .js contents to the "src=", in this way, a dynamic .js can be created. While javascript can not do that, because all javascript output goes to 'document', as a html formatted contents can not be used as .js file.

java applet <> javascript

1. javascript call java applet: http://www.rgagnon.com/javadetails/java-0170.html

* make the variable you want to call public in the applet.
* in javascript just: document.myapplet.myfunction(some parametres);

2.1 java applet call variable or function defined in javascript:

* You can try an easy method, by calling a specially crafted URL using the showDocument() method, like this :
getAppletContext().showDocument(new URL("javascript:alert(Hello World);));
This doesn't work anymore using Internet Explorer as of a certain IE update from Microsoft dated some time ago this year, so it is easily broken.

* You can use the LiveConnect objects that are implemented in IE on Windows, Mozilla/Firefox on anything, Safari on Mac, etc.. it works almost everywhere.
For this you have to declare that your applet MAYSCRIPT, by adding a special parameter in the OBJECT/EMBED tag in your web page. (google for it if you need examples).
Then you have to add the "jaws.jar" (or "plugin.jar" if there's no jaws.jar) from the lib of the JRE to compile your Applet.
This jar should include the LiveConnext classes, and netscape.javascript.JSObject is the one you need.
Then You can then do something like this to achieve the same as solution one above :
JSObject browserWindow = JSObject.getWindow(this); //here 'this' is the JApplet
browserWindow.eval(buffer.toString());
Or you can navigate the DOM javascript tree of the WebPage using the methods of JSObject. (google for it if you need more info).

2.2 java applet call variable defined in html:
Just use the parametre of applet, for example:


Tuesday 4 March 2008

shell history

For bash:

ctrl + r: will prompt you corresponding history when you type.

simplest way to config java security policy

In my case, on xp, these security policy files are stored here:
C:\Program Files\Java\jre1.6.0_04\lib\security

So, when applet need to access local or remote file, the "java.policy" should be modified.

Eclipse will generate a very dangerous java.policy.applet by default for testing, you can copy the setting permission line in to java.policy, in this case, your applet can reading files. But it's dangerous.

My way is to put such code in the java.policy. where the path is the place where my applet class file exists.

grant codeBase "file:///D:/My%20Documents/workspace/2008.3.applet/bin/" {
permission java.security.AllPermission;
};

Monday 3 March 2008

open file dialog by click

Sunday 2 March 2008

css for rss, that I always use

put this command in rss/xml file:
&lt;?xml-stylesheet href="rss.css" type="text/css"?&gt;
======================

rss
{
margin:10px;
}

channel
{
display:block;
border:solid 1px #000;
overflow:auto;
height:300px;
width:280px;
background-color:#eee;
font: 12px verdana;
}

item
{
display: block;
//padding:10px;
background-color:#fff;
}

item&gt;link
{
display:none;
}

channel&gt;title, item&gt;title
{
font:12px arial;
font-weight:bold;
font-size: 24px;
}

channel&gt;title, channel&gt;description, item&gt;title
{
display: block;
}

java copy file

[Old technique (pre JDK1.4)]

import java.io.*;

public class FileUtils{
public static void copyFile(File in, File out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
throw e;
}
finally {
if (fis != null) fis.close();
if (fos != null) fos.close();
}
}

public static void main(String args[]) throws Exception{
FileUtils.copyFile(new File(args[0]),new File(args[1]));
}
}

[JDK1.4 using the java.nio package (faster)]

import java.io.*;
import java.nio.channels.*;

public class FileUtils{
public static void copyFile(File in, File out)
throws IOException
{
FileChannel inChannel = new
FileInputStream(in).getChannel();
FileChannel outChannel = new
FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(),
outChannel);
}
catch (IOException e) {
throw e;
}
finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}

public static void main(String args[]) throws IOException{
FileUtils.copyFile(new File(args[0]),new File(args[1]));
}
}
NOTE:
In win2000 , the transferTo() does not transfer files > than 2^31-1 bytes. it throws an exception of "java.io.IOException: The parameter is incorrect"
In solaris8 , Bytes transfered to Target channel are 2^31-1 even if the source channel file is greater than 2^31-1
In LinuxRH7.1 , it gives an error of java.io.IOException: Input/output error


more details are on:http://www.rgagnon.com/javadetails/java-0064.html

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter