Sunday, December 29, 2013

Summary of file and directory operation in PHP



1) File Operation in PHP

There are a lot of functions in PHP to do file and directory operations, such as
fopen, fwrite, fread, fcolse, file_put_contents, file_get_contents,
For example fopen is used to open a file, fread to read from a file and fclose to close file handler.
code example:
if($handle=fopen(test.txt','r')){
   $content=fread($handle);
    fclose($handle);
}
//change file line break to HTML line break: nl2br
echo nl2br($content);

We can also read and get line by line from a file using fgets
code example
if($handle=fopen(test.txt','r')){
     while(1feof($handle)(
          $content=fgets($handle);
       echo $content."<br />";
      }
fclose($handle);
}
Other functions related to file operation: filesize: file size
filemtime: modified time (change content)
filectime: changed time (change content or metadata such as chmod)
fileatime: last access time such as read  or change.
touch($filename): update file time.

code example:
echo strftime('%m/%d/%Y %H%M',  filemtime($filename))."<br />";


2) Directory operation in PHP

To get current working directory: getcwd
create a new directory: mkdir
Example
makdir('mydir','0777'); //note permission  may be overwritten by umask
makdir('mydir/dir1/dir2','0777',true);recursively create new directoy

change directory chdir
remove a directory: rmdir
is_dir: to check if it is a directory
opendir: open directory to get directory handler
readdir: to get each file in a directory
Example:
if($mydir=opendir('test')){
    while($filename=readdir($mydir))
        echo $filename.'<br />';
}

Close directory: closedir
scandir:  read all file names in the directory into an array
Example:
$file_array=scandir('test');
foreach($file_array as $filename) 
       echo $filename.'<br />';
To remove .  and .. in the array which may appear when we scan directory , we can add
if(stripos($filename, '.')>0) // i.e first occurrence of  '.' not the first position.

Friday, December 20, 2013

Transfer your CSS to cross browser compatible using prefixr



For example, for linear gradient from top to bottom for background in CSS (no browser supports linear gradients using only this standard syntax)
background: linear-gradient(red, blue);

I have to write four other CSS rules for each of these for the different browsers.
 /* For Safari and Chrome */
 background: webkit-linear-gradient(red, blue);
 /* For Firefox */
background: -moz-linear-gradient(red, blue);
/*for Opera */
background: -o-linear-gradient(red, blue);

/* For Microsoft Internet Explorer */
background: -ms-linear-gradient(red, blue);


 
It is quite time consuming to write all these CSS rules for different browsers. We can use prefixr website:
 http://prefixr.com/
 In the input box, you paste
background: linear-gradient(red, blue);
then click Prefixize button, you can get
background: -webkit-linear-gradient(red, blue);
background: -moz-linear-gradient(red, blue);
background: -o-linear-gradient(red, blue);
background: -ms-linear-gradient(red, blue);
background: linear-gradient(red, blue);

You can save a lot of time for  writing your CSS scripts.

Thursday, December 19, 2013

Add spellcheck plugin in Notepad++ in Windows 7



 Notepad++ is an advanced free source editor, which can be downloaded from
http://notepad-plus-plus.org/
To add spellcheck plugin in Notepad++ in Windows 7
1) Go to
http://aspell.net/win32/
find Full installer  and English    aspell-en-0.50-2-3.exe and install
http://ftp.gnu.org/gnu/aspell/w32/Aspell-0-50-3-3-Setup.exe
http://ftp.gnu.org/gnu/aspell/w32/Aspell-en-0.50-2-3.exe
2) Add path
 ;C:\Program Files (x86)\Aspell\bin
detail steps:
- Right click on "computer" in the Windows start menu; choose properties
- Click on "Change Settings" at the bottom right of the pop up window
- Click on the new dialog's "advanced" tab
- At the bottom, there is an "Environment Variables…" button, click it.
- In the second section (System Variables)  scroll down until you see "Path"; select it.
- Click the "Edit…" button
- On the end of the text line add:
   ;C:\Program Files (x86)\Aspell\bin
 Video: Add spellcheck plugin in Notepad++ in Windows 7

Wednesday, December 18, 2013

CSS, difference between child selector and descendant selector



In CSS, what is difference between "li > a" and "li a"?
">" is the child selector, only for child level from parent, not grandchildren,
"" is the descendant selector, can be children, grandchildren and more.
Example 1
<foo> <!-- parent -->
  <bar> <!-- child of foo, descendant of foo -->
    <baz> <!-- descendant of foo -->
    </baz>
  </bar>
</foo>
Example 2
CSS
li a{ color: green; }
li>a{ color: red; }
 

HTML code 1
<ul>
  <li><span><a href='#'>HERE</a></span></li>
</ul>

 "HERE" will display as green due to that it is grandchild not child of li, CSS "li>a" will not apply.

HTML code2
<ul>
  <li><a href='#'>HERE</a></li>
</ul>
  "HERE" will display as red due to that it is both descendant and child of li, both CSS "li>a" and "li a" will  apply.

Monday, December 16, 2013

Manage all your passwords using keepass open source software



There are too many passwords need to be remembered. You may struggle to remember banking, email, Internet and PC computer passwords. You may need to manage all your passwords using a single master password. You can use keepass.  KeePass is a  free open source password manager, which can be downloaded from here:
 http://keepass.info/download.html
KeePass is a free, open source, light-weight and easy-to-use password manager for Windows, Linux, Mac OS X and mobile devices. You can store your passwords in a highly-encrypted database, which is locked with one master password or key file.

In Apple store, the application is called minikeepass for free download. You can import and export secure password database  iPhone  to dropbox  to synchronize to your local Windows PC.
Video:  Manage all your passwords using keepass open source software

Wednesday, December 11, 2013

jQuery mobile example



