Sunday, February 17, 2013

Resize image files in batch (in Mac)

Tags:

JPEG resize, image resize, Mac OS X, Mountain Lion, Preview


Problem:

I have a few photo (taken by my digital camera) and want to upload them to Picasa. But the images are too large (in both geometry size and file size). I want to scale them down before uploading.


Solution:

1. Select all files in a Finder window (Command-click or Shift-click for multiple files).
2. Right click on one of the selected file and select "Open With" -> "Preview".
3. In the Preview window, multiple files are shown as multiple pages on the side bar on the left.
4. Select all opened files by "Command-A" on the side bar.
5. Select from the menu bar: "Tools" -> "Adjust Size ...".
6. There you can change size. I selected the "Fit into: 1280x1024 pixels". Yours may be different.
7. Click "OK" to close the Adjust Size window.
8. Finally, "Save" the files and quit Preview.


Result:

The files are changed from 5MB to 256KB in file size while displayed perfectly in the web browser.

Thursday, January 31, 2013

Get WAN IP in one line command

If the local host is behind firewall and/or there is NAT in between, ifconfig may not report the correct IP address which is seen externally.

The following (one line) command prints out the WAN side IP.

# curl -s http://checkip.dyndns.org | sed -e 's/.*: //;s/<.*//'

Sunday, January 13, 2013

Expect: interact with external program with script

The following script calls an external program and interact with this external program by controlling the inputs and outputs of it.

The script first create call the external program 'dc', which is a postfix based calculator.
Then it send the string "4p\r" as input to the 'dc' program.
In the expect block, the script try to match two patterns: "0\r" and any digit followed by a carry return.
If the output of 'dc' is 0, then the script terminates it by sending the command "q".
If the output of 'dc' is any digit larger then 0 (starting from 4 in this example), the value will be decreased by sending "1-p" to 'dc'.


#!/usr/bin/expect -f

spawn dc      
send "4p\r"   

expect {

  "0\r" {
    puts "Expect: matched $expect_out(0,string)";
    send "q\r"
    puts "Expect: exit";
  }

  -re {[1-9]\r} {
    puts "Expect: matched $expect_out(0,string)";
    send "1-p\r";
    puts "Expect: reduce by 1";
    exp_continue
  }

}

Running the script will generated the following output on screen.


$ ./script.exp
spawn dc
4p
4
Expect: matched 4
Expect: reduce by 1
1-p
3
Expect: matched 3
Expect: reduce by 1
1-p
2
Expect: matched 2
Expect: reduce by 1
1-p
1
Expect: matched 1
Expect: reduce by 1
1-p
0
Expect: matched 0
Expect: exit


Notes:

1. Except captures all output from the external program including '\r'.
2. Variable $expect_out(0,string) stores the matched string from the immediate previous matching.
3. Variable $expect_out(buffer) stores the remaining output of the external program by removing all characters up to (and including) the matched string from the immediate previous matching.

Tuesday, January 08, 2013

Interface between C and TCL : Case III

Extending TCL script by C functions. The C functions are compiled as dynamic loaded library and is called from within a TCL script. The script can be interpreted by a standard TCL shell.

The C library is listed below.

#include <stdio.h>
#include <tcl.h>

int my_cmd1 (ClientData cdata, Tcl_Interp *interp,
    int objc, Tcl_Obj *const objv[]) {
  printf("Hello, world!\n");
  return TCL_OK;
}

int my_cmd2 (ClientData cdata, Tcl_Interp *interp,
    int objc, Tcl_Obj *const objv[]) {
  printf("Hello, again!\n");
  return TCL_OK;
}

