Thursday, August 11, 2011

Ajax


		$.ajax({
			url: "/inbox/newresults", 
			async: true, 
			dataType: 'json',
			data: data,
			timeout: 3000,
			success: function(json) {	
    	        if(json == null || json.currenttime == undefined){
    	        	return;
    	        }
    	        
    	        //json.count=Math.ceil(Math.random()*100);
    	        
    	        if(json.count > 0 && json.count != monitor.numOfNewResults ){
		        	monitor.lastCheckingTime = json.currenttime;
		        	monitor.message=_("Vous avez %1 nouveaux résultats")
		        		.replace('%1',''+json.count+'');
		            document.title = document.title.replace(/\s+\(\d+\)$/,'')+' ('+json.count+')';  
		        }

		        monitor.refresh();
		        monitor.numOfNewResults = json.count;
			}
		});


public function action_availableSerieObjectTypes(){
		
		$this->auto_render=false;
		$types = stats\Chart::getAvailableChartTypes();

		// translate
		foreach($types as $k=>$v){
			$types[$k]=_($v);
		}
		
		$this->request->response = json_encode(array('serie_object_types'=>$types));
	}



Reference: 

Wednesday, August 10, 2011

Javascript Utilities

function createTag(tag, content, attrs){
	
	var ret = "<" + tag;
	var isFirst = true;
	if(attrs != null){
		for( var k in attrs){
		   if(isFirst){
			   isFirst = false;
			   ret = ret + " " + k + "='";
		   }
		   else{
			   ret = ret + ", " + k + "='";
		   }
		   
		   ret = ret + attrs[k] + "'";
		}
	}
	if(content == null){
		ret = ret + "/>\n";
	}
	else  ret = ret + ">" + content + "\n";
	
	return ret;
}


function createComboBox(options, defaultOption, attrs){
    var ret = "";
	for( var i in options){
		if(defaultOption != null && defaultOption == options[i]){
			ret += createTag("option", options[i], {"selected":"true"});
		}
		else{
			ret += createTag("option", options[i]);
		}
		
	}
	ret = createTag("select", ret, attrs);
	return ret;
};

Reference:                        

template

<pre class="brush:php;tab-size: 8"></pre>

<b><u>Reference:&nbsp;                </u></b>

Thursday, August 4, 2011

关键字云

class Token{

 public $count = 0;

 public $key = null;

 private $subTokens = array();

 // type could be "object" or "category"

 public $type = null;



 public static function create($key, $type="object", $MIN_LEN=2, $MAX_LEN=6){

  $t = new Token;

  $t->key = $key;

  $t->type = $type;



  $len = mb_strlen($key, "UTF-8");

  if($len > $MIN_LEN){

   if($len > $MAX_LEN){

    $len = $MAX_LEN + 1;

   }

   $strs = self::extractTokenStrs($key, $len-1, $len-1);

   foreach($strs as $str){

    $t->addSubToken($str);

   }

  }

  return $t;

 }



 public function addSubToken($key){

  if(!isset($this->subTokens[$key])){

   $this->subTokens[$key]=1;

  }

  else{

   $this->subTokens[$key]++;

  }

 }



 public function getSubTokens(){
  return array_keys($this->subTokens);
 }



 public static function extractTokenStrs($string, $MIN_LEN=2, $MAX_LEN=6){

  $tokenStrs = array();

  //match the 2-char, 3-char, 4-char, 5-char and 6-char tokens and put it into $rawtokens

  $len = mb_strlen($string, "UTF-8");



  if($MAX_LEN >= $MIN_LEN){

   for($k = $MAX_LEN; $k >= $MIN_LEN; $k--){

    for($j = 0; $j <= $len-$MIN_LEN; $j++){

     $subStr = mb_substr($string, $j, $k, "UTF-8");

     if(mb_strlen($subStr, "UTF-8") != $k){

      break;

     }

     $tokenStrs[] = $subStr;

    }

   }

  }

  return $tokenStrs;

 }





}

class Cloud{

 private $keywords = array();

 private $categories = array();





 private function addToken($string){

  if(empty($string)){

   return false;

  }



  if(!isset($this->keywords[$string])){

   $this->keywords[$string] = Token::create($string, "object");

  }

  $this->keywords[$string]->count++;

  return $this->keywords[$string];

 }



 private function addCategory($string){

  if(empty($string)){

   return false;

  }



  if(!isset($this->categories[$string])){

   $this->categories[$string] = Token::create($string, "category");

  }

  return $this->categories[$string];

 }



 private function emptyCategories(){

  $this->categories = array();

 }



 public function addTokens($string){

  $strs = self::split($string, array("的","了","然后","[\pP\pS\pZ\pC\pM]+","[0-9a-zA-Z]+"));

  foreach($strs as $str){
   if(mb_strlen($str, "UTF-8") >= 2){

    $this->addCategory($str);


   }

  }



 }