jQuery mobile is a web framework to build mobile websites using HTML5 and CSS3.
Reference:
http://jquerymobile.com/
http://www.w3schools.com/jquerymobile/jquerymobile_examples.asp

Example code
1) Call jQuery library:
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
2) Call  jQuery mobile library
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
3)  Using jQuery mobile CSS
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
4) Define viewport for mobile
<meta name="viewport" content="width=device-width, initial-scale=1">
5) Define a header
<div data-role="header">
    <h4>jQuery Mobile  </h4>
  </div>

6) Define page content
 <div data-role="content"></div>
7) Define footer
 <div data-role="footer">
    <h4>&copy; 2013 Jiansen Lu</h4>
  </div>

8) complete example1.html
<!DOCTYPE html>
<html>
<head>
 <title>jQuery Mobile code example</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div data-role="page" id="pageone">
  <div data-role="header">
    <h4>jQuery Mobile  </h4>
  </div>

  <div data-role="content">
     <ul data-role="listview" data-inset="true" data-dividertheme="b">
                     <li data-role="list-divider">Options</li>
                     <li><a href="menu.html">Food menu</a></li>
                     <li><a href="">Location</a></li>
                     <li><a href="">Search Nearby</a></li>
                     <li><a href="">Contact us</a></li>
               </ul>          
  </div>

  <div data-role="footer">
    <h4>&copy; 2013 Jiansen Lu</h4>
  </div>
</div>

</body>
</html>

9) The link menu.html
<!DOCTYPE html>
<html>
<head>
 <title>Food Menu</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div data-role="page" id="home" data-theme="c">
<div data-role="content">
<div id="branding">
<h1>Food  Menu </h1>
</div>
<div class="choice_list">
<ul data-role="listview" data-inset="true" >
<li><a href="" data-transition="slidedown"> <img src="seaweedtofu.JPG"/> <h3> Sea Weed ToFu </h3></a></li>
<li><a href="" data-transition="slidedown"> <img src="shrimpdumpling.JPG"/> <h3> Shrimp Dumpling </h3></a></li>
<li><a href="" data-transition="slidedown"> <img src="boiledegg.JPG"/> <h3> Boiled Eggs</h3></a></li>
<li><a href="" data-transition="slidedown"> <img src="Congee.JPG"/> <h3> Congee</h3></a></li>
<li><a href=" " data-transition="slidedown"> <img src="snowpeas.JPG"/> <h3> Snow Peas </h3></a></li>
</ul>
</div>
</div>
</div><!-- /page -->
</body>
</HTML>

10) Demo page:
http://swf.site40.net/jquerymobile/example1.html

Password protected your Microsoft Word 2010 and EXCEL document


In Microsoft Word and Excel, there is a feature to encrypt your document and set password protected.
In  Microsoft Word 2010 and EXCEL document:
1) Go to file tab and Click Info
2) Click "Protect Document", a menu pop-up, select  second "Encrypt with Password"
3) Type your password, after "Confirm Password", type the same password again.

Now your  Microsoft Word  and EXCEL document  are password protected.

Tuesday, December 10, 2013

Remove bettersurf ads program in Windows 7



Bettersurf plus (better surf, ads by bettersurf) is an ads program installed in your local computer. It will display ads in your browser with double underline under text. To remove bettersurf plus in Windows 7.  Click start and click control panel,  click "uninstall a program" under programs. Find program name "BetterSurf Plus", right click mouse and uninstall program.After bettersurf plus  ads program is uninstalled, Firefox will restart.

Video: Remove bettersurf ads program in Windows 7

Monday, December 9, 2013

Design two side-by-side divs in CSS



Left div contains video or image, right div contains questions in quiz.
Left div, I used "width:60%;" and "float:left";
Right div, I use "width:35%;" and "float:right";
So the distance between two divs is 5%,
Final code:
<div style="display:block; width:60%;  overflow:auto;float: left;" > </div>
<div style="display:block; width:35%; height: 800px; overflow:auto; float: right;" ></div>

Thursday, December 5, 2013

modernizr JavaScript library: detect mobile, CSS3 and HTML5 features in user browser.



We can use  server-side useragent to detect browser type:

Example code to show browser type using  useragent
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.write(navigator.userAgent);
}
</script>

The userAgent property returns the value of the user-agent header sent by the browser to the server.

But a lot of time, we need to detect the specific features of   mobile, CSS3 and HTML5 rather than browser type. modernizr  JavaScript library is a client-side script to detect  mobile, CSS3 and HTML5 features in user browser.  modernizr  JS library can be downloaded from:
http://modernizr.com/
To use   modernizr JavaScript librar:
<script src="modernizr-1.7.js" type="text/javascript"></script>
test for geolocation  feauter
Modernizr.geolocation  will return true or false.
test for touch feauture
Modernizr.touch
Test for HTML5 feature
Modernizr.svg
Modernizr.canvas
local storage
Modernizr.localstorage
and more 

HTML5 boilerplate:
http://html5boilerplate.com/mobile/ 

Wednesday, December 4, 2013

Emulators for Windows Phone, for Android, and for Opera Mobile



You may want to test your web design codes in all mobile devices. Below is how to install emulators  for Windows Phone, for Android, and for Opera Mobile (iphone).

1) Install emulators for Windows Phone:
Download  Windows Phone SDK from:
http://dev.windowsphone.com/en-us/downloadsdk
And installing Windows Phone SDK ,  the Windows Phone Emulator can  be found under the Windows Phone Developer tools.

2)  Install emulators for Android:
Download Android SDK from:
http://developer.android.com/sdk/index.html

3) Install Opera mobile emulator:
Download Opera mobile emulator from:
http://www.opera.com/developer/mobile-emulator

Tuesday, December 3, 2013

Responsive web design--sliding and swiping through pages on iphone and ipad using swipejs JavaScript library



