XML copyOuterHTML

<xsl:template name="copyOuterHTML">
   <xsl:element name="{name()}">
      <xsl:apply-templates select="@* | * | text()" />
   </xsl:element>
</xsl:template>

ActionScript 保萨

this.createEmptyMovieClip("timer",50);
timer.onEnterFrame = function()
{
        if (this.startTime>0)
        {
                var diff = getTimer()-this.startTime;
                if (diff>this.timerLength)
                {
                        this.target.play();
                        this.startTime = 0;
                }
        }
};
function pauseFor(theTime)
{
        stop();
        timer.timerLength = (theTime*1000);
        timer.startTime = getTimer();
        timer.target = this;
}

PHP CakePHP - 通过小部件助手进行邮件查看

<?php
/**
 * Mail Templates
 * Sends email through a view
 *
 * The templates rendered must have extension .mail
 *
 * Uses:
 * @link http://phpmailer.sourceforge.net/
 * @see MailWidgetHelper
 *
 * @author RosSoft
 * @version 0.1
 * @license MIT
 *
 *
 * Usage example:
 * First, edit this file and change the define(’CONFIG_SMTP…
 * with your ISP config.
 *  
 * file views/foo/mail_view.mail
        <m:from name=”Miguel Ros” mail=”rosmiguel@teleline.es” />
        <m:to>
            rossoft@gmail.com
        </m:to>
       
        <m:to>
            rosmiguel@teleline.es
        </m:to>
       
        <m:subject> Hi! That is the subject
        </m:subject>
       
        <m:body_text>
        This is the plain body text
        </m:body_text>
       
        <m:body_html>
        This is the HTML <b>Body</b>
        </m:body_html>
       
        <m:attach path=”/tmp/test1.txt” name=”test_file_1.txt” />
        <m:attach path=”/tmp/test2.txt” />
    File views/foo/mail_view.thtml:
        The mail has been set
    Action in FooController:
        function mail_view()
        {
            $this->view=’Mail’;
             $this->render(); //render the mail_view.mail
        
             $this->view=’View’;
             $this->render(); //now the mail_view.thtml renders
         }                       
 
 */
 