 private function emptyKeywordsList(){
  $this->keywords = array();
 }

 public function buildKeyWordsList(){
  $this->emptyKeywordsList();
  foreach($this->categories as $c){
   $ss = Token::extractTokenStrs($c->key, 2, 6);
   foreach($ss as $s){
    $this->addToken($s);
   }
  }
 }



 public static function longest_string_in_array($array) {

  $mapping = array_combine($array, array_map('mb_strlen', $array));

  return array_keys($mapping, max($mapping));

 }



 public function findBestMatchingWords($threshold){

  /* find the longest words satisfies the threshold */

  $keywords = array();

  foreach($this->categories as $k){

   $this->extractCategoryKeywords($k, $threshold, $keywords);

  }

  $keys = array_keys($keywords);

  if(count($keywords)===0){

   return false;

  }

  $lkeys = self::longest_string_in_array($keys);

  $ret = array();

  foreach($lkeys as $k){

   $ret[$k] = $keywords[$k];

  }

  return $ret;

 }

 private function removeInfluence(Token $token){
  $num = $token->count;
  $ss = Token::extractTokenStrs($token->key, 2, 6);

  foreach($ss as $s){
   $this->keywords[$s]->count-=$num;
  }
 }



 public function getKeywords($threshold = 3){

  $this->buildKeyWordsList();

  $stopList = array();
  $keywords = array();


  $categoriesToRestore = $this->categories;
  while(true){



   $bestWords = $this->findBestMatchingWords($threshold);



   if($bestWords === false){

    break;

   }



   // add it to stopList

   // add it the keywords

   foreach($bestWords as $w){

    $keywords[$w->key]= $w;
    $this->removeInfluence($w);
    $stopList[] = $w->key;

   }



   // use the stop list to rebuild the categories

   $oldCategories = $this->categories;

   $this->emptyCategories();

   foreach($oldCategories as $c){

    $list = self::split($c->key, $stopList);

    foreach( $list as $nc){

     $this->addCategory($nc);

    }

   }

  }

  $this->categories = $categoriesToRestore;
  return $keywords;

 }



 public static function split($string, $delimiters){

  //build the patterns

  $pattern = "/";



  foreach($delimiters as $c => $d){

   if($c === 0){

    $pattern = $pattern.$d;

   }

   else{

    $pattern = $pattern."|".$d;

   }

  }

  $patterns = $pattern."/isu";

  $rawtokens = preg_split($patterns, $string);

  return $rawtokens;

 }



 public function extractCategoryKeywords($root, $threshold, &$keywords=null){



  $key = $root->key;



  if($keywords === null){

   $keywords = array();

  }



  if(isset($keywords[$key])){

   return;

  }



  if(isset($this->keywords[$key]) && $this->keywords[$key]->count >= $threshold){

   $keywords[$key]=$this->keywords[$key];

  }

  else{

   $subTokens = $root->getSubTokens();

   foreach( $subTokens as $s){

    $this->extractCategoryKeywords($this->keywords[$s], $threshold, $keywords);

   }

  }

 }

}// Cloud ends

set_time_limit ( 1000 );
$string = <<<EOT
meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
meta name="description" content="[回到部落格首頁]"
EOT;
$cloud = new Cloud();
$cloud->addTokens($string);
print_r(array_keys($cloud->getKeywords(3)));
echo "hello";


Reference 

Tuesday, August 2, 2011

优女友待举措

【女孩子希望得到,却不愿说出的事】:
1.搂她的腰;
2.跟她真正的谈话;
3.和她分享秘密;
4.给她一件你的衬衫;
5.温柔地亲她;
6.和她拥抱;
7.和她一起笑;
8.带她去你去的地方;
9.和朋友出去玩时带上她;
10.和她合影;
11.让她坐在你膝上;
12.告诉她她很漂亮;
13.不要对她说谎;
14.别脚踏两只船......

 Reference:                                    
  1. http://photo.renren.com/photo/268684280/photo-4223894716#4254420495

PHP general variable or array control

//swap two variables

function swap (&$x, &$y) {

$x ^= $y ^= $x ^= $y;

} 

Reference:                                         
  1. http://www.bukisa.com/articles/30572_swap-variables-values-in-php

Monday, August 1, 2011

资源存放和对象分工经验

一个类对于其子类组织结构,自身实现应该有足够的自主能力,所以应该将所有这些逻辑置于这个类内,而只提供函数接口给其它类使用。不要让其他类透视这种类的组织结构并使用之完成它的企图。

层式结构的核心在于下层对上层一无所知,上层对下层的知识仅在于其接口。

PHP Time Utilities

function greaterDate($start_date,$end_date){
   $start = strtotime($start_date);
   $end = strtotime($end_date);
   if ($start > $end)
     return true;
   else
     return false;
}


Friday, July 29, 2011

法语词汇前缀

法语词汇前缀