In responsive web design, you may need to move the content with your fingers in mobile phones.
SwipeJs is a JavaScript library for touch-enabled mobile slider, which can be downloaded from:
https://github.com/bradbirdsall/Swipe/
The company website:
 http://swipejs.com/
My demo:
http://www.jiansenlu.zoka.cc/swipemaster/

To use this code,  jquery library and swipe.js are called.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src='swipe.js'></script>

swipe.js uses touch events for mobile instead of mouseclick in desktop.

Apples event object for touch events

The event object contains the following arrays:
  • touches - contains touch information upon touchStart and touchMove not touchEnd events
  • targetTouches - contains information for touches originating from the same target element
  • changedTouches - contains touch information upon all touch events
 Reference:
 http://www.javascriptkit.com/javatutors/touchevents.shtml

We can detect a swipe (left, right, top or down) using event.touch:
http://www.javascriptkit.com/javatutors/touchevents2.shtml

There are several other JavaScript libraries related to swipe feature in mobile phone:
1. http://swipeplanes-jquery.blogspot.com/
2. http://cubiq.org/iscroll-4/
3. dragend JS is another good option.
http://stereobit.github.io/dragend/
4. http://www.jqtouch.com/
5. SwipeView
works both for desktop and tablet/mobile


Friday, November 29, 2013

Increase MySQL SELECT speed in complicated statement



I have following MySQL statement using 4 SELECT loops:
  $sql = "SELECT subject_id,study_code,active,reminders FROM subjects WHERE subject_id IN(
               SELECT subject_id FROM review_slot_subjects WHERE review_slot_id
                  IN (SELECT review_slot_id FROM review_slots WHERE project_id=$pid AND review_slot_id
                     IN (SELECT review_slot_id FROM review_slot_reviewers WHERE member_id=$rid))) ORDER BY study_code";
      $result = mysql_query($sql, $db);

It takes  about 2 minutes to finish execution.
Change the MySQL statement into two steps: one is three SELECT, another one SELECT
//step 1
$sql = "SELECT subject_id FROM review_slot_subjects WHERE review_slot_id
                  IN (SELECT review_slot_id FROM review_slots WHERE project_id=$pid AND review_slot_id
                     IN (SELECT review_slot_id FROM review_slot_reviewers WHERE member_id=$rid))";
        $result = mysql_query($sql, $db);
       $subject_id_array=array();
    while($row = mysql_fetch_assoc($result))  $subject_id_array[]=$row['subject_id'];
 //step 2
    $matches = implode(',',$subject_id_array);        
    $sql = "SELECT subject_id,study_code,active,reminders FROM subjects WHERE subject_id IN(
               $matches) ORDER BY study_code";
      $result = mysql_query($sql, $db);


The MySQl execution time is reduced to few seconds.

Tuesday, November 26, 2013

Mac OSX Snow Leopard 10.6.3 CD in Virtual Box in Windows 7



Read some articles about install Mac OSX Snow Leopard 10.6.3 in Virtual Box in Windows 7 using official CD. And make some summary:
1)iboot.iso  from
http://www.tonymacx86.com/downloads.php?do=cat&id=3
2) Oracle VM Virtual Box:
https://www.virtualbox.org/
3) imgburn:
http://www.imgburn.com/index.php?act=download
Following instruction from
http://www.sysprobs.com/install-mac-os-1065-snow-leopard-virtualboxseveral-issues-fixed
http://www.tonymacx86.com/hardware-troubleshooting/112092-ebios-read-error-error-0x0c-block-0x18a96a-sectors-0-a.html
Still errors
EBIOS read error, error 0x0c,
block 0x0 sector 0
 Later reset storage as following:
Then start, iboot is working and switch to Host Drive "D:" (set in SATA port 1, passthrough is checked)
The  error disappeared, and following shown:
But system hanged in "Mac OS X install DVD"



Monday, November 25, 2013

Build Native iOS Apps on Windows Computers using Mobione



Mobione can be downloaded from:
http://www.genuitec.com/mobile/features/
Now anyone can build App Store-ready apps for iPhone, iPad or iPod devices. The best part is you can do it from your existing Windows computer. (Apple requires you to own a Mac, but now you don't!)
Video:Build Native iOS Apps on Windows Computers

MobiOne FAQ:
http://www.genuitec.com/mobile/mobione_faqs.html#dev3

Apple store  requires that your application must be a native iOS application. Use the Build iOS Application wizard in MobiOne to create a native iOS application (.ipa file).

Record your screen with microphone using Hypercam and ezvid for free



There are server software to record screen with microphone: camtasia  (not free), www.screenr.com (free account maximum 5 minutes, save as mp4), ezvid (maximum 45 minutes)  and this one Hypercam (no time limit, free, save as avi).

Hypercam for Windows can be downloaded from:
http://www.hyperionics.com/hc/downloads.asp

HyperCam supports text annotations, sound, and screen notes (great for creating automated software demos and software training!). You can also select Frame rate and compression quality prior to recording your movie.  But HyperCam is not intended for re-recording of other video clips from the screen (e.g. playing in Media Player, RealVideo, QuickTime etc.), but rather for creating regular software presentations, tutorial, demos etc.

ezvid has a lot of nice features, such as insert symbol, text pronunciation, video editing. ezvid can be downloaded from:
 http://www.ezvid.com

Video: How to use ezvid:

Password protect your folders in Windows 7 using "Folder Lock"



You may need to protect your folders in Windows 7 for important document.
You can download free version of  "Folder Lock" from here:
http://www.newsoftwares.net/folderlock/

Folder Lock lets you password-protect files, folders and drives; encrypt your important files on--the-fly; backup them in real-time; protect USB drives and portable devices; shred files and clean history.

Hide some of dropbox folder in Windows 7



When you install dropbox in Windows 7, it will create a dropbox folder in your Windows 7 and sync to dropbox.  You may not want some of your security files stay in your local computer. To hide some of the local dropbox folder in Windows 7, there are two ways:
Method 1:
1) Go to  system tray at the bottom menu of Windows 7, click dropbox  icon,   a menu popup, click gear icon at top right,  click preferences, the click advanced,  click selective sync and choose the folder you want to show in Windows. The unchecked folder will be deleted from your local computer.
2) But local dropbox folder  is still  linked to your dropbox account. You many need to got to preference, and click Accounts and click "unlink to computer"
 Method 2:
