Mount smb share on Mac OS using mount-smbfs command

mount_smbfs "//DOMAIN;" /Volumes/test

Enable iglx on Mac OS (XQuartz) or Linux for JavaFX Applications

When executing a Java FX application on a remote SSH server by forwarding display to local X11(XQuartz), I got this error:

libGL error: No matching fbConfigs or visuals found
libGL error: failed to load driver: swrast
X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  149 (GLX)
  Minor opcode of failed request:  24 (X_GLXCreateNewContext)
  Value in failed request:  0x0
  Serial number of failed request:  25
  Current serial number in output stream:  26

searched and found this solution:


  • On Mac OS(XQuartz), execute the command below in Terminal:
    defaults write org.macosforge.xquartz.X11 enable_iglx -bool true
    and restart X11(XQuartz)
  • On Linux, try this

see also

Install SSL certificate on Mediaflux server

  1. Generate certificate request and private key. (The private key can be reused to generate new requests for renewing the certificate.)
    • Create a request configuration file named your-domain-name.csr.conf like below:
      # PrintableStrings only
      ST=Your State
      L=Your City
      O=Your Organization
      OU=Your Organisation Unit
    • Generate certificate request using the command below:
      openssl req -config your-domain-name.csr.conf -new -days 3650 -keyout your-domain-name.key -out your-domain-name.csr
      You should now have the generated private key file: your-domain-name.key and request file: your-domain-name.csr. Keep the private key file in safe for future certificate renewal requests.
  2. Submit the generated your-domain-name.csr file to be signed by CA (You only need to sumit the csr file.) And you should get CA signed certificate: your-domain-name.crt
  3. Install the CA signed certificate:
    • Convert private key to .p8 format:
      openssl pkcs8 -topk8 -inform PEM -outform DER -nocrypt -in your-domain-name.key -out your-domain-name.key.p8
      You only need to do this once and keep the your-domain-name.key.p8 file together with your-domain-name.key for future certificate installations.
    • Install the CA signed certificate using the command below in Aterm:
      server.certificate.identity.import :in file:/path/to/your-domain-name.key.p8 :in file:/path/to/your-domain-name.crt :replacement true
      It should return the imported certificate identity entry. Remember the id of the identity to be used in the next step.
    • Set default certificate alias the the newly installed certificate identity (assume its id is 2): :property -name server.default.certificate.alias 2

openssl commands to check certificate, request and private key

  • Check a certificate: Check a certificate and return information about it (signing authority, expiration date, etc.):
    openssl x509 -text -noout -in server.crt
  • Check a key: Check the SSL key and verify the consistency:
    openssl rsa -check -in server.key
  • Check a CSR: Verify the CSR and print CSR data filled in when generating the CSR:
    openssl req -text -noout -verify -in server.csr
  • Verify a certificate and key matches: These two commands print out md5 checksums of the certificate and key; the checksums can be compared to verify that the certificate and key match.
    openssl x509 -noout -modulus -in server.crt | openssl md5
    openssl rsa -noout -modulus -in server.key | openssl md5

Shell scripting: get total file sizes of a directory

find . -type f -exec du -ch {} + | grep total$
find . -type f -name '*.java' -exec du -ch {} + | grep total$
find . -type f -name '*.pdf' -exec du -ch {} + | grep total$

Eclipse Debug Arguments: double dashes are replaced by single long dash automatically. How to disable smart dashes substitution?

On Eclipse Oxygen, when input double dash -- into "Arguments" of "Debug Configurations...", It substitutes double dash -- with single long dash —
It is really annoying. You cannot even input the correct arguments. The only way to make it work is to disable "Smart Dashes" See below:

  • Right click the Arguments area to open the context menu
  • Select "Substitutions" then uncheck "Smart Dashes"
  • Now you should be able to input double dashes

Mediaflux TCL script: loop through query results with cursors

set size 100
set idx 1
set remaining 1