1. 表示否定的前缀
a-,an-, 不,非,无 apolitique[不问政治的anonyme[不具名的
im-il-im-ir-) 不,非,无 inaltérable[不变质的illisible[不清楚的immangeable[不能吃的irréel[不现实的www.54tyro.com我是新手
non- 不,非,无 nonchalant[漫不经心的non-métal[非金属
2. 带有强化意义的前缀
archi- 极端;过度 archifou[极疯狂的;极傻的我是新手
extra- 超;极端;过度 extra-fin[极精细的;特优的我是新手
hyper- 超;过度 hypersensible[过分敏感的
super- 超越;过度;高级 supermarché[超级市场
sur- 超过;过分 suralimentation[过度营养
ultra 超;过度;极端 ultramoderne[极现代化的我是新手
3. 表示同情敌视对立的前缀
anti- 反对,反抗 antidémocratique[反民主的 
antidote[解毒的
contre- 反对;相反 contre-attaque[反击
pro- 赞成,亲 procommuniste[赞成共产党的]prochinois[亲华的
4. 表示时空关系的前缀 www.54tyro.com我是新手
anté- 先,前;在之前 antécombrien[前寒武纪的]antéposer[前置,放在前面
après-
post- 后;在之后 après-demin[后天
après-gurre[战后
postface[后记,跋我是新
avant- 我是新手
pré- 先,前,在以前 avant-hier[前天
préétabli[预定的
co-con- 共,同,合,和,相互 co-auteur[合作者
concitoyen[同乡
entre- 之间 entreacte[幕间休息
ex- ex-ministre[前部长我是新
extra- 外;在之外 extra-terrestre[地球之外的
inter- 之间 interscolaire[校际的
intra- 内部,在内 intramusculaire[肌肉内的
trans- 横贯,穿过 transnational[跨国的
5. 常见动词前缀 我是新手
a- 方向;目的,使 abaisser[放下
attendrir[使变软
anté- 先,前 antéposer[前置
auto- 自行,自动;自身 automatiser[使自动化
co- 共,同,合,相互 coexister[共存
con- 我是新手
col-
com- 我是新手
cor- 共,同,合,相互 concorder[相符,协调
combiner[组合,联合
collaborer[合作,协作
correspondre[符合
contre- 反对;相反 contre-attaquer[反攻,还击
dé-,dés- 分离;去除,解除 dépoétiser[使失去诗意我是新手
dis- 否定 disjoindre[拆开54tyro.com我是新手
é-,ef-es- 分离,去除,失去 échanger[交换,互换
égarer[使迷路
en-,em- 使成为 engraisser[使肥沃
emmaigrir[使消瘦我是新手,进步从此开始!
entr- 相互 s’entretuer[自相残杀
ex- 出,外 exclure[开除;排斥
in-,il-,im- 不,无,非; 我是新手
向,入,内 invalider[使无效
impatienter[使不耐烦
inter- 禁止 54tyro.com我是新手
相互关系 interdire[禁止
interconnecter[使互连
intro- 向内,进入 introduire[引入,介绍
mal- 坏,恶;错 malmener[虐待
micro- 微,小 microminiaturiser[使微型化我是新手
mono- 单独的 momologuer[自言自语我是新手:
monopoliser[垄断,专营
multi- 多,复 multiplier[增多我是新手
poly- 多,聚 polycopier[油印
post- 后,在 postposer[后置,放在后面
pré- prévenir[预防
re-,ré- 再,重新 refaire[重做
réimprimer[重印
r- 逆,反 rajuster[再调整
rétro- 向后,追溯 rétroagir[追溯既往我是新手
sous- 不足;再 sous-amender[再修正
sub- 再,在 subordonner[使从属于
我是新手www.54tyro.com
super- 在上面;超越 superfinir[超精加工我是新手:
sur- 在上;超过 surmonter[置于 
trans- 横贯,穿过;变化 transcrire[眷写
transpercer[穿过
ultra- 超过,极度 ultracentrifuger[超速离心分离
uni- 单一 unifier[统一,划一

Reference:                                                  
  1. http://www.ecolefrancois.com.cn/News_View.asp?NewsID=522

法语前缀re的学习和应用

通常情况下,re-加在以辅音或者虚音h为首字母的动词前:

remarier - 使再婚

(加在marier - 使结婚前)

rehausser - 再提高

(加在hausser - 提高前)

Res-

在以s开头的动词前,re-常常为res-

ressortir - 再出来

(加在sortir - 出来前)

ressembler - 相似

(加在sembler - 好象前)

Ré- and r-

在元音或者哑音h前,re-要么加上一个变成ré(在拉丁词根的单词中尤其如此),要么缩写成r-,对于个别动词,这两种情况都存在。

外语爱好者网站-www.ryedu.net

réapparaître - 复现

(加在apparaître - 出现前)

réélire - 再次选举

(加在élire - 选举前)

rentrer - 再进入;回来

(加在entrer - 进入前)

rhabiller - 重新给…穿衣服

(加在habiller - 给…穿衣服前)

récrire, réécrire - 再写,再写一遍

(加在écrire - 写前)

re- 的意思(以及它的变体)

1. 重做,再做一遍

rouvrir - 再打开

(加在ouvrir - 打开前)

ressaisir - 重新抓住

(加在saisir - 抓住前)

2. 回到一个先前的位置,条件或状态

revenir - 回来

(加在venir - 来前)

réhabituer - 使重新习惯于

(加在habituer - 使习惯于前)

3. 为了强调一个动词

redoubler - 大大增强;倍增

(加在doubler - 增加一倍前)

remercier - 感谢

(加在mercier[古]- 谢谢前)

注意:因为前缀re- 往往不只一种意思,所以一些动词也是如此:

rappeler - 再打电告给(某人);叫回,召回;使想起,唤醒

(加在appeler - 打电话前)

renvoyer - 送回;退回;再送;再派遣

(加在envoyer - 寄,送前)

Reference:                                        
  1. http://class.wtojob.com/class771_52407.shtml#

Tuesday, July 26, 2011

check Chinese, Japanese and Korean(CJK) block in UTF-8

function countChars($text, $startCode, $endCode){
 
 $len = mb_strlen($text,"UTF-8" );
 $s = hexdec($startCode);
 $e = hexdec($endCode);
 $cnt = 0;
 for($k = 0; $k < $len; $k++){
  $ch = mb_substr($text, $k, 1, "UTF-8");
  if(getUnicodeFromOneUTF8($ch) >= $s && getUnicodeFromOneUTF8($ch) <= $e){
   $cnt++;
  }
 }
 return $cnt;
}

function countChinese($text){
 return countChars($text, "4e00", "9fa5");
}

function countJapanese($text){
 return countChars($text, "0800", "4e00");
}

function countKorean($text){
 return countChars($text, "3130", "318f") + countChars($text, "ac00", "d7a3");
}

function countSpaces($text){
 return countChars($text, "20", "20");
}

function getUnicodeFromOneUTF8($word) {
  //获取其字符的内部数组表示,所以本文件应用utf-8编码!
  if (is_array( $word))
    $arr = $word;
  else 
    $arr = str_split($word);
  //此时,$arr应类似array(228, 189, 160)
  //定义一个空字符串存储
  $bin_str = '';
  //转成数字再转成二进制字符串,最后联合起来。
  foreach ($arr as $value)
    $bin_str .= decbin(ord($value));
  //此时,$bin_str应类似111001001011110110100000,如果是汉字"你"
  //正则截取
  $bin_str = preg_replace('/^.{4}(.{4}).{2}(.{6}).{2}(.{6})$/','$1$2$3', $bin_str);
  //此时, $bin_str应类似0100111101100000,如果是汉字"你"
  //u4e00-u9fa5 (中文)
  //x3130-x318f (韩文)
  //xac00-xd7a3 (韩文)
  //u0800-u4e00 (日文)
  return bindec($bin_str); //返回类似20320,汉字"你"
  //return dechex(bindec($bin_str)); //如想返回十六进制4f60,用这句
}
Reference 

Wednesday, July 6, 2011

redirect php standard error and output

fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
       
 $STDIN = fopen($options["logLocation"], "r");
 global $STDOUT;global $STDERR;
 $STDERR = $STDOUT = fopen($options["logLocation"], "a+");


set_error_handler(array('System_Daemon', 'phpErrors'), E_ALL);

Wednesday, June 29, 2011

处理用户输入的经验

用户端的介面应有尽可能清晰的提示,确保用户能正确输入,但是不需要多少安全验证,因为再多的安全保护都很容易很删改

服务器端不需要有多少对用户的提示,不过必需尽可能地保证数据的合法,一致,安全

Tuesday, June 28, 2011

Send variables between Javascript, Form and PHP on the same page



Super useful bits of PHP, Form and JavaScript code
















All code on this page is considered by us to contain the most basic and
important aspects of form sending. This page basically shows in the
shortest possible way how you can:

  • Test your PHP offline - Test your PHP pages offline easily, without installing your own web server.








  • Send variables between Javascript, Form and PHP on the same page:








  • Send variables from one page to another:









  • * URL variables to PHP/JavaScript page - Allow
    sending different variables via the URL string to the new page (readable
    through PHP or Javascript). This is more appropriate than the below if
    there are few pieces of small info you wish to send.

    * PHP variables to PHP page - Alternatively, maintain a session by sending PHP variables to another page with PHP in (allows super large arrays).

    * Form variables to PHP page - Alternatively, allow sending hidden form variables to a PHP page. This allows the user to (more easily than the above methods) select options on the page (via URL, radio buttons, or dropdown menu), and for these to be sent to the new page.

    * Form variables (tick boxes) to PHP page - As above but with tick boxes.






  • Dynamically update HTML - Allow different bits of HTML to dynamically execute according to user input:





















  • Send variables between Javascript, Form and PHP on the same page:





    PHP variable to Javascript variable:


    <?php   $myvar=10;   ?>
    
     <script type="text/javascript">
      jsvar = <?php echo $myvar; ?>;
      document.write(jsvar);  // Test to see if its prints 10:
     </script>
    


    Form variable to Javascript variable:


    <form name="myform4">    <input type="hidden" name="formvar" value="100">     </form>
    
     <script type="text/javascript">
      jsvar = document.myform4.formvar.value;
      document.write(jsvar) // test
     </script>
    





    PHP variable to Form variable:


    <form name="myform4">
      <input type="hidden" name="formvar" value="<?php phpvar=10; echo phpvar; ?>"> // PHP code inside HTML!!
     </form>
    




    Javascript variable to Form variable:


    <form name="myform3">
      <!-- It needn't be a "hidden" type, but anything from radio buttons to check boxes -->
      <input type="hidden" name="formvar" value="">
     </form>
    
     <script type="text/javascript">
      jsvar=10;
      document.myform3.formvar.value = jsvar;
     </script>
    


    Javascript variable to PHP variable:


    This is impossible (unless you reload the page), since all PHP code is
    rendered first (on the server side), and then Javascript is dealt with
    afterwards (on the client side).





    Form variable to PHP variable:


    Impossible like above.

























    Allow sending different variables via the URL string to the new page (readable through PHP or Javascript).



    The version shown below uses PHP to read the variables back, but it's
    possible to use Javascript and some messy splitting to do the same (for
    that route, see this nice little function, or here, or here for example code.)




    EXAMPLE:



    Send variables via URL!


    INSIDE "page1.php" or "page1.html"


    // Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
     <a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a> 
    
     


    INSIDE "page2c.php"

    <?php
      // Retrieve the URL variables (using PHP).
      $num = $_GET['myNumber'];
      $fruit = $_GET['myFruit'];
      echo "Number: ".$num."  Fruit: ".$fruit;
     ?>
     





























    Maintain a session by sending PHP variables (including multiple full
    blown multi-dimensional arrays if you so wish) to a page with PHP in.



    INSIDE "page1.php"

    <?php
     // "session_register()" and "session_start();" both prepare the session ready for use, and "$myPHPvar=5"
     // is the variable we want to carry over to the new page. Just before we visit the new page, we need to
     // store the variable in PHP's special session area by using "$_SESSION['myPHPvar'] = $myPHPvar;"
     session_register();
     session_start();                      
     $myPHPvar=5;
     $_SESSION['myPHPvar'] = $myPHPvar;
    ?>
    
    <a href="page2.php">Click this link</a>, and the "$myPHPvar" variable should carry through.
    



    INSIDE "page2.php"

    <?php
     // Retrieve the PHP variable (using PHP).
     session_start();
     $myPHPvar = $_SESSION['myPHPvar'];
     echo "myPHPvar: ".$myPHPvar." ..........(should say \"myPHPvar: 5\")<br>";
    ?>
    















    Allow sending hidden form variables to a PHP page. This allows the
    user to select options on the page, and for these to be carried across
    to the new page.



    EXAMPLE:



    (these links all go to the same PHP page...)

    Click 1st

    Click 2nd

    Click 3rd




    Click 1st

    Click 2nd

    Click 3rd
















    INSIDE "page1.php" or "page1.html"


    <!-- Pass over to the new page an arbitrary value, which in this case, is determined by... -->
    
    
    <!-- ***********  the link being clicked: (USE THIS OR...) ************** -->
    
    <a href="#" onclick="document.myform.formVar.value='first'; document.myform.submit(); return false">Click 1st</a><br>
    <a href="#" onclick="document.myform.formVar.value='second'; document.myform.submit(); return false">Click 2nd</a><br>
    <a href="#" onclick="document.myform.formVar.value='third'; document.myform.submit(); return false">Click 3rd</a><br>
    
    <!-- ***********  the radio button pressed before clicking "Send Form" (...OR USE THIS OR...) ************** -->
    
    <input name="br" type="radio" onClick="document.myform.formVar.value='first'">Click 1st<br>
    <input name="br" type="radio" onClick="document.myform.formVar.value='second'">Click 2nd<br>
    <input name="br" type="radio" onClick="document.myform.formVar.value='third'">Click 3rd<br><br>
    
    <!-- *********** the dropdown menu selected before clicking "Send Form" (...OR USE THIS) ************** -->
    
    <select onchange="document.myform.formVar.value=this.value">
     <option value="first">Select 1st</option>
     <option value="second">Select 2nd</option>
     <option value="third">Select 3rd</option>
    </select>
    
    <!-- ***************************************** -->
    
    
    <!--  In each of the above three cases, the hidden variable in the code below is needed for it all to work.
    Also notice how the destination page is given here, rather than in anything above -->
    
    <form method=post name="myform" action="page2.php">
     <input type="hidden" name="formVar" value="">
     <input type="submit" value="Send form!">
    </form>
    
    


    INSIDE "page2.php"

    <?php
     // Retrieve the hidden form variable (using PHP).
     $myvar = $_POST['formVar'];
     echo "myvar: ".$myvar;
    ?>
    









    Allow sending hidden form variables (using tick boxes) to a PHP
    page. This allows the user to select options on the page, and for these
    to be carried across to the new page.


    EXAMPLE:

    INSIDE "page1.html"


    Tick A

    Tick B

    Tick C









    CODE:


    INSIDE "page1.html"

    Tick A <input type="checkbox" checked onClick="document.myform2.a0.value = this.checked"><br>
    Tick B <input type="checkbox" onClick="document.myform2.b0.value = this.checked"><br>
    Tick C <input type="checkbox" onClick="document.myform2.c0.value = this.checked">
    
    <form method=post name="myform2" action="page2b.php">
     <input type="hidden" name="a0" value="true">
     <input type="hidden" name="b0" value="false">
     <input type="hidden" name="c0" value="false">
     <input type="submit" value="Send form!">
    </form>
    

    INSIDE "page2b.php"

    <?php
     // Retrieve the hidden form variable (using PHP).
     $myvarA = $_POST['a0'];
     $myvarB = $_POST['b0'];
     $myvarC = $_POST['c0'];
     echo "myvarA: ".$myvarA."<br>";
     echo "myvarB: ".$myvarB."<br>";
     echo "myvarC: ".$myvarC;
    ?>
    
















    Allow different bits of HTML to dynamically execute according to which radio button is pressed

    This is useful for many purposes including using buttons to change the
    picture (as part of a gallery), or for different sub forms to appear
    accordingly.



    EXAMPLE:





    Click 1st

    Click 2nd

    Click 3rd



    Anything can go here



    .....[I am the footer]







    CODE:

    <script type="text/javascript">
     function SetHTML1(type) {
      document.getElementById("a1").style.display = "none"
      document.getElementById("b1").style.display = "none"
      document.getElementById("c1").style.display = "none"
      // Using style.display="block" instead of style.display="" leaves a carriage return
      document.getElementById(type).style.display = ""
     }
    </script>
    
    <input name="br" type="radio" checked onClick="SetHTML1('a1')">Click 1st<br>
    <input name="br" type="radio" onClick="SetHTML1('b1')">Click 2nd<br>
    <input name="br" type="radio" onClick="SetHTML1('c1')">Click 3rd<br><br>
    
    <span id="a1" style="">Anything can go here                                                          </span>
    <span id="b1" style="display:none">...like an image...<br><img src="http://www.skytopia.com/ar.png">    </span>
    <span id="c1" style="display:none">...<a href="http://www.skytopia.com">or a link</a>...                         </span>
    
    .....[I am the footer] <!-- Not needed, but shows how stuff below the dynamic content makes it move up and down -->
    







    Allow different bits of HTML to dynamically execute according to which dropdown menu is selected


    EXAMPLE:






    Anything can go here



    .....[I am the footer]





    CODE:

    <script type="text/javascript">
     function SetHTML2(type) {
       document.getElementById("a2").style.display = "none"
       document.getElementById("b2").style.display = "none"
       document.getElementById("c2").style.display = "none"
       // Using style.display="block" instead of style.display="" leaves a carriage return
       document.getElementById(type).style.display = ""
     }
    </script>
    
    <select onchange="SetHTML2(this.value)">
     <option value="a2">Select 1st</option>
     <option value="b2">Select 2nd</option>
     <option value="c2">Select 3rd</option>
    </select>
    
    <span id="a2" style="display:none">Anything can go here                                                 </span>
    <span id="b2" style="display:none">...like an image...<br><img src="http://www.skytopia.com/ar.png">    </span>
    <span id="c2" style="display:none">...<a href="http://www.skytopia.com">or a link</a>...                </span>
    
    .....[I am the footer] <!-- Not needed, but shows how stuff below the dynamic content makes it move up and down -->
    








    Add/remove bits of HTML according to multiple checkboxes


    EXAMPLE:







    Anything can go here









    CODE:

    <script type="text/javascript">
     function SetHTML3(check,type) {
      if(check==true) document.getElementById(type).style.display = "";
      else            document.getElementById(type).style.display = "none";
     }
    </script>
    
    <input type="checkbox" CHECKED onClick="SetHTML3(this.checked,'a3')">
    <input type="checkbox" onClick="SetHTML3(this.checked,'b3')">
    <input type="checkbox" onClick="SetHTML3(this.checked,'c3')">
    
    <span id='a3'> <b> Anything can go here </b></span>
    <span id='b3' style="display:none"> <b> ...like an image... <img src="http://www.skytopia.com/ar.png"> </b></span>
    <span id="c3" style="display:none"> <b> ...<a href="http://www.skytopia.com">or a link</a> </b></span>
    









    Test your PHP pages offline easily, without installing your own web server.

    This was something recently that doubled my productivity in a snap. Simply use EasyPHP.
    It's only 8 megabyte, and a million times quicker and simpler to
    install/configure than a fully blown Apache (or equivalent) server. In
    fact, it's small GUI window will make it instant - just make sure you
    put PHP pages inside its special www folder, and point your browser to
    the "http://127.0.0.1/mywebpage.php".



    Apart from this amazing time saver, always "View source" to see what PHP
    outputs to the HTML/Javascript page (remember, PHP is read by the
    server, but is not potentially visible to the visitor in the same way
    that Javascript or HTML is).



    The last amazing tip is to insert "exit();" when an annoying bug creeps
    into the code to see where the code goes wrong (try "exit()" at
    different points throughout the code)

    References:                           
    1.  http://www.skytopia.com/project/articles/compsci/form.html

    Monday, June 27, 2011

    Mysql Problems with error 1100: Table ... was not locked with LOCK TABLES

    When you use LOCK TABLES, you must lock all tables that you are going
    to use in your queries. Because LOCK TABLES will not lock views, if
    the operation that you are performing uses any views, you must
    also lock all of the base tables on which those views depend.
    While the locks obtained with a LOCK TABLES statement are in effect,
    you cannot access any tables that were not locked by the statement.
    Also, you cannot use a locked table multiple times in a single
    query. 

    Reference                           
    1. http://hi.baidu.com/kennlee/blog/item/e839db66246e0520aa184c25.html 
    2. http://forums.mysql.com/read.php?21,134450,144180#msg-144180

    Tuesday, June 21, 2011

    When using a PHP function that requires a callback, how do we pass a custom parameter to the callback?

    class Callback
    {
        public $parameter;
    
        public function handle($matches)
        {
            return $matches[1] . ($matches[2] + $this->parameter);
        }
    }
    
    $instance = new Callback();
    $instance->parameter = 99;
    echo preg_replace_callback("|(\d{2}/\d{2}/)(\d{4})|", array($instance, 'handle'), $text);
    

    Reference 
    1. http://stackoverflow.com/questions/1502626/when-using-a-php-function-that-requires-a-callback-how-do-we-pass-a-custom-param

    Saturday, June 18, 2011

    止咳嗽

    陈皮, 黑豆,蜜枣,瘦肉

    1.浸陈皮
    2. 2个蜜枣,黑豆煮瘦肉
    3.  后下陈皮

    Friday, June 17, 2011

    How to configure apache for a new website

    //For Linux

    1. go /etc/apache2/sites-available/ and create a file for your site
    2. run command "a2ensite [yoursite]"
    3. reload apache by command "/etc/init.d/apache2 reload"
    4. configure hosts file /etc/hosts



    //For Mac

    1. go /etc/apache2/other/ and create a file for your site
    2. restart apache
    3. configure hosts file to point you website to 127.0.0.1 /etc/hosts


    //To include website configuration files into httpd.conf

    add this line to the bottom

    Include /private/etc/apache2/other/*.conf


    //To make .htacces file work

    So I opened up my http.conf file and went down to line 378, and sure enough this is what I saw:

    <directory>
    Options Indexes FollowSymLinks
    AllowOverride None
    </directory>

    In order to get .htaccess files working in the new version, I just had to change None to All, restart the server, and everything worked normally. Just thought I would share in case anyone else runs into this problem.

    <directory>
    Options Indexes FollowSymLinks
    AllowOverride All
    </directory>

    Reference:                      
    So You Want to Use .htaccess files with MAMP?
    http://trevordavis.net/blog/use-htaccess-files-with-mamp

    Thursday, May 26, 2011

    Eclipse Error: The builder launch configuration could not be found.

    Errors during build.
    Errors running builder "Integrated External Tool Builder" on project project.
    The builder launch configuration could not be found.
    Errors running builder "Integrated External Tool Builder" on project project.
    The builder launch configuration could not be found.
    Errors running builder "Integrated External Tool Builder" on project project.
    The builder launch configuration could not be found.
    Errors running builder "Integrated External Tool Builder" on project project.
    The builder launch configuration could not be found.
    Errors running builder "Integrated External Tool Builder" on project project.
    The builder launch configuration could not be found.
    ************************


    1.Select the right project
    2.Choose "project"on the tool bar -> Properties
    3.Click "Builders" in the menus of the popped up window
    4.Remove the missing builders

    Reference                                      
    1. http://dy.f.blog.163.com/blog/static/60711476200941824126555/

    Wednesday, May 11, 2011

    Passing parameters to a function called with setTimeout

    When creating my news ticker plugin, I came across a slight complication when using setTimeout() to calling a function which needed parameters passed to it. Not having had much call to use setTimeout in the past, I simply put:

    setTimeout(myFunction(parameter),myTimeout);
    


    but that doesn’t work. An apparent solution (until tried in Internet Explorer) is:

    setTimeout(myFunction,myTimeout,parameter);
    

    It wasn’t as easy as I expected to find out how to get around this, but it turns out that all is needed is a “closure”:

    setTimeout(function(){myFunction(parameter)},myTimeout);
    

    Reference:                                                                                                      
    1. http://www.makemineatriple.com/2007/10/passing-parameters-to-a-function-called-with-settimeout

    Wednesday, April 27, 2011

    MySQL不支持INTERSECT和MINUS,及其替代方法

    Doing INTERSECT and MINUS in MySQL

    By Carsten | October 3, 2005

    Doing an INTERSECT

    An INTERSECT is simply an inner join where we compare the tuples of one table with those of the other, and select those that appear in both while weeding out duplicates. So

    SELECT member_id, name FROM a
    INTERSECT
    SELECT member_id, name FROM b

    can simply be rewritten to

    SELECT a.member_id, a.name
    FROM a INNER JOIN b
    USING (member_id, name)

    Performing a MINUS
    To transform the statement

    SELECT member_id, name FROM a
    MINUS
    SELECT member_id, name FROM b

    into something that MySQL can process, we can utilize subqueries (available from MySQL 4.1 onward). The easy-to-understand transformation is:

    SELECT DISTINCT member_id, name
    FROM a
    WHERE (member_id, name) NOT IN
    (SELECT member_id, name FROM table2);

    Of course, to any long-time MySQL user, this is immediately obvious as the classical use-left-join-to-find-what-isn’t-in-the-other-table:

    SELECT DISTINCT a.member_id, a.name
    FROM a LEFT JOIN b USING (member_id, name)
    WHERE b.member_id IS NULL

    Reference:                                                     
    1. http://blog.sina.com.cn/s/blog_4a9b80d00100b76s.html

    Kill a Process by Process Name from Ubuntu Command Line

    There are a number of ways to kill a process if you know the name of the process. Here’s a couple different ways you can accomplish this. We are going to assume that the process we are trying to kill is named irssi

        kill $(pgrep irssi)
    
        killall -v irssi
    
        pkill irssi
    
        kill `ps -ef | grep irssi | grep -v grep | awk ‘{print $2}’` 
    


    These techniques can be useful in shell scripts, where you wouldn’t know the process ID and would need to restart or kill a process.

    Reference:                                                      

    1. http://www.howtogeek.com/howto/ubuntu/kill-a-process-by-process-name-from-ubuntu-command-line/

    Tuesday, April 26, 2011

    Simple php multiple processes

    function fork()
    {
    $pid = pcntl_fork();
    if ($pid === -1) {
    // Error
    echo 'Process could not be forked';
    } else if ($pid) {
    // Parent
    echo 'pid of the child process:'.$pid."\n";
    } else {
    // Child
    sleep(30);
    }
    }
    
    fork();
    
    

    How to run a php file in terminal

    You can also create php scripts designed to run in the terminal like so:

    # php -f php-file.php
    
    


    1) Fire up a text editor and create your file, eg:

    #!/usr/bin/php
    // ^^ that line tells the command line that the file should be parsed by the php CLI interpreter
    echo "Hello terminal\n";  
    
    

    2) Give the script execute permissions:

    # chmod +x script.php
    
    

    3) Execute your script:

    # ./script.php
    Hello terminal
    
    


    This is all assuming you have the CLI version of PHP. FC installs this by default.



    Reference:                                                                                                      
    1. http://www.linuxquestions.org/questions/linux-software-2/can-i-run-php-trom-terminal-435783/

    Test code listing

    // Comment
    
    public class Testing {
    
    public Testing() {
    
    }
    
    public void Method() {
    
    /* Another Comment
    
    on multiple lines */
    
    int x = 9;
    
    }
    
    }
    
    

    /**
         * SyntaxHighlighter
         */
        public class HelloWorld extends ActionSupport {
       private String name;
       private String message;
    
       public String getName() {
         return name;
       }
    
       public void setName(String name) {
         this.name = name;
       }
    
       public String getMessage() {
        return message;
       }
       
       public void setMessage(String message) {
        this.message = message;
       }
       
       public String execute() {
        setMessage("Hello, " + getName());
        return "SUCCESS";
       }
    
    }
    

    Friday, April 22, 2011

    How to post well-formed code on Blogger ?

    Syntax Highlighting with Blogger Engine

    You can find a good solution here

    All the brushes available

    PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

    Problem:

    PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens


    Reason:

    The restrictions of PDO to the parameters bound are very strict, so you bind must exactly the same as that present in the query statement. No more parameter can be bound.