1) Log in to your dropbox account,   go to Settings and click Security, find your PC name and
click unlink.  The dropbox folder in local PC is still there, but no more updated. You can delete some of directories which you do not want to show.
Video:  Hide some of dropbox folder in Windows 7

Protect your PC with external flash USB drive using Predator



The Predator software uses a USB drive as a key to lock or unlock your computer by removing it or plugging it in. The software is free to download here:
http://www.predator-usb.com/predator/en/index.php

How it works?
  • when you're away from your PC, you simply remove the USB drive:
    once it is removed, the keyboard and mouse are disabled and the screen darkens
  • when you return back to your PC, you put the USB flash drive in place:
    keyboard and mouse are immediately released, and the display is restored. 
 Video: Secure your Computer with a USB!

Friday, November 22, 2013

MySQL: copy a row value to a new row and update some of values






Below is PHP code to copy a row value in table projects and update the values of  date_created and name columns: The method is used for copy modules and research projects in PHP projects.
Her we use insert into ...set..
$nl  = "\r\n";
$insert_set    = "INSERT INTO `%1s` SET %2s;".$nl;
$sql_insert = '';
$s1 = '';
$s2 = array();
$sql    = "SELECT * FROM projects WHERE project_id=$project_id";
$result = mysql_query($sql,$db);
if($row = mysql_fetch_assoc($result)) {
   $s1 = 'projects';
   $s2 = array();
   foreach($row as $key=>$value){
      if($key == 'project_id'){
         $s2[] = 'project_id=0';
         continue;
      }
      if($key == 'date_created'){
         $s2[] = "date_created = NOW()";
         continue;
      }
      if($key == 'name'){
         $s2[] = "name ='$project_name'";
         continue;
      }
      $value = addslashes($value);
      $s2[] = "$key='$value'";
   }

   $sql_insert = (vsprintf($insert_values,Array($s1,implode(',',$s2))));
   mysql_query($sql_insert,$db);
   $new_project_id = mysql_insert_id();
}


