PHP 调试变量的代码

/** This function is used to debug variables during page execution
	* @param $what , the variable which need to debug,can be array or single variable
	* @param $more , to know the method and line number where that variable is used
	* @param $die , set TRUE if want to stop the page
	* how to use : debug::watch($postarray,1,1);
	* @author keshav mohta
	* @date Aug 12, 2010
	*/
class debug()
{
	static function watch($what,$more=FALSE,$die=FALSE)
	{
		$d = debug_backtrace();
		
		if($more && isset($d[1])) 
        {
         	echo "<br/>METHOD:".$d[1]['class']."::".$d[1]['function'];
            echo "<br/>LINE:".$d[0]['line'];
        }
		echo "<br/>";
		if( is_array($d[0]['args'][0]) || is_object($d[0]['args'][0]) )
		{
			echo "DATA:<pre>";
			print_r($d[0]['args'][0]);
			echo "</pre>";
		}
		else 
		{
			echo "Data:".$d[0]['args'][0];
		}			
		
		if($die)
		{
			echo "<br/>";
			die('ends here');
		}
		
	}
}

PHP 简单的MySQL包装PDO

<?php

// ------------------------------------------------------------------
// -                Database class'es				                -
// ------------------------------------------------------------------

	/**
	 *		Main database class
	 *			Works as a layer over PDO. Every static call is forwarded to the PDO object, except for those which are defined
	 *
	 **/

	class DB
	{
		protected static $DB;
		
		private function __construct()	{}
		private function __clone()		{}

		public static function connect($dbname='default', $host='localhost', $user='root', $password='')
		{
			try {
				// connects to the database
				self::$DB = new PDO("mysql:dbname=$dbname;host:=$host" , $user , $password);
				
				// set the error reporting attribute
				self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			}
			catch(PDOException $e) {
				echo $e->getMessage();
			}
		}
		
		public static function close_connection()
		{
			self::$DB = NULL;
		}
		
		public static function __callStatic($name, $arguments)
		{
			return forward_static_call_array(array(self::$DB, $name), $arguments);
		}
	}


	/**
	 *		A test class
	 *			Using SQLite with 'sqlite::memory:' so that its no need for username, password, etc
	 *			Perfect for quick testing purpose
	 *
	 **/

	class DBtest extends DB
	{
		public static function connect()
		{
			try {
				self::$DB = new PDO("sqlite::memory:");									// connect to database
				echo 'database created in memory <br /> <br />';						// only at debug mode - @TODO: remove it
				self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);		// set the error reporting attribute
			}
			catch(PDOException $e) {
				echo $e->getMessage();
			}
		}
	}

// ------------------------------------------------------------------
// -                Initilize a standard connection                 -
// ------------------------------------------------------------------


include 'config.php';

$dbh::connect(	$config['db']['default']['dbname'],
				$config['db']['default']['host'],
				$config['db']['default']['username'],
				$config['db']['default']['password']
			);

			
?>

PHP 根据WordPress中的用户角色显示/隐藏内容

<?php if (is_user_logged_in() ) { //only logged in user can see this ?>
<div><p>You are logged in!</p></div>
<?php } ?>

<?php if ( current_user_can( 'delete_others_posts' ) ) { //only admins and editors can see this ?>
   <p>You are an admin</p>
<?php } else { ?>
   <p>You are not an admin</p>
<?php } ?>

PHP Wordpress二级菜单子页面

<?php
    global $wp_query;
    if( empty($wp_query->post->post_parent) ) 
      {
         $parent = $wp_query->post->ID;
      } 
    else 
     {
         $parent = $wp_query->post->post_parent;
     } ?>
   
<?php if(wp_list_pages("title_li=&child_of=$parent&echo=0" )): ?>
    <ul class="submenus">
      <?php wp_list_pages("title_li=&child_of=$parent" ); ?>
     </ul>

<?php endif; ?>

PHP 自定义诊所分类标准下拉列表

/******* CUSTOM CLINIC TAXONOMY DROPDOWN *********/