define(’CONFIG_SMTP_HOST’,'xxxx’);
define(’CONFIG_SMTP_USER’,'yyyy’);
define(’CONFIG_SMTP_PASS’,'zzzz’);

//Directory within VENDORS/
define(’PHPMAILER_SUBDIR’,'phpmailer’ . DS);     

class MailView extends View
{
    var $mail=null; //instance of MailAux
       
    function render($action = null, $layout = null, $file = null)
    {       
        $this->mail=& new MailAux;
        $this->controller->mail=& $this->mail;
           
        $file=null;      
       
        $this->load_helper(’MailWidget’);
       
        if ($action==NULL)
        {
            $action=$this->action;
        }
        $file=$this->get_filename($action,’.mail’);
        ob_start();       
        parent::render($action,$layout,$file);
        ob_get_clean();
        return $this->mail->send();       
    }   

    /**
     * Adds a helper to the helpers array for loading it
     * @param string $helper Name of the helper like ‘Javascript’
     */   
    function load_helper($helper)
    {
        if (!in_array($helper,$this->helpers))
        {
            $this->helpers[]=$helper;
        }
    }
   
    /**
     * Returns the filename associated with the action
     * with the extension “.$ext”
     *
     * @param string $action If null, then current action
     * @param string $ext Extension of the view template (with dot) Example: ‘.xml’
     * @return string
     */
    function get_filename($action,$ext)
    {       
        $old_ext=$this->ext;
        $this->ext=$ext;
        $fn=$this->_getViewFileName($action);
        $this->ext=$old_ext;
        return $fn;
    }
   
}

/**
 * This object is the interface between MailView and MailWidgetHelper
 */
class MailAux extends Object
{
    var $charset=’utf-8′;
   
    var $from_mail=null;
    var $from_name='’;
    var $to=array();
    var $subject='’;
    var $body_text=null;
    var $body_html=null;   
    var $attachments=array();

    /**
     * SMTP Configuration
     */   
    var $host=CONFIG_SMTP_HOST;
    var $username=CONFIG_SMTP_USER;
    var $password=CONFIG_SMTP_PASS;

    /**
     * It contains mailer error message or false if no
     * error has occurred
     */   
    var $error=false;
   
   
    function send()
    {       
        vendor(PHPMAILER_SUBDIR. ‘class.phpmailer’);
        $mail = new PHPMailer();
        $mail->PluginDir = VENDORS .PHPMAILER_SUBDIR ;
        $mail->SetLanguage(’en’,VENDORS .PHPMAILER_SUBDIR . ‘language’ . DS);
               
        $mail->CharSet= $this->charset;       
        $mail->IsSMTP();                  // send via SMTP
        $mail->Host     = $this->host; // SMTP servers
        if ($this->username !==null)
        {
            $mail->SMTPAuth = true;     // turn on SMTP authentication
            $mail->Username = $this->username;  // SMTP username
            $mail->Password = $this->password; // SMTP password           
        }       
        $mail->From = $this->from_mail;   
        $mail->FromName = $this->from_name;
        foreach ($this->to as $address)
        {           
            $mail->AddAddress($address);           
        }
        $mail->Subject  =  $this->subject;
        if ($this->body_html)
        {
            $mail->IsHTML(true); // send as HTML       
            $mail->Body     =  $this->body_html;
            $mail->AltBody  =  $this->body_text;
        }
        else
        {
            $mail->IsHtml(false);
            $mail->Body        =  $this->body_text;
        }
        //$mail->WordWrap = 50;                              // set word wrap
        foreach ($this->attachments as $attach)
        {
            $mail->AddAttachment($attach[’path’],$attach[’name’],’base64′,$attach[’type’]);
           
        }       
        if (! $mail->Send())
        {
            $this->error=$mail->ErrorInfo;
            $this->log(’Mail send:’ . $mail->ErrorInfo);
            return false;           
        }
        else
        {
            $this->error=false;
            return true;
        }
                               
    }
}
?>

Copy to app/views/helpers/mail_widget.php

<?php
/**
 * MailWidgetHelper
 *
 * For usage with MailView
 *
 * @author RosSoft
 * @version 0.1
 * @license MIT
 */
 
class MailWidgetHelper extends WidgetHelper
{   
    var $tag=array(    ‘m:from’,
                    ‘m:to’,
                    ‘m:subject’,
                    ‘m:body_text’,
                    ‘m:body_html’,
                    ‘m:attach’);

    /**
     * m:from (Mail From)
     * $attr[’mail’] Mail
     * $attr[’name’] Name (optional)
     */   
    function tag_m_from($attr,$inner_html)
    {
        $this->view->mail->from_name=@$attr[’name’];
        $this->view->mail->from_mail=@$attr[’mail’];
    }

    /**
     * m:to (Mail To)
     * $inner_html Destination address
     */   
    function tag_m_to($attr,$inner_html)
    {
        $this->view->mail->to[]=$this->_trim($inner_html);
    }
   
    /**
     * m:subject (Mail Subject)
     * $inner_html The subject
     */
    function tag_m_subject($attr,$inner_html)
    {
        $this->view->mail->subject=$this->_trim($inner_html);
    }
   
    /**
     * m:body_text  Body in plain text
     * $inner_html The body
     */
     function tag_m_body_text($attr,$inner_html)
     {
         $this->view->mail->body_text=$inner_html;
     }
       

    /**
     * m:body_html Body in html text
     * $inner_html The body
     */
     function tag_m_body_html($attr,$inner_html)
     {
         $this->view->mail->body_html=$inner_html;
     }

    /**
     * m:attach Adds an attachment
     * $attr[’path’] The path of the file
     * $attr[’name’] Overrides the attachment name
     * $attr[’type’] MIME type
     */
     function tag_m_attach($attr,$inner_html)
     {
         $path=$attr[’path’];
         $name=($attr[’name’])? $attr[’name’] : ‘’;
         $type=($attr[’type’])? $attr[’type’] : ‘application/octet-stream’;
        
         $this->view->mail->attachments[]=array(    ‘path’=>$path,
                                                 ‘name’=>$name,
                                                 ‘type’=>$type);
     }

     /**
      * Removes the spaces, tabs, newlines from
      * the beginning and ending of the string
      * @param string $string
      * @return string
      */     
     function _trim($string)
     {
         preg_match(’/^[\n\t\s]*(.*)[\n\t\s]*$/’,$string,$matches);
         return $matches[1];        
     }

}
?>

Java Arrays.deepToString()

String[][] ticTacToe = { {"X", "O", "O"},

                            {"O", "X", "X"},

                            {"X", "O", "X"}};

   System.out.println(Arrays.deepToString(ticTacToe));

JavaScript 迭代节点删除

function killsChildNodes(an_element) {
	while (an_element.hasChildNodes()) {
		if (!an_element.firstChild.hasChildNodes()) {
			var k = an_element.firstChild;
			an_element.removeChild(k);
		} else {
			killsChildNodes2(an_element.firstChild);
		}
	}
}
function killsChildNodes2(another_element) {
	while (another_element.hasChildNodes()) {
		if (!another_element.firstChild.hasChildNodes()) {
			var k2 = another_element.firstChild;
			another_element.removeChild(k2);
		} else {
			killsChildNodes(another_element.firstChild);
		}
	}
}
function killAllChildNodesFrom(bob) {
	if(document.getElementById(bob).hasChildNodes()) {
		killsChildNodes(document.getElementById(bob));
	}
}
function killFirstChildNodeFrom(bob) {
	if(document.getElementById(bob).hasChildNodes()) {
		killsChildNodes(document.getElementById(bob).firstChild);
		document.getElementById(bob).removeChild(document.getElementById(bob).firstChild);
	}
}
function killLastChildNodeFrom(bob) {
	if(document.getElementById(bob).hasChildNodes()) {
		killsChildNodes(document.getElementById(bob).lastChild);
		document.getElementById(bob).removeChild(document.getElementById(bob).lastChild);
	}
}

PHP PHP文本日志

#This is the message that will be added to the text file"
$linefeed ="\n\n\n-------\n\n\n" ;// Determines what separates each entry. 

$fileloc ="d:\path\to\log.txt" ;// Absolute path to the text file 
$handle =fopen ($fileloc ,'a' ); // Use 'a' to add to the end of the file, 'w' for the beginning 
fputs ($handle ,$emailBody ); // The message variable is whatever you want to add 
fputs ($handle ,$linefeed ); // Adds the linefeed 
fclose ($handle ); // Closes the file

Ruby 随机ASCII字符生成器

require 'enumerator'

def random_string(length=10, s="")
  length.enum_for(:times).inject(s) do |result, index|
    s << rand(93) + 33 
  end
end

PHP 带有域名的Cookie包装器

class Cookie
{
   var $__setting;

   function __construct($name = 'FuseLogic',$live = 31104000)
   {
      $this->__setting = new open();
      $this->__setting->name = $name;
      $this->__setting->_cookies = array();
      $this->__setting->space = '___';

      $this->setDomain();
      $this->setPath();
      $this->setLive($live);

      if(is_array($_COOKIE))
      {
         foreach($_COOKIE as $k =>$v)
         {
            $temp = explode($this->__setting->space,$k);
            if($temp[0] == $this->__setting->name)
            {
               $k = str_replace($this->__setting->name.$this->__setting->space,'',$k);
               $this->__setting->_cookies[$k] = $v;
            }
         }
      }
   }
    
   function setDomain($domain = '')
   {
      $this->__setting->domain = $domain;
   }

   function setLive($time = 3600)
   {
      $this->__setting->live = (int) $time;
   }

   function setPath($path = '/')
   {
      $this->__setting->path = $path;
   }

   function name($name = null)
   {
      return $this->__setting->name.$this->__setting->space.$name;
   }

   public function __get($name)
   {
      return $this->__setting->_cookies[$name];
   }
  
   public function __set($name,$value)
   {
      $this->__setting->_cookies[$name] = $value;
      $name = $this->name($name);
      $_COOKIE[$name] = $value;
      if($value == null)
      {
         setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
      }else
      {
         setcookie($name,$value,time()+$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
      }
   }

   public function __isset($name)
   {
      return isset($this->__setting->_cookies[$name]);
   }

   function clean()
   {
      foreach($this->__setting->_cookies as $name => $value)
      {
         $name = $this->name($name);
         setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
         @$_COOKIE[$name] = null;
      }
      $this->__setting->_cookies = array();
   }

   function cleanAll()
   {
      foreach($_COOKIE as $name => $value)
      {
         setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
      }
      @$_COOKIE = array();
   }

   function toArray()
   {
      return $this->__setting->_cookies;
   }

   function fromArray($a = null)
   {
      if(is_array($a))
      {
         foreach($a as $k => $v ) $this->$k = $v;
      }
   }

}

PHP PHP函数示例

/*
Título:     Explicación de funciones (básica)
Autor:         Angel Velásquez (a.k.a angvp)
E-Mail:        angelvelasquez@gmail.com
Web:        http://www.anacosoft.com
Fecha:         02/01/2006
Licencia:     Creative Commons j/k (BAHHH GNU MY FRIEND!)
======================================================
Las funciones usualmente son pequeñas partes de un script usadas para devolver resultados, ¿Lógico no?, pero la idea es que entiendan el correcto uso de las mismas.

*/

function holamundo() {
    return "Hola Mundo!";
}
/*
Esa es la clásica Hola Mundo, ahora llevada a función (es como inútil una función tan corta), aunque en cierto y sólo ciertos casos, nos ahorraría mucho para ahorrar código, pero, este no es el caso, el caso es que a esta función no hay que pasarle parámetros para que se ejecute, con sólo poner echo holamundo(); se verá reflejado en pantalla "Hola Mundo!".
*/
function holamundov2($nombre) {
    $var = "Hola $nombre . Bienvenido al mundo!";
    return $var;
}

/*
 Para ejecutar esa función se requiere pasarle un parámetro, su correcta ejecución sería así:
 echo holamundov2("Pepe"), como salida obtendríamos Hola Pepe . Bienvenido al mundo!.
 
 Bien, no siempre las funciones dependen de parámetros, o podemos decirle que sino le pasamos un parámetro, ella misma lo declare, ¿Cómo?, muy sencillo, en el próximo ejemplo, lo veremos.
*/

function holamundov3($nombre = "Pepe") {
    $var = "Hola $nombre . Bienvenido al mundo!";
    return $var;
}

/*
En el caso de holamundov3, es distinto, la función comprueba si se le pasó un parámetro, en caso de no haberse pasado un parámetro ($nombre), ella asignará automáticamente, Pepe, también es útil, la idea de hacer funciones es hacer funciones genéricas que nos ahorren trabajo, no hacer mil funciones personalizadas (aunque sea más fácil).

FAQ:
====
1.- Q: Si pongo echo en vez de return también funciona...
    A: Si, funciona, pero y si quieres guardar el resultado en una variable y luego concatenarlo con otra cosa.. unuseful...
2.- Q: ¿Tengo que poner siempre return?
    A: Sí, si vas a usar una función con condiciones te recomiendo que guardes el resultado de la condición positiva o negativa en una variable (con el mismo nombre) ejemplo:
   
    function holamundov4($nombre = "Pepe") {
        if ($nombre == "Pepe") {
            $var = "Hola Mundo!";
        }
        else {
            $var = "Hola $nombre . Bienvenido al mundo!";
        }
        return $var;
    }
   
Enjoy the tutorial, sorry que no fui más específico

Angel
*/

PHP smart_trim

#################################################
####
#### smart_trim
#### This function trims a string to a specified length.
#### Words are separated by space characters, and they are not
#### chopped if possible.
#### 
#### @package smart_trim
#### @author  Michael Gauthier <mike@silverorange.com>
#### silverorange
#### labs.silverorange.com
#### 
#### Copyright (c) 2003, silverorange Inc.
#### All rights reserved.
#### 
#### Redistribution and use in source and binary forms, with or without modification,
#### are permitted provided that the following conditions are met:
#### 
####     * Redistributions of source code must retain the above copyright notice, this
####       list of conditions and the following disclaimer.
####     * Redistributions in binary form must reproduce the above copyright notice,
####       this list of conditions and the following disclaimer in the documentation
####       and/or other materials provided with the distribution.
####     * Neither the name of silverorange Inc. nor the names of its contributors may
####       be used to endorse or promote products derived from this software without
####       specific prior written permission.
#### 
#### THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#### ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#### WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#### IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
#### INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
#### BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#### DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#### LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
#### OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
#### OF THE POSSIBILITY OF SUCH DAMAGE.
#### 
#################################################

/**
 * Trim the string.
 *
 * @param  string  $text        The line to trim.
 * @param  integer $max_len     The maximum length of the trimmed line.
 *                              This ignores the length of the characters
 *                              that indicate trimming has occured.
 * @param  boolean $trim_middle Trimming takes place in the middle of the line
 *                              iff true. Otherwise, the line is trimmed at the
 *                              end. Defaults to false.
 * @param  string  $trim_chars  Characters to use to indicate trimming has
 *                              occured. Defaults to '...'.
 *
 * @return string               The trimmed line of text.
 */
function smart_trim($text, $max_len, $trim_middle = false, $trim_chars = '...')
{
	$text = trim($text);

	if (strlen($text) < $max_len) {

		return $text;

	} elseif ($trim_middle) {

		$hasSpace = strpos($text, ' ');
		if (!$hasSpace) {
			/**
			 * The entire string is one word. Just take a piece of the
			 * beginning and a piece of the end.
			 */
			$first_half = substr($text, 0, $max_len / 2);
			$last_half = substr($text, -($max_len - strlen($first_half)));
		} else {
			/**
			 * Get last half first as it makes it more likely for the first
			 * half to be of greater length. This is done because usually the
			 * first half of a string is more recognizable. The last half can
			 * be at most half of the maximum length and is potentially
			 * shorter (only the last word).
			 */
			$last_half = substr($text, -($max_len / 2));
			$last_half = trim($last_half);
			$last_space = strrpos($last_half, ' ');
			if (!($last_space === false)) {
				$last_half = substr($last_half, $last_space + 1);
			}
			$first_half = substr($text, 0, $max_len - strlen($last_half));
			$first_half = trim($first_half);
			if (substr($text, $max_len - strlen($last_half), 1) == ' ') {
				/**
				 * The first half of the string was chopped at a space.
				 */
				$first_space = $max_len - strlen($last_half);
			} else {
				$first_space = strrpos($first_half, ' ');
			}
			if (!($first_space === false)) {
				$first_half = substr($text, 0, $first_space);
			}
		}

		return $first_half.$trim_chars.$last_half;

	} else {

		$trimmed_text = substr($text, 0, $max_len);
		$trimmed_text = trim($trimmed_text);
		if (substr($text, $max_len, 1) == ' ') {
			/**
			 * The string was chopped at a space.
			 */
			$last_space = $max_len;
		} else {
			/**
			 * In PHP5, we can use 'offset' here -Mike
			 */
			$last_space = strrpos($trimmed_text, ' ');
		}
		if (!($last_space === false)) {
			$trimmed_text = substr($trimmed_text, 0, $last_space);
		}
		return remove_trailing_punctuation($trimmed_text).$trim_chars;

	}

}

/**
 * Strip trailing punctuation from a line of text.
 *
 * @param  string $text The text to have trailing punctuation removed from.
 *
 * @return string       The line of text with trailing punctuation removed.
 */
function remove_trailing_punctuation($text)
{
	return preg_replace("'[^a-zA-Z_0-9]+$'s", '', $text);
}