while { $remaining > 0 } {
    set r [asset.query :size $size :idx $idx :count true :where "namespace>=/test"]
    foreach id [xvalues id $r] {
         puts $id
    set idx [expr { $idx + $size }]
    set remaining [xvalue cursor/remaining $r]

Python pysftp: bypass ssh host key verification

import pysftp

cnopts = pysftp.CnOpts();

# set hostkeys to None to disable ssh key verification
cnopts.hostkeys = None
   sftp = pysftp.Connection(host='', username='sftp-user', password='password', port=22, cnopts=cnopts)
   if sftp:

Windows Batch Script: remove trailing slash from a path string

set "a=C:\Users\wx\Downloads\"
if "%a:~-1%"=="\" set "a=%a:~0,-1%"
if "%a:~-1%"=="/" set "a=%a:~0,-1%"
echo %a%

see also

Windows Batch Script: parse arguments

@echo off
setlocal EnableExtensions EnableDelayedExpansion

set verbose=false
set value=

if "%~1"=="" (
    if "%~1"=="--help" (
        call :help
        exit /b 0
    if "%~1"=="--value" (
        set value=%~2
        goto :loop
    if "%~1"=="--verbose" (
        set verbose=true
        goto :loop
    goto :loop

see also

Windows Batch Script: check if argument exists

if "%~1"=="" ( echo exists ) else ( echo not exist )

Windows Batch Script: command argument expansion

expands %I removing any surrounding quotes:
%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

Windows Batch Script: string operations

  • substring:
    set "var=apple pear"
    echo %var~6,4%
    REM pear
    echo %var~0,-5% 
    REM apple
  • replace character:
    set "var=a,b,c"
    REM replace commas with spaces
    echo %var:,= %
    REM a b c

see also

Windows Batch Script: comma in command arguments

Comma (or semicolon) in command arguments, if not quoted, are considered separators (same as white space). See the script (named test.bat) below:
@echo off
if not "%~1"=="" (
    echo %~1 
    goto :loop
When calling the script,
if not quoted:
test.bat 1,2,3

if quoted:
test.bat "1,2,3"

Windows Batch Script: enable delayed expansion

In compound code blocks, with setting EnableDelayedExpansion, the current value will NOT assigned to the variable as expected. see the code below:
set var=1
set switch=on

if "%switch%"=="on" (
   set var=2
   echo %var%
   REM it prints 1
It actually prints the original value 1. To avoid such unexpected behaviour, you need to set EnableDelayedExpansion, and using !var!:
setlocal EnableDelayedExpansion
set var=1
set switch=on

if "%switch%"=="on" (
   set var=2
   echo !var!
   REM it prints 2

see also

Windows Batch Script: split comma delimited string and loop through the tokens


SET emails=%emails:,= %

FOR %%e in (%emails%) DO (
    echo %%e

Windows Batch Script: replace a character in string

SET str=1,2,3,4

REM replace comma with blank space
SET str=%str:,= %
ECHO %str%

see also

Windows Batch Script: get the script file name


  • ~ -- strip/trim quotes off
  • d -- drive
  • p -- path
  • n -- file name
  • x -- extension
  • f -- full path


suppose I have a script file at C:\Users\WXYZ\Documents\test.cmd
REM test.cmd
ECHO %~0

REM test
ECHO %~n0

REM .cmd
ECHO %~x0

REM C:\Users\WXYZ\test.cmd
ECHO %~dpf0

REM C:\Users\WXYZ\test.cmd
ECHO %~dpnx0

REM C:\Users\WXYZ\test
ECHO %~dpn0

REM C:\Users\WXYZ\
ECHO %~dp0

see also

Windows Batch Script: escape special characters in ECHO

REM This is a <test>
ECHO This is a ^<test^>

see also

Windows Batch Script: IF THEN ELSE

    ECHO success
) ELSE (
    ECHO failure

Shell script: parse arguments

The best answer:

BASH script: split string to array

IFS=',' read -r -a array <<< "$str"

for e in "${array[@]}"
    echo $e

see also

Shell scripting: extract substring (or path components) from string in BASH

str="I like shell scripting."

echo ${str:7:5} # 7 is offset, 5 is length, it will print shell

echo ${path#*/}     # trim the prefix: a/b/c
echo ${path#/a/}    # trim the prefix: b/c
echo ${path#$root/} # trim the prefix: b/c
echo ${path#*b}     # trim the prefix: /c

echo ${name%/*}   # trim the suffix: /a/b
echo ${name%.txt} # trim the suffix: /a/b/c

see also

Shell scripting: loop through an array or positional access

# declare a empty array
declare -a array1=()


echo ${array1[0]} # foo
echo ${array1[1]} # bar

for elem in "${array1[@]}"
    echo $elem

Shell scripting: append element to array

declare -a array1=()

for elem in "${array1[@]}"
    echo $elem

Shell scripting: check if an array is empty

declare -a array1=()

if [[ ${#array1[@]} -eq 0 ]]; then
    echo "array1 is empty"

echo "array1 has ${#array1[@]} elements"

echo "array1 has ${#array1[@]} elements"

Windows Batch Script: download file using bitsadmin without ssl certification validation

  • For the web server that does not support content range requests. You have to set priority to FOREGROUND to force the job to run synchronously. Otherwise, error: BG_E_INSUFFICIENT_RANGE_SUPPORT (0x80200013)
    bitsadmin /transfer MyJob /priority FOREGROUND  "" "C:\test\"
  • For the web server with self signed certificate or could not pass the ssl certificate validation, you cannot use a single bitsadmin /transfer command and the job has to be run asynchronously. You have to bitsadmin /create a job and bitsadmin /SetSecurityFlags to value 30
    bitsadmin /create MyJob1
    bitsadmin /addfile MyJob1 "" "C:\test\"
    bitsadmin /SetSecurityFlags MyJob1 30
    bitsadmin /SetPriority MyJob1 FOREGROUND
    bitsadmin /resume MyJob1
    bitsadmin /monitor || bitsadmin /cancel MyJob1

see also

curl and wget: bypass ssl certification validation

  • --insecure or -k for curl:
    curl --create-dirs -k -o /path/to/output-dir/file
  • --no-check-certificate for wget:
    wget --no-check-certificate -O /path/to/output-dir/file

curl and wget: create parent directories

curl --create-dirs -o "/path/to/output-dir/file.txt" ""
mkdir -p "/path/to/output-dir" && wget --no-check-certificate -O "/path/to/output-dir/file.txt" ""

Bash scripting: check whether the script is sourced or executed in subshell

if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
    echo "sourced"
    echo "executed"

The example below, call return if the script is sourced otherwise call exit:
my_func1 || ( if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then return 1; else exit 1 )

see also


Shell Script: if then else in one line

if [[ ${a} -ge 0 ]]; then echo "positive number"; else echo "negative number"; fi

if [[ $? -ne 0 ]]; then echo "failure"; else echo "success"; fi

Windows Batch Script: Download file using powershell

SET "url="
SET "out=C:\Downloads"
POWERSHELL -COMMAND "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};(New-Object Net.WebClient).DownloadFile('%url%', '%out%')"
NOTE: [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} bypass the SSL certificate validation.

See also

Windows Batch Script: call multiple powershell commands in one line

Multiple powershell commands are separated by semicolons:
POWERSHELL -COMMAND "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};(New-Object Net.WebClient).DownloadFile('%url%', '%out%')"

Windows Batch Script: conditional exit one line

CALL :FUNC1 || ( ECHO "Error: exit code=%ERRORLEVEL%" && EXIT /B 1 )

Windows Batch Script: Create directories recursively

SETLOCAL EnableExtensions
SET dir="C:\A\B\C"
MD "%dir%"

Windows Batch Script: dirname equivalent, get the parent directory of a file

Note: the code below can handle the path contains spaces:
  • Option 1:
    SET filename="C:\Files\A Dir\file1.txt"
    FOR %%F IN (%filename%) DO SET "dirname=%%~dpF"
    ECHO %dirname%
  • Option 2:
    SET "filename=C:\Files\A Dir\file1.txt"
    FOR %%F IN ("%filename%") DO SET "dirname=%%~dpF"
    ECHO %dirname%

Remote desktop to Ubuntu Linux via x2go

I. Install X2Go server on the remote Ubuntu Linux host

  1. Add the X2Go repository:
    sudo add-apt-repository ppa:x2go/stable
    and confirm this with [Enter]. Then, update the package lists:
    sudo apt-get update
  2. Install the X2Go server:
    sudo apt-get install x2goserver x2goserver-xsession
  3. Install extra bindings depend on what window manager you use:
    • for LXDE:
      sudo aptitude install --reinstall lxde lxsession-logout x2golxdebindings
    • for GNOME:
      sudo apt-get install x2gognomebindings
      GNOME only works for versions earlier than gnome 3.10, better earlier than gnome 3.08
    • for KDE:
      sudo apt-get install plasma-widget-x2go
  4. Test if the service is up and running:
    sudo service --status-all | grep x2go
    If not, try starting it manually:
    sudo service x2goserver start

II. Install X2Go Client on the local computer

  • Windows: Download and install the newest windows client from the X2Go website
  • Linux:
    sudo apt-get install x2goclient
  • Mac OS:

III. Connect to remote Linux host using X2Go client

  • For Mac OS, starts XQuartz first then X2Go client. You need to set the prefences of XQuartz to allow connections:

See also

Java: System Tray (awt) to control JavaFX application

System Tray (AWT) to control a JavaFX application.

Java: watching directory for changes

see also

Java: Open a socket only listening to localhost

new ServerSocket(9090, 0, InetAddress.getLoopbackAddress());

see also

NoMachine: Setup public key authentication

  • Server side:
    • Edit ~/.nx/config/authorized.crt and append public key to it.
      mkdir -p ~/.nx/config
      vi ~/.nx/config/authorized.crt

see also

Java & Python SSH/SCP Code examples

Acrow Prop Hire in Melbourne


Smart Hire Oakleigh

21-25 Coora Road,Oakleigh South, VIC 3167
Phone: 03 8546 5744

Smart Hire Carnegie

1076 Dandenong Road,Carnegie, VIC 3163
Phone: 03 9571 9488

Trading Hours

We're open on the following day and hours:
Mon to Fri: 7am - 5pm
Sat : 7:30am - 1pm
Sun: Closed

Sum the file sizes on Linux

find ./test -type f -name '*.jpg' -exec du -cb {} + | grep total$

Windows batch scripting notes

  • pass all arguments:
    java -jar app.jar %*
  • logical AND in IF conditionals
    IF %age% geq 18 (
        IF %age% leq 68 (
            SET class=working
    IF %age% geq 0 IF %age% leq 18 SET class=children
  • logical OR in IF conditionals
    SET children_or_elderly=F
    IF %age% leq 18 set children_or_elderly=T
    IF %age% geq 60 set children_or_elderly=T
    IF "%children_or_elderly%"=="T" (
        ECHO kids or retired
  • Test if the argument exists
    IF [%1] == [] ECHO No arguments
  • Count number of arguments
    SET nbArgs=0
    FOR %%x IN (%*) DO SET /A nbArgs+=1
    ECHO %nbArgs%
  • Check if file exists
    IF NOT EXIST C:\FILE2.TXT ECHO not exist

see also

Sort LinkedHashMap by key or by value in Java 8

Java 8 Collection Stream in reverse order

GWT override css from theme

  • Create css file in com/myapp/client/resource/myapp.css:
    • body, table td, select {
        font-family: Helvetica, Arial Unicode MS, Arial, sans-serif;
        font-size: small;
      .my-css-class {
  • Create client bundle file:
    • package com.myapp.client;
      public interface Resources extends ClientBundle {
        public static final Resources INSTANCE = GWT.create(Resources.class);
        public interface Style extends CssResource {
        @ClientBundle.Source("resource/myapp.css") // relative path to the css file.
        @CssResource.NotStrict // No compile error if no css class in the css file.
        Style css();
  • In the entry point class:
    • package com.myapp.client;
      public class MyApp implements EntryPoint {
        public void onModuleLoadSafe() {
          // Inject the css
          // ... ... ...

Mediaflux example: tcl script to repair metadata with empty string as attribute

foreach id [xvalues id [asset.query :where xpath(daris:pssd-derivation/input/@vid)='' :size infinity]] {

    set args ":id ${id} :meta -action remove < :daris:pssd-derivation > :meta < :daris:pssd-derivation"

    set doc [xelement asset/meta/daris:pssd-derivation [asset.get :id ${id}]]

    set doc_id [xvalue daris:pssd-derivation/@id ${doc}]

    set args "$args -id ${doc_id} < "

    set processed [xvalue daris:pssd-derivation/processed ${doc}]

    set args "$args :processed ${processed}"

    foreach input [xvalues daris:pssd-derivation/input ${doc}] {

        set vid [xvalue asset/@vid [asset.get :cid ${input}]]

        set args "$args :input -vid ${vid} ${input}"


    set method [xvalue daris:pssd-derivation/method ${doc}]

    set step [xvalue daris:pssd-derivation/method/@step ${doc}]

    set args "$args :method -step ${step} ${method}"

    set args "$args > >"

    puts "asset.set $args"
    asset.set $args


Extract table data from PDF to CSV spreadsheet

UniSurf 8 Windows Tablet: Boot from USB

  1. Connect USB hub to the tablet and connect mouse and keyboard to the USB hub.
  2. Log into the Windows Environment, reboot to see BIOS.
  3. Set up BIOS as below:
    • Chipset
      • South Bridge
        • USB Configuration
          • USB OTG Support: PCI Mode
          • USB VBUS: OFF
    • Security
      • Secure boot menu
        • Secure boot: disabled
    • Boot
      • Setup prompt timeout: 15
      • Quiet boot: disabled
    • Save and Exit
      • Boot override
        • Select <your USB Flash Drive>
  4. Reboot from the USB