function get_terms_dropdown($taxonomies, $args){
	$myterms = get_terms($taxonomies, $args);
	$firstitem = "<option value=\"\">Choose a clinic...</option><option value=\"about/providers\"><strong>* Show All Providers *</strong></option>";
	$output ="<select name=\"clinic\" onchange=\"window.open(this.options[this.selectedIndex].value,'_top')\" style=\"background:transparent;\">
		$firstitem";
	foreach($myterms as $term){
		$root_url = get_bloginfo('url');
		$term_taxonomy=$term->taxonomy;
		$term_slug=$term->slug;
		$term_name =$term->name;
		$link = $term_slug;
		$output .="<option value='clinic/".$link."'>".$term_name."</option>";
	}
	$output .="</select>";
return $output;
}

PHP 强制自定义模板选择

/******* FORCE CUSTOM TEMPLATE SELECTION *********/

function my_template_redirect()
{
global $wp;
if ($wp->query_vars["taxonomy"] == "clinic")
{
include(TEMPLATEPATH . "/taxonomy-clinic.php");
die();
}
}
add_action("template_redirect", 'my_template_redirect');

PHP WordPress:自定义子导航

<?php
	global $post; $thispage = $post->ID; // grabs the current post id from global and then assigns it to $thispage
	$subpages = get_pages("child_of=".$thispage."&sort_column=menu_order"); // gets a list of pages that are sub pages of $thispage and assigns it to $pagekids
?>

<?php if ($subpages) { // if there are any values stored in $pagekids, meaning there are sub-pages of the current page ?>

	<ul class="links">
		<?php wp_list_pages("depth=1&title_li=&sort_column=menu_order&child_of=".$thispage); // display ONLY the sub pages of the current page ?>
	</ul>

<?php } else { // $pagekids is empty ?>

	<ul class="links">
		<?php wp_list_pages('depth=1&title_li=&child_of='.$post->post_parent.'&sort_column=menu_order'); // display the sub-pages of the current parent page ?>
	</ul>

<?php } ?>

C# 简单的SQL Server差异工具

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;

