Blog

xmllint: separate xpath result with newline
xmllint is a helpful tool for anazing xml files. one common usageis its xpath query, which can extract useful information from a xml file.for example, let th...
Dynamic firewall with firewalld
firewalld is a Linux firewall management tool which provides a dynamicallymanaged firewall with support for zones.firewalld features a two layer design: ...
nginx: Block IP-based access
There are 2 different methods to access a website: Through domain name: example.org. Through IP address: 1.2.3.4. Some site owners don’t want cl...
CSS trick: Centering an overflowed table
The trickiest HTML element to style is probably <table>. The <table> elementrepresents the older way of styling, and that’s much older than moder...
When nginx meets SELinux: 403 Forbidden
This error happens when: The nginx service is running on a SELinux system. The nginx service is started by systemd, not manually from shell by us...
Package manager cheatsheet
The table below contains package manager commands for common Linux distros.Haven’t used Gentoo for a while. What a pity. I will add it later if I find timeto...
How to make strong passwords
There is a four-volume document available covering how to make strong passwords,published by NIST: SP 800-63 Digital Identity GuidelinesThis document is in ...
Make PCManFM display thumbnails correctly
PCManFM is a very good file manager. However, when using PCManFM, a problem hastroubled me for a long time: When you rotate a JPEG image taken from mobiledev...
CJK fonts work together
There are many beautiful fonts available for Latin characters. There are alsoquite a few nice fonts for CJK (Chinese/Japanese/Korean) characters. However,it’...
Pretty print multi-byte characters
Many programs need to pretty print a series of data for better view and easierpost processing. For example, we may need a simple program len.sh which printst...
A git branch workflow
In this post I present a git branch workflow that has been working for years. Bymaking it public, I hope it will help other coding monkeys get bananas easily...
Dropbox IPO
S-1
Fix magnet saving in deluge
Deluge is a good software. However, recently I was plagued by a bug in itslatest stable version 1.3.15: It simply doesn’t save torrent fileswhen they are add...
Merkle–Damgård construction
Merkle-Damgård construction is a method of building collision-resistantcryptographic hash functions from collision-resistant one-waycompression functions. Th...
Good Old Android Docs
Current Android docs page: https://developer.android.com/index.htmlGood old Android docs page: https://stuff.mit.edu/afs/sipb/project/android/docs/index.ht...
Download Historical Versions of Firefox
A major change happened to Firefox recently: Starting from Firefox 57 (releasedon 2017-11-14), legacy add-ons will no longer be supported. Legacy add-ons ref...
Install Android Command-Line Tools
First of all, android create project no longer works.In fact, tools/android has been removed in SDK Tools 25.3.0:********************************************...
Deploy LEMP on Arch Linux
This article covers installation and configuration of LEMP (Linux + NGINX +MySQL + PHP) on Arch Linux.InstallationLinuxSee this guide.NGINXThere are 2 versio...
Object-Oriented Programming in Lua
this article shows how to implement class-based oop in lua using itsprototype-based system.table - the data structurefirst and foremost, always remember this...
GRUB: chainloader +1
In a GRUB configuration file, it’s very common to seechainloader +1The meaning of +1 is often obscure. For a long time it was misinterpreted asthe next bootl...
chroot: failed to run command
ProblemSteps to build a chroot environment: Make a directory /tmp/newroot as the new root: mkdir -p /tmp/newroot Compile a helloworld prog...
GRUB on a BIOS System
GRUB on a BIOS system can use either a Master Boot Record (MBR) disk or a GUIDPartition Table (GPT) disk.GRUB consists of several image files, the most impor...
Permutation Generation Algorithms
This article introduces common algorithms for permuation generation.Algorithm 1: Backtracking Algorithmdef perm_backtrack(l): ''' Switch-to-end backtra...
Bash Invocation
Historically, Bash invocation has confused many users, both experts and newbies.Bash forums are filled with questions such as: Why weren’t my commands e...
How to Write Bash Completion
Bash has a programmable completion feature that allows the command line to becompleted from a partial command with a press of the <Tab> key. This featu...
A simple Xlib program
For a long time, Xlib remained a mystery to me. My head grew biggerwhenever I saw a function starting with an X.But today I came up with a very simple Xlib p...
Hungarian Notation
Hungarian notation is an identifier naming convention in which the name of avariable or function is prefixed by its type or intended use. For example: lAcco...
Python3: Strings, chars and bytes
Every programmer uses strings. A string consists of a sequence of characters.However, to many people’s surprise, Python 3 doesn’t have a char type at all.You...
Install package data with setuptools
setuptools provides a package_data keyword argument in its setup()function for users to include package data for deployment and installation. Butthis keyword...
Floats and Decimals
IntroductionSome languages provide a decimal type in addition to the float or double types. What isdecimal and when do we use decimals instead of floats or d...
Android Wi-Fi hotspot and USB tethering
I know that the topic of Android tethering is old and dry. But there is just one more use case weneed to address.In this world, some stupid wireless access p...
Python Decorators
In Python, a decorator turns a function into another function. A decorator can be either a class or a function. A decorator with argument...
Karatsuba Algorithm
Karatsuba algorithm is a fast multiplication algorithm with time complexity\(O(n^{\log_2 3}) \approx O(n^{1.58})\).The basic idea is divide-and-conquer:This ...
Let's Encrypt
Let’s Encrypt makes it easy for any website owner to obtain a free, valid SSLcertificate.How to useThe tool it offers is certbot (previously named letsencryp...
JavaScript Inheritance
As a prototype-based language, JavaScript has a less apparent way of defining object hierarchies.But of course it’s doable.Prototype What is a prototype...
Huffman tree linear-time construction
From Wikipedia: If the symbols are sorted by probability, there is a linear-time (\(O(n)\)) method to create a Huffman tree using two queues, the first one...
Four-Square Theorem
The story begins with a coding problem: Given a positive integer \(n\), find the least number of perfect square numbers (for example, \(1, 4, 9, 16\), …) w...
Jekyll Assets
What is an Asset PipelineFrom http://guides.rubyonrails.org/asset_pipeline.html: The asset pipeline provides a framework to concatenate and minify or compre...
Edit Files In-Place
Sometimes we want to process a file and write back to the same file (aka in-place editing).However, the simplest shell redirection won’t do the job:cat a.txt...
HDFS High Availability
Background Prior to Hadoop 2.0.0, the NameNode was a single point of failure (SPOF) in an HDFS cluster. Each cluster had a single NameNode, and if that mac...
Strict Aliasing
Pointer aliasing is a common pitfall: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]From gcc man page: -fs...
Semantic Versioning
Given a version number MAJOR.MINOR.PATCH, increment the: MAJOR version when you make incompatible API changes, MINOR version when you add functiona...
Android Lollipop DNS Settings
Each new release of Android will bring you some change and require you to change. dumpsys is yourfriend. How to query/change the default gateway via bash on...
Android SMS and Call Logs Backup
#!/bin/bash# backup sms and call logs.adb shell su -c cp -r /data/data/com.android.providers.telephony/databases /sdcard/telephonyadb shell su -c cp -r /data...
Terminal Color Checker
Some terminal color checker scripts: Changing foreground: for c in {0..255} ; do tput setaf $c ; printf "%03d" "$c" ; tput sgr0 ; echo ; done | less ...
Postfix and Dovecot
Arch Wiki Postfix - Arch Wiki Virtual user mail system - Arch WikiPostfix README Postfix Address Classes Postfix Virtual Domain Hosting HowtoUbuntu Wiki ...
CAP Theorem
Conjecture. Proof. CAP Theorem: Explained. CAP Theorem: Revisited.
Bit Twiddling Hacks
The basic bit hack is probably No-Temp Swap:x = x ^ y;y = x ^ y;x = x ^ y;Today I learned there is also No-Branch Minimum:r = y ^ ((x ^ y) & -(x < y))...
Nagle's Algorithm and Delayed ACK
The story between Nagle’s algorithm and delayed ACK: Nagle’s algorithm TCP delayed acknowledgment TCP Performance problems caused by inter...
Regex for multiples of an integer
This article provides a method to construct a regular expression thatmatches multiples of 3. Here we generalize it and give a method to construct a regular e...
CUPS without root privilege
Run in terminal as rootgpasswd -a <username> sysThen in cpusd.conf, setSystemGroup sysBy default group sys should already be set in cupsd.conf, so the ...
Markdown Preview in Vim
Nate gives a nice script to preview Markdown files in Vim:http://blog.natesilva.com/post/5256838248/how-to-preview-a-markdown-document-in-vimBut he hasn’t te...
Find hard links
Find all hard links to a.txt in current directory:find -xdev -samefile a.txtDisplay the inode number of a.txt:ls -i a.txtFind all files (mutual hard links) w...
some interesting facts about USB connectors
There are two main types of USB connectors: Standard-A and Standard-B, eachwith its own plugs and receptacles.If you examine how they are used in our lives, ...
Rest In Peace, DMR
Most, if not all, of the fun of learning computer science was given by Unix and C.R.I.P. - Dennis MacAlistair Ritchie
Generate OpenSSL certificates
#!/bin/bash# prepare directory structuremkdir -p ./demoCA/{certs,crl,newcerts,private}touch ./demoCA/index.txtecho 00 > ./demoCA/serial# CAopenssl rand 20...
httptunnel
Server is hts. Client is htc. htc supports HTTP proxy and proxy authentication.# Server listens on port 80, and forwards to local port 22hts -F 127.0.0.1:22 ...
Paxos Made Simpler
In Paxos Made Simple, Leslie Lamport presented the Paxos algorithm in anintuitive way by starting from intuitions and then trying to fulfill the requirements...
Zero-Knowledge Sudoku
Say Victor has a Sudoku problem written on a paper but doesn’t know how to solve it. Peter knows thesolution. If there is a double-sided photocopier, how can...
Offline Wikipedia
This article introduces how to setup an offline Wikipedia which supportskeywords search.Before you start, you should read the great tutorial provided by Than...
Myhill-Nerode Theorem
Tom Henzinger’s notes about the Myhill-Nerode: http://www-cad.eecs.berkeley.edu/~tah/172/7.pdfA regular language L has finitely many equivalence classes. Sin...
Gödel's first incompleteness theorem
Gödel’s first incompletenesstheoremsays (excerpted from Wikipedia): For any consistent, effectivelygenerated formal theory that proves certain basic arithme...
busy beaver is uncomputable
http://www.earlham.edu/~peters/courses/logsys/turing2.htm (This proof lookscool. But I think in step (3) it should be \(n+d\) rather than \(n+1\).) ...
How to write a quine
A quine is a program which outputs itself when it runs. Recursion Theoremtells you how to write a quine for a Turing machine.But you may want toimplement one...
LaTeX templates: automata and quantum circuits
Here are two LaTeX templates, one for drawing automata, the other for drawingquantum circuits.AutomataThis templates uses pgf/tikz.Note. On Arch Linux, you c...
Type Russian In Linux
To input characters in alphabetic writing systems such as Russian, French andGerman, you don’t have to install an input method. You can just change thekeyboa...
Linux file associations
To set file associations, there are 2 configurations you should care about: mime-type definition application associationTo set mime-type definition, open /...
AWStats for Nginx
AWStats is a log analyzer and supports Apache well. To use it with Nginx,however, you should fine-tune some details.But for now, let’s get familiar with AWSt...
scrot
Scrot is definitely a cute but powerful screenshot tool.Fullscreen shotscrot a.pngManually pick a windowscrot -s a.pngCountdown (specified with -c, and delay...
HighID for aMule
If you are in a LAN, in which there is a server that has public network IP,then you just do a port map using iptables. DNAT, specifically.Suppose the server’...
POSIX shared memory
Just have a try with the examples provided by Operating System Concepts, P103, with some modification.Run sm_alloc first, and you’ll receive a shared memory ...
djvu single page extraction
Tried to find a tool which can extract a page from a multi-page .djvu file,but failed. djvutoy in Windows may do that job, but no counterpart found inLinux.S...
xset auto-repeat
I love fast auto-repeat but I don’t want it happen on the XF86AudioMute keys. What surprised me wasthat I found xset provides the function of configuring aut...
Gnome application accelerate key setting
Add a new file ~/.gtkrc-2.0, write the following line in it:gtk-can-change-accels = 1Source this file and open a Gnome application such as evince. Move curso...
core dump
Generally, when you write and run a program, and then receive a Segmentationfault, you’d be confused where the problem happens. You use gdb to debug theexecu...
three C tips
This example says sizeof can be used on a dereferenced pointer, even if it is of type struct *, and doesn’t point to anything. This is because the size...
Linux sound systems
Linux sound system is, well, really a mess… Look at the following pictures:Maybe these articles will help:http://www.linux.com/archive/feature/113775http://w...
256-color SGR sequence
As we all know that by editing .bashrc we can give less a colorful appearance.However, the 16-color scheme looks a little bit ugly. For example, if I wantto ...
radial engine
Look at this engine! It looks so sexy!Well, they are formally called radial engines, and are used in aircraftshaving propeller connected to the shaft deliver...
a C comment trick
Today I saw a trick to comment and uncomment multiple lines of code in C. Ituses both /*...*/ and // to comment as below:/* foo(); bar();//*/To uncomme...
headers with the same names in gcc
Suppose we have the following program main.c:#include <stdio.h>#include "main.h"int main(){ extern int k; printf("%d\n",k); return 0;}And we c...
Xlib Tutorial
A tutorial of Xlib.http://users.actcom.co.il/~choo/lupg/tutorials/xlib-programming/xlib-programming.htmlAnd I strongly recommend you go to the Tutorials home...
git reset
reset is a useful command in Git. Basically, it has three options: hard soft mixed(default)In all the three cases, reset will reset the HEAD pointer(see b...
Set Keyboard Auto-Repeat Delay and Rate
Sometimes you may find it not convenient to have a too long auto-repeat delayand rate. However, you can easily adjust them, both in console and X. conso...
Volume Control OSD for Openbox
I’ve looked up a lightweight volume control OSD for Openbox for over an hour. Iwant it simple, no-dependency and XF86Audio-keys-supported so it’s really har...
xmledit
xmledit is a Vim filetype plugin to ease XML/HTML file editing.xmledit is available at AUR. You can install byyaourt vim-xmleditTo add HTML support, after do...
xbindkeys
Do you have extra keys on your keyboard, mouse or laptop that are never used?For example, you may not be a Korean but buy a keyboard which has Korean-specifi...
Conky
Conky is a light-weight system monitor.Conky’s Homepage: http://conky.sourceforge.net/index.htmlIt can be easily customized by editing ~/.conkyrc, and the fo...
nvidia-xconfig
I remember when I install X.Org for the first time, it troubles me what tool Ishould use to generate the /etc/X11/xorg.conf file. There are multiplechoices: ...
Knuth's .fvwm2rc
Prof. Knuth uses fvwm and has this beautiful .fvwm2rc file.
Ctags and Cscope
ctags and cscope are the 2 most useful tools for source code browing andediting, especially in Vim.ctags - generate tag files for source codeBasic usage: ...
Linux Compression/Decompression Commands
There are some utilities for compression and decompression on Linux that areused often. Now I’ll explain their usages one by one.Suppose we have files a.txt,...
HTTPS For Nginx
Generate key pair using OpenSSLopenssl genrsa -out my.key 2048Generate a Certificate Signing Requestopenssl req -new -key my.key -out my.csrSign the Certific...
gpg
(excerpted and modified from http://www.gnupg.org/gph/en/manual.html)Suppose the key is:Cyker Way (Cyker Way’s personal key) [email protected]# Generate key pa...
LaTeX Equation Environments
As we all know, there are many equation environments to choose, including equation multline align eqnarray IEEEeqnarrayI prefer $$ for inline equation ...
Beamer Tutorial
This is a very good Beamer tutorial written by Professor Rouben Rostamian atUMBC. Look it through.http://www.math.umbc.edu/~rouben/beamer/And Professor Rosta...
Google Font API
You can add web fonts to your pages using this API. What is needed is onlyadding a special stylesheet link to your pages. For example, using thefollowing cod...
sizeof All Basic Types in C++
#include <iostream>using namespace std;int main(){ // type bool cout << "bool = " << sizeof(bool) << endl; // type char c...
LaTeX Resume Templates by rpi.edu
A group of resume templates, originally designed by the Rensselaer CareerDevelopment Center, are available in LaTeX format.http://www.rpi.edu/dept/arc/traini...
Dropbox referral
Well, this post is for a Dropbox referral. For those who haven’t had a Dropboxaccount, I strongly recommend this online service to sync, store and shareyour ...
The Online Books Page
The Online Books Page is a list offree online books held by University of Pennsylvania.I like this kind of lists maintained by world-class universities and r...
Wow6432Node
The HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node registry entry indicates thatyou’re running a 64-bit version of Windows. The OS uses this key to present aseparat...
TopCoder Plugins
Plugins CodeProcessor http://www.topcoder.com/contest/classes/CodeProcessor/CodeProcessor.jar FileEdit http://www.topcoder.com/contest/clas...
MSS problem of Android
I once used Linux to set up an ad-hoc network and connected with it using anAndroid phone with static IP. I used iptables to do NAT. The Android phone canget...
voxforge
Thisdocumentprovides a list of some widely-used speech corpora. However, most of themrequire a charge.After searching for some time, I find the projectvoxfor...
Filesystem Hierarchy Standard
When I was a stark beginner of Linux, I always wondered where should I placefiles, and how to compile source code to make sure the corresponding binariesare ...
Implementing Graphs In Python
This article introduces how to use List and Dict to implement a graph represented as anadjacent list in Python.
Modify DNS Server In Windows
Find network interface name with:ipconfig /allChange DNS server with:netsh interface ipv4 set dns name="Local Area Connection* 12" static 8.8.8.8 primary
Retrieve Wallpapers From Chrome Themes
Log into Google Chrome Themes Gallery and you’ll find a lot of theme files withextension .crx. By default, Chrome will automatically apply this theme if youc...
Sikuli
Have you ever programmed like this?It’s a project named Sikuli from MIT. From its official website: Sikuli automates anything you see on the screen. It uses...
Use CLSID to create system folders
According to MSDN: A CLSID is a globally unique identifier that identifies a COM class object.CLSIDs can be used to create system folders such as My Compute...
py2exe
py2exe is a tool which turns .py to .exe (on Windows platform) Install py2exe at http://sourceforge.net/projects/py2exe/. Write a setup script fo...
Use Gdiplus to Read An Image
#include <windows.h>#include <gdiplus.h>#include <stdio.h>using namespace Gdiplus;#pragma comment(lib, "gdiplus.lib")INT main(){ Gdiplus...