The  table projects is created as following, projects and project_id are primary key with auto increment:
CREATE TABLE  `research_projects_new1`.`projects` (
  `project_id` mediumint(8) unsigned NOT NULL auto_increment,
  `name` varchar(255) NOT NULL default '',
  `owner_id` mediumint(8) unsigned NOT NULL default '0',
  `date_created` datetime NOT NULL default '0000-00-00 00:00:00',
  `date_start` datetime NOT NULL default '0000-00-00 00:00:00',
  `date_end` datetime NOT NULL default '0000-00-00 00:00:00',
  `arms` tinyint(3) unsigned NOT NULL default '0',
  `groups` tinyint(3) unsigned NOT NULL default '0',
  `subjects` smallint(5) unsigned NOT NULL default '0',
  `auto_study_code` tinyint(1) NOT NULL default '1',
  `subject_demographics` text,
  `subject_to_group` enum('ordered','random','manual') NOT NULL default 'ordered',
  `reviewer_to_subject` enum('ordered','random','manual') NOT NULL default 'ordered',
  `reviewer_assignment_rule` enum('subject','arm_group','arm','group') NOT NULL default 'arm_group',
  `subjects_per_review_slot` tinyint(3) unsigned NOT NULL default '0',
  PRIMARY KEY  (`project_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8; 


The MySQL statement is:
INSERT INTO `projects` SET project_id=0,name ='small project COPY',owner_id='37',date_created = NOW(),date_start='2008-07-21 00:00:00',date_end='2008-07-25 00:00:00',arms='1',groups='2',subjects='10',auto_study_code='1',subject_demographics='N;',subject_to_group='manual',reviewer_to_subject='ordered',reviewer_assignment_rule='subject',
subjects_per_review_slot='1'; 

We can also use insert into ...values
Insert into table values and insert into table set in MySQL are identical.
Example
INSERT INTO table_1 (a, b, c) VALUES (1,2,3)
is the same as
INSERT INTO table_1 SET a=1, b=2, c=3
 PHP code to copy a row value to a new row and update some of values
$nl  = "\r\n";
$insert_values = "INSERT INTO `%1s` VALUES(%2s);".$nl;

$sql_insert = '';
$s1 = '';
$s2 = array();
//start with the base entry edu_courses
$sql    = "SELECT * FROM projects WHERE project_id=$project_id";
$result = mysql_query($sql,$db);
if($row = mysql_fetch_assoc($result)) {
   $s1 = 'projects';
   $s2 = array();
   foreach($row as $key=>$value){
      if($key == 'project_id'){
         $s2[] = '0';
         continue;
      }
      if($key == 'date_created'){
         $s2[] = "NOW()";
         continue;
      }
      if($key == 'name'){
         $s2[] = "'$project_name'";
         continue;
      }
      $value = addslashes($value);
      $s2[] = "'$value'";
   }
   $sql_insert = (vsprintf($insert_values,Array($s1,implode(',',$s2))));

   mysql_query($sql_insert,$db);
   $new_project_id = mysql_insert_id();
}


The MySQL statement is:
 INSERT INTO `projects` VALUES(0,'small project COPY','37',NOW(),'2008-07-21 00:00:00','2008-07-25 00:00:00','1','2','10','1','N;','manual','ordered','subject','1');

Thursday, November 21, 2013

Find stored passwords in Fireftp ftp client



Fireftp ftp client stores around  quick connections for you, but passwords are hidden. Those passwords can be found in the location as  normal Firefox password location.

1) Go to Tools at the top of Firefox menu, click options, then select  Security,
2) click Saved Passwords:, then click  Show Passwords button
3) Look for ftp under site column, then look for password column, you can see a list of passwords, which are for Fireftp,

It is recommended to use Master password in security setting.
Video:  Find stored passwords in Fireftp ftp client

Find stored passwords in Filezilla ftp client



Filezilla ftp client stores around 8 quick connections for you, but passwords are hidden. Those passwords can be found in Filezilla configuration directory.  For example  in my Windows 7 PC:
open file (replace jiansen to your user name)
C:\Users\jiansen\AppData\Roaming\FileZilla\recentservers.xml
You can see something like this:
<FileZilla3>
    <RecentServers>
        <Server>
            <Host>10.29.227.88</Host>
            <Port>21</Port>
            <Protocol>0</Protocol>
            <Type>0</Type>
            <User>jiansen</User>
            <Pass>my_pass</Pass>
            <Logontype>1</Logontype>
            <TimezoneOffset>0</TimezoneOffset>
            <PasvMode>MODE_DEFAULT</PasvMode>
            <MaximumMultipleConnections>0</MaximumMultipleConnections>
            <EncodingType>Auto</EncodingType>
            <BypassProxy>0</BypassProxy>
        </Server>

    </RecentServers>
</FileZilla3>

The password is stored inside pass tag in recentservers.xml file.

Sometimes Appdata directory is hidden, To unhide this directory,  under \user\jiansen\ (replace jiansen to your user name),  click organize at top left menu,  click folder and search options, click view, select  "show hidden files , folders and drives) and click OK.

Another way to find Appdata folder in Windows 7:
Click Start and in search box enter:
%AppData%
The Appdata directory will show up.

Create a New User with same privileges as root in MYSQL



Sometimes we may need to create a new user with same  privileges as root in MYSQL in case we forget the root password.
To  create a new user jianse  in MySQL with password "mypass"
CREATE USER 'jiansen'@'localhost' IDENTIFIED BY 'mypass';
Sets all simple privileges except GRANT OPTION to new user jiansen
GRANT ALL PRIVILEGES ON * . * TO 'jiansen'@'localhost';
Add GRANT OPTION to new user jiansen
GRANT GRANT OPTION ON * . * TO 'jiansen'@'localhost';
Now user jiansen has same rigth as root in MySQL.

Reference:
Crack mysql root password in several ways
 http://www.sureshkumarpakalapati.in/2011/07/crack-mysql-root-password-in-several.html

Sunday, November 17, 2013

Gmail backup and archive to local computers (Windows) and restore utility



You can download your  google data except gmail into zip file via:
https://www.google.com/settings/takeout
You may want to backup and archive your gmail.
Solution one:
1) Backup gmail to Google drive:
reference:
 http://www.skipser.com/p/2/p/archive-backup-gmail-google-drive.html
First open this "Gmail archiver spreadsheet" and select File->Make a Copy.
 Select "Gmail Drive Backup" menu, click "Initialize
 Now select "Gmail Drive Backup" again and click "Start Daily Gmail Backup". You will be asked to enter the Gmail Label you want to archive. This application is able to archive the attachment. But this script also remove the original mails in the label. The next solution is better.
Solution 2
2) Another solution is using Gmail backup utility
https://code.google.com/p/gmail-backup-com/
This application will backup all emails (event trash), but no attachment and no classification in labels.

Wednesday, November 13, 2013

MySQL NOW() function add 1 hour, day, month, year



MySQl NOW() function returns current time with format ‘YYYY-MM-DD HH:MM:SS’. If we use
NOW()+1, a second is added, but the return value format is changed to:
YYYYMMDDHHMMSS.uuuuuu #sthash.K5ILIJDY.dpuf
 
 YYYYMMDDHHMMSS.uuuuuu
MySQL statement example 1:
 SELECT NOW(), NOW() + 1;
we will get
 '2013-11-13 13:17:07', 20131113131708.000000
To keep the same format: we can use
NOW() + INTERVAL 1 second;
to add a second with format ‘YYYY-MM-DD HH:MM:SS’

MySQL statement example 2:
 SELECT NOW(), NOW() + INTERVAL 1 second;
 we will get
 '2013-11-13 13:19:21', '2013-11-13 13:19:22'
Similarly  we can add 1 hour, 1 day, 1 month or one year using
+INTERVAL 1 hour,  +INTERVAL 1 month, +INTERVAL 1 year

We can use "-" to reduce time.


YYYYMMDDHHMMSS
YYYYMMDDHHMMSS.uuuuuu #sthash.K5ILIJDY.dpuf
YYYYMMDDHHMMSS.uuuuuu #sthash.K5ILIJDY.dpuf
YYYYMMDDHHMMSS.uuuuuu #sthash.K5ILIJDY.dpuf

Tuesday, November 12, 2013

Make and embed Youtube Playlist



A lot of youtube music videos are only a few minutes, you may want to create a playlist and embed in your blog.
Go to  your Youtube account, go to Video manager (in upload tab), click playlists in left menu,  click New Playlist in right top corner, add url from youtube videos.
Below is the playlist I created:
https://www.youtube.com/watch?v=JnNT-DSsb1w&list=PLmhRNZyYVpDmMBBLU_a8ur8yYSTnus_5N
The list id is PLmhRNZyYVpDmMBBLU_a8ur8yYSTnus_5N
To embed this playlist:
<iframe allowfullscreen="" frameborder="0" height="600" src="http://www.youtube.com/embed/videoseries?list=PLmhRNZyYVpDmMBBLU_a8ur8yYSTnus_5N" width="100%"></iframe>
To embed another playlist, replace my list id  PLmhRNZyYVpDmMBBLU_a8ur8yYSTnus_5N to yours.
Result:

PHP, global variable and local variable



In PHP programming, we should be careful of the scope of global variable and local variables.
Example 1: the $a variable inside test function is not related to the global varialbe $a outside test function, and default is 0
<?php
$a = 2; /* global scope */
function test()
{
    $a=$a+1;
    echo $a.'<br />'; /* reference to local scope variable */
}
test();
test();
echo $a;
?>

The result is
1
1
2

Example 2: now we declare $a as a global variable inside function test, it is  the same as the $a  variable defined  outside the test function
<?php
$a = 2; /* global scope */

function test()
{
   global $a;
    $a=$a+1;
    echo $a.'<br />'; /* reference to local scope variable */
}

test();
test();
echo $a;
?>

The result is
3
4
4
Example 3: global variable $db is often used in mysql_query($sql, $db) in PHP functions,
and  static variable $now is used to memorize its first  value, after first time call write_to_rplog function,  the variable $now is set. 
function write_to_rplog($operation_type, $table_name, $num_affected, $details) {
    global $db;
    static $now;
 
    if (!$now) {
        $now = date('Y-m-d H:i:s');
    }
    if ($num_affected > 0) {
        $details = addslashes(stripslashes($details));
        $sql    = "INSERT INTO  rp_admin_log VALUES ('$_SESSION[login]', '$now', '$operation_type', '$table_name', $num_affected, '$details')";
        $result = mysql_query($sql, $db);
    }
}

Friday, November 1, 2013

Customize iPhone 5s



Below are some tips for iPhone 5s beginners:

1) Setup fingerprints:
 In Settings, click General then touch ID & Passcodes->Touch ID, then click add a fingerprint to add fingerprints

  2) Setup Apple ID and  allow icloud  to locate the iPhone:
1. Open the "Settings" application
- 2. Go to "General" and select "Passcode & Fingerprint"
- 3. Go to "Fingerprints" and tap "Add a fingerprint"
- 4. Follow the on-screen prompts
Read more at http://www.mobileburn.com/22047/news/apple-iphone-5s-touch-id-demo-how-to-setup-the-iphone-5s-fingerprint-scanner#dGEvzqZJAc70OTOk.99
1. Open the "Settings" application
- 2. Go to "General" and select "Passcode & Fingerprint"
- 3. Go to "Fingerprints" and tap "Add a fingerprint"
- 4. Follow the on-screen prompts
Read more at http://www.mobileburn.com/22047/news/apple-iphone-5s-touch-id-demo-how-to-setup-the-iphone-5s-fingerprint-scanner#dGEvzqZJAc70OTOk.99
1. Open the "Settings" application
- 2. Go to "General" and select "Passcode & Fingerprint"
- 3. Go to "Fingerprints" and tap "Add a fingerprint"
- 4. Follow the on-screen prompts
Read more at http://www.mobileburn.com/22047/news/apple-iphone-5s-touch-id-demo-how-to-setup-the-iphone-5s-fingerprint-scanner#dGEvzqZJAc70OTOk.99

 Sign up Apple ID,  allow icloud (https://www.icloud.com/) to find my iPhone.
install icloud (http://www.apple.com/ca/icloud/setup/) in my local Windows 7 PC

3) Setup WiFi
 In Settings,  click WiFi, enter  WiFi password for work and at home

4) Setup email account, voicemail password and phone contact

5)  Check cellular data usage.

In settings,  click cellular data, turn off when  not using it. Click cellular data, to see cellular data usage.

6) multiple  input keyboards for different languages, for example for English and Chinese
In Settings, click General and select Keyboards, then click keyboards, add New Keyboard, add Chinese -simplified (handwriting) and Chinese -simplified (Pinyin), my default is English. So I can input Chinese.

7) Configure to spend less  battery time:
To spend less battery time, in settings, click General and select Background App Refresh, turn off Background App Refresh.
In pedometer, disable auto tracking (in more menu) to not using it.
 
8) In App store, download several free applications:
transit:
to see the bus schedule  and map directly related to where you are.
 pacer pedometer,
measure how many steps you walk every day
 YouTube, Google, Google Maps, TD Canada, Roger  my account, 文学城 etc

iphone 5s slow motion: Halloween night fireworks



Using iphone 5s slow motion to take Halloween night fireworks
Video:  iphone 5s slow motion: Halloween night fireworks

Below is how I make this video:
1)Take video using iphone 5s slow motion. Export slow motion to local computer
2) Use Windows live movie maker in Windows 7,
edit -speed 0.5x (0.25x too slow)
3) Export the movie in 720p
4) The drawback of slow motion has no sound

Friday, October 25, 2013

MySQL select random rows



Below is the example of MySQL statement   to select 4 random rows form table cesei_members using ORDER BY RAND() LIMIT 4:

SELECT * FROM  cesei_members  ORDER BY RAND() LIMIT 4;

I use it to randomly pick up 4 committee members for each module.

Wednesday, October 23, 2013

php, upload file same name



I upload mp3 files using PHP, I want to check if the file exists, then change the file name.
using
$filebase = basename($filename, ".mp3");
to get the filename without mp3 extension, for example test.mp3, we get test.
If test.mp3 exists, the upload file name will be changed to test_1.mp3, test_2.mp3 ... in sequence.
The final PHP code is as follows
<?php
$filetmpname = $_FILES['newfile']['tmp_name'];    
$filename=$_FILES['newfile']['name'] ;
 $basedir="C:\\LMS_CESEI\\file_repository\\";
$filebase = basename($filename, ".mp3");
$i=0;
while(file_exists($basedir.$filename)) {
$i = $i +1;
$filename = $filebase.'_'.$i.'.mp3';
}
$ok = move_uploaded_file($filetmpname, $basedir.$filename);

?>

To see the list of files uploaded in the remote directory
<?php
$basedir=
"C:\\LMS_CESEI\\file_repository\\";
 if ($handle = opendir($basedir)) {
      while (false !== ($file = readdir($handle))) {
          if ($file == '.' || $file == '..') {
            continue;
          }
          echo $file."<br />";
        }
}
?>

php, play mp3 file outside web server directory



To prevent that mp3 audio files are downloaded, we may need to  put mp3  file outside  web server directory. On the other hand, we also want to play these mp3 files online. The following PHP script is used to play the nn.mp3 file in folder C:\LMS\uploads\, which is not related to the web server folder.
<?php
$file = "C:\\LMS\\uploads\\nn.mp3";
$real = realpath($file);
if (file_exists($real)){

     $ext   = 'audio/mpeg';
      $size  = filesize($real);
      $size2 = $size-1;
      header('Content-Type: '.$ext);
      header("Content-Range: bytes 0-$size2/$size");
      header('Content-Length: '.$size);
      echo @file_get_contents($real);

}else {
       echo $file." does not exsit";

}
?>

For other file formats, $ext will be changed as below:
$mime['zip']   = 'application/zip';
$mime['au']    = 'audio/basic';
$mime['snd']   = 'audio/basic';
$mime['mid']   = 'audio/midi';
$mime['midi']  = 'audio/midi';
$mime['kar']   = 'audio/midi';
$mime['mpga']  = 'audio/mpeg';
$mime['mp2']   = 'audio/mpeg';
$mime['mp3']   = 'audio/mpeg';
$mime['aif']   = 'audio/x-aiff';
$mime['aiff']  = 'audio/x-aiff';
$mime['aifc']  = 'audio/x-aiff';
$mime['ram']   = 'audio/x-pn-realaudio';
$mime['rm']    = 'audio/x-pn-realaudio';
$mime['ra']    = 'audio/x-realaudio';
$mime['wav']   = 'audio/x-wav';
$mime['pdb']   = 'chemical/x-pdb';
$mime['xyz']   = 'chemical/x-pdb';
$mime['gif']   = 'image/gif';
$mime['ief']   = 'image/ief';
$mime['jpeg']  = 'image/jpeg';
$mime['jpg']   = 'image/jpeg';
$mime['jpe']   = 'image/jpeg';
$mime['png']   = 'image/png';
$mime['tiff']  = 'image/tiff';
$mime['tif']   = 'image/tiff';

$mime['xml']   = 'text/xml';
$mime['mpeg']  = 'video/mpeg';
$mime['mpg']   = 'video/mpeg';
$mime['mpe']   = 'video/mpeg';
$mime['qt']    = 'video/quicktime';
$mime['mov']   = 'video/quicktime';
$mime['avi']   = 'video/x-msvideo';
$mime['movie'] = 'video/x-sgi-movie';
$mime['ice']   = 'x-conference/x-cooltalk';
$mime['html']  = 'text/html';
$mime['htm']   = 'text/html';
$mime['xls']   = 'application/vnd.ms-excel';
$mime['log']   = 'text/plain';

$mime['gtar']  = 'application/x-gtar';
$mime['gz']    = 'application/x-gzip';
$mime['tgz']   = 'application/x-gzip';

$mime['pdf']   = 'application/pdf';
$mime['swf']   = 'application/x-shockwave-flash';

Record voice using microphone and upload to server using flash and PHP



Below is to get the flash from  Moodle LMS audio recording plugin and redesign PHP upload file.
Below is the snapshot of Moodle flash plugin interface:

1) Download moodle audio recording plugin:
https://moodle.org/plugins/pluginversions.php?plugin=assignment_onlineaudio
unzip and get onlineaudio folder,  copy assests/recorder.swf to your working directory.
2) Embed recorder.swf:
<embed type="application/x-shockwave-flash" src="recorder.swf" id="recorder" name="recorder" quality="high" wmode="transparent" flashvars="gateway=simpleupload.php" height="276" width="430">
3) create simpleupload.php to process the sound file produced by recorder.swf:
<?php
 $filename = preg_replace('/\s/', '', $_FILES['newfile']['name']);
$filetmpname = $_FILES['newfile']['tmp_name'];  

$ok = move_uploaded_file($filetmpname, "C:\\LMS\\uploads\\".$filename);
?>
In this example, the upload file will be put in C:\LMS\uploads\
4) To displayand play  the audio file (for example nn.mp3), I used the longtail_payer.swf from JW player:
<audio controls="controls">
 <source src="nn.mp3" />
 <!-- fallback -->
  <embed type="application/x-shockwave-flash"                                                        
    flashvars="audioUrl=nn.mp3"   
     src="longtail_player.swf"  
     width="650? height="0? quality="best"></embed>
</audio>`  

5)   For recorder using Flash Media server, refer to pRecorderTest. 115K Zip file in 
http://flash-communications.net/sourcecode/index.html

Friday, October 18, 2013

Remove last character of a string, for example comma and a space



In the following example, I combined all reviewer full name using ',  ' (comma and  a pace), but I need to remove the last comma and space when they are displayed.  PHP function rtrim can be used for this purpose, example PHP code:
  $sql_1 = "SELECT
                  M.prefix,M.first_name,M.last_name
                  FROM cesei_module_user_reviews MUR
                  LEFT JOIN cesei_members M ON MUR.member_id=M.member_id WHERE MUR.module_id=".$module_id ;
  $result_1 = mysql_query($sql_1, $db);
   $reviewers = ' ';
 while($row_1 = mysql_fetch_assoc($result_1)){
             $reviewers .= trim(htmlspecialchars($row_1['prefix'].' '.$row_1['first_name'].' '.$row_1['last_name'])).',  ';
        
    }
    $reviewers = rtrim($reviewers, ", ");

Wednesday, October 16, 2013

PHP/MySQL - Simple way to return a single value using mysql_result



Normally, we can use mysql_fetch_assoc to get the MySQL query result in PHP, example:
   $module_id = 2;
   $sql = "SELECT  * FROM  cesei_review_done WHERE module_id=$module_id";
    $result = mysql_query($sql,$db);
    while($row = mysql_fetch_assoc($result)) {
        $review_result = $row['review_done'];
    }

In some casews, we know MySQL will return only a single value, the simple way to get this single value is to use PHP function  mysql_result instead of  mysql_fetch_assoc, example:

   $module_id = 2;
   $sql = "SELECT  review_done FROM  cesei_review_done WHERE module_id=$module_id";
    $result = mysql_query($sql,$db);
    $review_result  = mysql_result($result, 0);

Tuesday, October 15, 2013

MySQL key, primary key and uinque key



KEY is normally a synonym for INDEX. Using key or index,  MySQL can quickly determine the position of the data  without having to look at all the data. It is much faster then reading sequentially.  MySQL uses indexes for the operations such as WHERE and LIKE for quick  search.

 A UNIQUE  key creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.

A PRIMARY KEY is a special unique key. A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE primary key.

Example of MySQL code for these keys:
CREATE TABLE `FACULTIES` (
  `FACULTYID` int(11) NOT NULL auto_increment,
  `FACULTYCODE` varchar(4) NOT NULL default '',
  `TITLE` varchar(127) NOT NULL default '',
  `dean` varchar(7) NOT NULL default '',
  PRIMARY KEY  (`FACULTYID`),
  UNIQUE KEY `FACULTYCODE` (`FACULTYCODE`),
  KEY `dean` (`dean`)
) TYPE=MyISAM;


Tuesday, October 8, 2013

PHP, split summary text data from pubmed using preg_split and preg_match


I have summary text data from pubmed and I want to separate them into author, title, author, date and pubid etc. The PHP code:
<?php
//Journal list number and authorlist
$pmregex = '/^(\d+): (.+?)\.'

//article title
         . ' (.+?)\.'

// (.+?)  Journal name such as Oral Dis
// \. (\d\d\d\d)(.*?);  . 2013 Jul
// ;(.+?)     :19 (5)
//:(\w+)-?(\w*?) page number such as  440-451
// add \n? after considering 0+ line break
         . '(.+?)[\. \n?](\d\d\d\d)(.*?);(.+?):(\w+)-?(\w*?)[\.\;](.*)'
//PMID number
       . '[PMID: \n?](\d+)'
         . '/s';
$data="1: Saini R, Poh C. Photodynamic therapy: a review and its prospective role in the
management of oral potentially malignant disorders. Oral Dis. 2013
Jul;19(5):440-451. doi: 10.1111/odi.12003. PubMed PMID: 24079944.



2: Powell JJ, Apiratpracha W, Partovi N, Erb SR, Scudamore CH, Steinbrecher UP,
Buczkowski AK, Chung SW, Yoshida EM. Subcutaneous administration of hepatitis B
immune globulin in combination with lamivudine following orthotopic liver
transplantation: effective prophylaxis against recurrence. Clin Transplant. 2006
Jul-Aug;20(4):524-5. PubMed PMID: 16842532.
";
//[\r\n]: newline, \d+:  separator is digital numbers followed by : ,
//?=Separator is included in the output array
$choppeddata = preg_split('/([\r\n])(?=\d+: )/',$data);

foreach($choppeddata as $subdata)
{
print_r($subdata);
echo '<br /><br />';
preg_match($pmregex, trim($subdata), $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
}
?>

Running result:
1: Saini R, Poh C. Photodynamic therapy: a review and its prospective role in the management of oral potentially malignant disorders. Oral Dis. 2013 Jul;19(5):440-451. doi: 10.1111/odi.12003. PubMed PMID: 24079944.
Array
(
    [0] => 1: Saini R, Poh C. Photodynamic therapy: a review and its prospective role in the
management of oral potentially malignant disorders. Oral Dis. 2013
Jul;19(5):440-451. doi: 10.1111/odi.12003. PubMed PMID: 24079944
    [1] => 1
    [2] => Saini R, Poh C
    [3] => Photodynamic therapy: a review and its prospective role in the
management of oral potentially malignant disorders
    [4] =>  Oral Dis
    [5] => 2013
    [6] => 
Jul
    [7] => 19(5)
    [8] => 440
    [9] => 451
    [10] =>  doi: 10.1111/odi.12003. PubMed 
    [11] => 24079944
)
2: Powell JJ, Apiratpracha W, Partovi N, Erb SR, Scudamore CH, Steinbrecher UP, Buczkowski AK, Chung SW, Yoshida EM. Subcutaneous administration of hepatitis B immune globulin in combination with lamivudine following orthotopic liver transplantation: effective prophylaxis against recurrence. Clin Transplant. 2006 Jul-Aug;20(4):524-5. PubMed PMID: 16842532.
Array
(
    [0] => 2: Powell JJ, Apiratpracha W, Partovi N, Erb SR, Scudamore CH, Steinbrecher UP,
Buczkowski AK, Chung SW, Yoshida EM. Subcutaneous administration of hepatitis B
immune globulin in combination with lamivudine following orthotopic liver
transplantation: effective prophylaxis against recurrence. Clin Transplant. 2006 
Jul-Aug;20(4):524-5. PubMed PMID: 16842532
    [1] => 2
    [2] => Powell JJ, Apiratpracha W, Partovi N, Erb SR, Scudamore CH, Steinbrecher UP,
Buczkowski AK, Chung SW, Yoshida EM
    [3] => Subcutaneous administration of hepatitis B
immune globulin in combination with lamivudine following orthotopic liver
transplantation: effective prophylaxis against recurrence
    [4] =>  Clin Transplant
    [5] => 2006
    [6] =>  
Jul-Aug
    [7] => 20(4)
    [8] => 524
    [9] => 5
    [10] =>  PubMed 
    [11] => 16842532
)