namespace Sdiff
{
    internal class Program
    {
        /// <param name = "args">arg[0] old schema connection string, arg[1] target schema connection string</param>
        /// <summary>
        ///   Tells you what to do with old schema to get it into the shape of the new
        /// </summary>
        private static void Main(string[] args)
        {
            var diffs = new List<Diff>();

            var oldContext = new IsDataContext(args[0]);
            var newContext = new IsDataContext(args[1]);

            var newTableNames = newContext.Tables.Select(x => x.Name).ToList();
            var oldTableNames = oldContext.Tables.Select(x => x.Name).ToList();

            AddDiffs(diffs, oldTableNames.Except(newTableNames), DiffKind.TableDelete);
            AddDiffs(diffs, newTableNames.Except(oldTableNames), DiffKind.TableCreate);

            var commonTableNames = newTableNames.Intersect(oldTableNames);
            foreach (var tableName in commonTableNames)
            {
                var newColumns = newContext.Columns.Where(x => x.TableName == tableName).ToList();
                var oldColumns = oldContext.Columns.Where(x => x.TableName == tableName).ToList();

                var newColumnNames = newColumns.Select(x => x.FullName);
                var oldColumnNames = oldColumns.Select(x => x.FullName);

                AddDiffs(diffs, oldColumnNames.Except(newColumnNames), DiffKind.ColumnDelete);
                AddDiffs(diffs, newColumnNames.Except(oldColumnNames), DiffKind.ColumnCreate);

                var commonColumnNames = newColumnNames.Intersect(oldColumnNames);
                foreach (var commonColumnName in commonColumnNames)
                {
                    var newDataType = newColumns.Where(x => x.FullName == commonColumnName).Select(x => x.DataType).Single();
                    var oldDataType = oldColumns.Where(x => x.FullName == commonColumnName).Select(x => x.DataType).Single();
                    if (oldDataType != newDataType) diffs.Add(new Diff(commonColumnName + " " + oldDataType + " -> " + newDataType, DiffKind.ColumnDataTypeChange));
                }
            }

            WriteSection(diffs.Where(x => x.Kind == DiffKind.TableDelete), "Tables to delete");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.TableCreate), "Tables to create");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnDelete), "Columns to delete");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnCreate), "Columns to create");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnDataTypeChange), "Columns to modify");

            Console.ReadKey();
        }

        private static void AddDiffs(List<Diff> diffs, IEnumerable<string> names, DiffKind diffKind)
        {
            diffs.AddRange(names.Select(name => new Diff(name, diffKind)));
        }


        private static void WriteSection(IEnumerable<Diff> diffs, string title)
        {
            if (!diffs.Any()) return;
            Console.WriteLine();
            Console.WriteLine(title);
            Console.WriteLine(string.Empty.PadLeft(title.Length, '-'));
            foreach (var name in diffs.Select(x => x.Name).OrderBy(x => x))
            {
                Console.WriteLine(name);
            }
        }

        private class Diff
        {
            public Diff(string name, DiffKind kind)
            {
                Name = name;
                Kind = kind;
            }

            public string Name { get; private set; }
            public DiffKind Kind { get; private set; }
        }

        internal enum DiffKind
        {
            TableDelete,
            TableCreate,
            ColumnDelete,
            ColumnCreate,
            ColumnDataTypeChange
        }
    }


    public class IsDataContext : DataContext
    {
        public Table<Column> Columns;
        public Table<Table> Tables;
        public IsDataContext(string connection) : base(connection) {}
    }

    [Table(Name = "INFORMATION_SCHEMA.TABLES")]
    public class Table
    {
        [Column(Name = "TABLE_NAME")] public string Name;
    }

    [Table(Name = "INFORMATION_SCHEMA.COLUMNS")]
    public class Column
    {
        [Column(Name = "CHARACTER_MAXIMUM_LENGTH")] public int? CharacterMaximumLength;
        [Column(Name = "DATA_TYPE")] public string DataTypeName;
        [Column(Name = "COLUMN_NAME")] public string Name;
        [Column(Name = "TABLE_NAME")] public string TableName;

        public string DataType
        {
            get
            {
                if (!CharacterMaximumLength.HasValue) return DataTypeName;
                if (CharacterMaximumLength.Value == -1) return DataTypeName + "(MAX)";
                return DataTypeName + "(" + CharacterMaximumLength.Value + ")";
            }
        }

        public string FullName { get { return TableName + "." + Name; } }
    }
}

Ruby 正则表达式在Ruby中创建URL排列

# return 4 urls, with and without trailing slash, with and without www
# useful for matching urls passed as params into some function,
# "does this url exist?"... need to make sure you check permutations
def url_permutations(url)
  url, params = url.split("?")
  # without_trailing_slash, with www
  a = url.gsub(/\/$/, "").gsub(/http(s)?:\/\/([^\/]+)/) do |match|
    protocol = "http#{$1.to_s}"
    domain = $2
    domain = "www.#{domain}" if domain.split(".").length < 3 # www.google.com == 3, google.com == 2
    "#{protocol}://#{domain}"
  end
  # with_trailing_slash, with www
  b = "#{a}/"
  # without_trailing_slash, without www
  c = a.gsub(/http(s)?:\/\/www\./, "http#{$1.to_s}://")
  # with_trailing_slash, without www
  d = "#{c}/"
  
  [a, b, c, d].map { |url| "#{url}?#{params}"}
end

puts url_permutations("http://google.com/search?q=http://google.com").inspect
#=> [
  "http://www.google.com/search?q=http://google.com",
  "http://www.google.com/search/?q=http://google.com",
  "http://google.com/search?q=http://google.com",
  "http://google.com/search/?q=http://google.com"
]

JavaScript 添加前导零

/* EXAMPLE

document.write(addLeadingZeros([1,2,3,4,5,6,7,8,9,10]));

*/

function addLeadingZeros(array) {
	
	var highestInt = Math.max.apply(Math,array);
	
	for(var i=0; i<array.length; i++) {
		
		var nLeadingZeros =  highestInt.toString().length - array[i].toString().length;
		
		for(var j=0; j<nLeadingZeros; j++) array[i] = '0' + array[i];
	}
	
	return array;
}