// The function name must matches the dynamic library name.
// With the first letter in capital form and a "_Init" postfix.
int My_cmd_Init (Tcl_Interp *interp) {

  if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL)
    return TCL_ERROR;

  Tcl_CreateObjCommand(interp, "my_cmd1", my_cmd1,
      (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL );

  Tcl_CreateObjCommand(interp, "my_cmd2", my_cmd2,
      (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL );

  return TCL_OK;
}

To compile this file into a dynamic library (in Mac OS X 10.8.2), run the following line:

gcc -Wall -shared -o my_cmd.dylib my_cmd.c \
  -undefined dynamic_lookup -rdynamic

The expected output is:

$ tclsh
% load ./my_cmd.dylib
dlsym(0x7fb5dbe02360, My_cmd_SafeInit): symbol not founddlsym(0x7fb5dbe02360, My_cmd_Unload): symbol not founddlsym(0x7fb5dbe02360, My_cmd_SafeUnload): symbol not found
% my_cmd1
Hello, world!
% my_cmd2
Hello, again!
% exit

The "symbol not found" error can be safely ignore for this simple example.

Interface between C and TCL : Case II

C main function create an interactive TCL shell. The program terminates after the TCL shell is terminated and will not return control to C.

The C main function is listed below.

#include <stdio.h>
#include <tcl.h>

// A dummy initialisation.
int Tcl_AppInit(Tcl_Interp *interp) { return 0; }

int main(int argc, char *argv[]) {

  printf("In C start\n");
  Tcl_Main(argc, argv, Tcl_AppInit);
  printf("In C end\n");   // This line will never be executed.

  return 0;
}

The program is compiled by:

gcc -Wall -o main main.c -ltcl

The expected output is:

$ ./main
In C start
% puts "hello"
hello
% exit

Interface between C and TCL : Case I

C main program calls TCL interpreter to run an external TCL script. C and TCL communicate through variable values. TCL can call C function.

The C main program is listed below.

#include <stdio.h>
#include <tcl.h>

// a function to be called from within the TCL script
int my_func (ClientData data, Tcl_Interp *interp,
    int objc, Tcl_Obj *const objv[]);

int main(void) {

  Tcl_Interp *interp = NULL;

  interp = Tcl_CreateInterp();
  if (interp)
    printf("In C: TCL interpretor started.\n");

  Tcl_CreateObjCommand(interp, "my_cmd", my_func, 
      (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL );

  printf("In C: TCL script begin.\n");
  if (Tcl_EvalFile(interp, "simple.tcl") == TCL_OK)
    printf("In C: TCL script end.\n");

  printf("C says: Hello, %s!\n", Tcl_GetVar(interp, "name", 0));

  Tcl_DeleteInterp(interp);
  if (Tcl_InterpDeleted(interp))
    printf("In C: TCL interpretor stopped.\n");

  return 0;

}


int my_func (ClientData data, Tcl_Interp *interp,
    int objc, Tcl_Obj *const objv[]) {
  int i;

  printf("In C: my_func() started.\n");
  printf("  obj[0] = %s.\n", Tcl_GetString(objv[0]));
  printf("  obj[1] = %s.\n", Tcl_GetString(objv[1]));
  if (Tcl_GetIntFromObj(interp, objv[2], &i) == TCL_OK)
    printf("  obj[2] = %d.\n", i);
  else
    printf("  obj[2] is not a integer!\n");
  printf("  obj[3] = %s.\n", Tcl_GetString(objv[3]));
  printf("In C: my_func() ended.\n");

  return TCL_OK;
}

The TCL script is listed below.

#!/usr/bin/tclsh

puts "Tcl calls: my_cmd (implemented as a C function)"
my_cmd abc +123 xyz

puts "----"

puts "Tcl asks: What is your name? "
gets stdin name

The program is compiled by (in Mac OS X 10.8.2) :

gcc -Wall -o main main.c -ltcl

The expected output is (in Mac OS X 10.8.2) :

$ ./main 
In C: TCL interpretor started.
In C: TCL script begin.
Tcl calls: my_cmd (implemented as a C function)
In C: my_func() started.
  obj[0] = my_cmd.
  obj[1] = abc.
  obj[2] = 123.
  obj[3] = xyz.
In C: my_func() ended.
----
Tcl asks: What is your name? 
Brittle
In C: TCL script end.
C says: Hello, Brittle!
In C: TCL interpretor stopped.

Wednesday, November 07, 2012

Mac OS X Preview reduce PDF size

Problem:

I have some (scanned) PDF documents which is a bit large (in a few MB) and want to reduce their size. The Preview app in Mas OS X has the function to reduce the PDF size but the resulted output is not clear enough to be useful.

To reduce PDF size in this way, we first open the PDF file in Preview. The select "File" -> "Export...". In the "Quartz Filter" option, select "Reduce File Size" and then "Save" the file with a new name. In one example, a 1.4MB colour scanned file is reduced to 65KB but the text is hardly readable.


Configuration:

Mac OS X 10.8.2


Solution: 

Open the "ColorSync Utility" from the "Applications" -> "Utilities" folder. On the lower left corner, click the "+" icon to add a new filter. You can name it as "PDF downsize".

Select this new filter and click the down arrow icon on the right. Select "Add Image Effects Component" -> "Color Image Sampling". In the newly created "Image Sampling" component, set the followings:

Scale : 100%
Resolution : <empty> Pixels / inch
Max : 1684 Pixels
Min : 512 Pixels
Quality : High

Click the down arrow icon again, this time, select "Add Image Effects Component" -> "Image Compression". In the newly created "Image Compression" component, set the followings:

Mode : JPEG
Quality : slide to around 25% towards Min

After these modifications, the "ColorSync Utility" can be closed.

Finally, open a terminal window (by "Applications" -> "Utilities" -> "Terminal". Then run the following command. Enter you root password if asked.

sudo mv ~/Library/Filters/PDF\ downsize.qfilter  /Library/PDF\ Services/

Now, you can select the "PDF downsize" filter in Preview and the above mentioned example is reduced from 1.4MB to 353KB with very readable result.

Tuesday, November 06, 2012

Disable auto generation of ~/Desktop ~/Documents ~/Downloads etc.

I prefer mwm and don't want any of the Gnome/KDE stuff on my (CentOS 6.3) desktop. But the system keep regenerating the following folders in my home directory.

Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos

Solution:

Edith /etc/xdg/user-dirs.conf to set "enabled=False". Then remove the above directories and relogin again. Done!

Saturday, November 03, 2012

Problem of X11 forwarding

Problem:

When connected using the -X or -Y option with ssh, the following error is reported.

/usr/bin/xauth:  timeout in locking authority file /home/<user>/.Xauthority


Cause:

It is in fact caused by incorrect SELinux setting.


Solution:


# ls -alZ
drwxr-xr-x. uid gid   unconfined_u:object_r:home_root_t:s0 <user>
# chcon unconfined_u:object_r:user_home_t:s0 <user>
# ls -alZ
drwxr-xr-x. uid vid   unconfined_u:object_r:user_home_t:s0 <user>

Then login again, the xauth will create the .Xauthority automatically.

Wednesday, October 24, 2012

Macbook Air fan goes crazy

Scenario:

Out of nowhere, the fan of my Macbook Air goes crazy from time to time. Even I have been doing nothing but looking at the blank desktop wallpaper! Huge fan noise and the upper left corner of the Air (near the power inlet) becomes really hot.


Configuration:

2011 MacBook Air with 1.7GHz Intel Core i5, 4GB RAM and Mac OS X 10.8.2


Cause:

Checking at the activities in the machine, I found this process (displayed by the top command):

USER             PID  %CPU %MEM      VSZ    RSS   TT  STAT STARTED      TIME COMMAND
khtsoi           501  98.8  1.6  2606200  67320   ??  Rs    4:07PM   0:05.10 com.apple.quicklook.satellite

After searching the "Quicklook" and "Satellite" keywords in the Internet, some one suggested that the cause is Quicklook tries to call QuickTime to generate thumbnails for video files which are not supported by the QuickTime codec.

Then I realised that this process re-spawns itself every time when I click on the "Downloads" folder icon in the Dock. The default action of this click is to expand the folder contents in grid mode. Even I did not have any video/audio files in that folder, I noticed that the thumbnail of a M$ Word file is not rendered. All files after this Word file are also displayed as an empty box without the thumbnail image.

So, I fired up the "Activity Monitor" tool from the "Utilities" folder, select on the "QuickLookSatellite-general" process and click the "Inspect" icon from the tool bar. Under the "Open Files and Ports" tab, I confirm that the last thing this process trying to read is that M$ Word file.


Solution:

Everything is fine after removing the Word file from the "Downloads" folder. I can open that file with the M$ Word correctly and that file is 13MB. There are other M$ Word files in the same folder but they have never caused similar problem.


Edit: one more step to really get rid of the noise (in software level).

Problem:

The fan still goes crazy and the Air is still hot even the quick lock.satellite is gone. There is no heavy duty process showing up in top or the "Activity Monitor". But I notice there are something wrong in the system log. I found the following three errors message keep showing up in the system log (by going to "Applications" -> "Utilities" -> "Console" and select the "All Messages".)


mdworker[1626]: Unable to talk to lsboxd

sandboxd[1633]: ([1631]) mdworker(1631) deny mach-lookup com.apple.ls.boxd

kernel[0]: Sandbox: sandboxd(1627) deny mach-lookup com.apple.coresymbolicationd


Cause:

I don't know and I don't care. It's better to leave it to Apple to explain it to its customers.


Solution:

Step 1: Modify the system configure file (you need to be root to do so). Edit the /System/Library/Sandbox/Profiles/system.sb file to append the following three lines at the end:


;;; FixSandboxErrors
(allow mach-lookup (global-name "com.apple.ls.boxd"))
(allow mach-lookup (local-name "com.apple.ls.boxd"))

Step 2: Clear the cache (you need to be root to do so) by running the following command.

rm -fr /System/Library/Caches/*

Step 3: Safeboot the Mac.
 - Shutdown the Mac first (remember to enable speaker volume before shutdown).
 - Start up the Mac. Just after the startup tone (cannot do it before the tone), press and hold the shift key.
 - When the grey apply logo appears, release the shift key.
 - After the system is up to the login screen, confirm that there is a red "safeboot" label at the upper right screen corner.
 - Then you can simply restart the Mac.

Enjoy the Mac without the fan noise.

Monday, October 22, 2012

problem of ICC (ld: cannot find -lpthread)

Problem:

I cannot compile my old project using the Intel Compiler. The error reported is

ld: cannot find -lpthread

Cause:

Playing with the pthread library is not helpful. The real problem is the "-fast" option which enables "-xHOST -O3 -ipo -no-prec-div -static" by default.

But my current OS is CentOS 6.3 which hates static library. So the last "-static" option is the cause of the problem.

Solution:

Replace the "-fast" with "-O3 -ipo -no-prec-div".

Friday, October 19, 2012

Decision

I will join Imagination Tech in a month time. Submitted my resignation letter to Imperial College today. Heading to the unknown ...

Thursday, October 18, 2012

installing CUDA driver in CentOS 6.3

Problem: The new CUDA 5.0 is out. This time, a single package including the driver, development tools and example codes. But the installation cannot finish by keep asking for reboot.

Cause: The CentOS 6.3 kernel boots with the "nouveau" feature enabled.

Solutoin:

Edit the /boot/grub/grub.conf such that the kernel line with the following at the end of the line: rdblacklist=nouveau

Edit the /etc/modprobe.d/blacklist.conf to append "blacklist nouveau" after the last line. 

Thursday, October 11, 2012

Problem of sharing folder in CentOS guest by VMWare

Host: Mac OS X 10.8.2
VMWare 5.0.1
Guest: CentOS 6.3 x86_64

Problem:
Cannot share a folder in OS X to CentOS, the /mnt/hgfs directory is empty.
When toggle the on/off of folder sharing in VMWare options, it reports errors that cannot mount directory.

Cause: unknown!

Solution: Reinstall the VMWare tools by selection the "Virtual Machine -> Reinstall VMWare tools".

Wednesday, October 10, 2012

Problems when building project in Xilinx XPS/SDK 14.2

1.

Symptom: Missing the libz.so during SDK compilation.

Cause: My system is CentOS 6.3 x86_64. But the Xilinx tool "as" in the 64-bit EDK directory is actually a 32-bit ELF executable. It is looking for the 32-bit libz.so instead of the 64-bit installed version.

Solution: Install the 32-bit libz.so by
yum -y install libzip.i686"


2.

Symptom: Missing the xil_cache.h file when compiling the platform.c file in SDK.

Cause: There are modules, created by XSP/BSB, have capital letter(s) in their module name (e.g. LEDs_8Bits, etc.).

Solution: Exit XPS. Edit the *.MHS file. Change all "INSTANCE" name with lower case letters only.


3.

Symptom: The simulation in XPS seams endless without clock and reset.

Cause: The XPS does not create testbench by default so there is no drive to these signals.

Solution: Check the "generate simulation template" option in the project options.

Saturday, November 26, 2005

The first word

Welcome.