2020/04/26

A gotcha on python's round method (Banker's rounding)

Before studying the gotcha, let’s have a quiz, and see whether you will fall into the trap on round() or not.
Try to round below 22 float numbers to nearest integer, and see whether you can get them all correct. Below is the quiz in python.
floatNumbers = [1.1, 1.2, 1.3, 1.4, 1.49, 1.5, 1.51, 1.6, 1.7, 1.8, 1.9]
roundNumbers = list(map(round, floatNumbers))
formatFloatNumbers = ['%.02f' % num for num in floatNumbers]
formatRoundNumbers = ['%.02f' % num for num in roundNumbers]
print('Q', formatFloatNumbers)
print('A', formatRoundNumbers)

floatNumbers = [2.1, 2.2, 2.3, 2.4, 2.49, 2.5, 2.51, 2.6, 2.7, 2.8, 2.9]
roundNumbers = list(map(round, floatNumbers))
formatFloatNumbers = ['%.02f' % num for num in floatNumbers]
formatRoundNumbers = ['%.02f' % num for num in roundNumbers]
print('Q', formatFloatNumbers)
print('A', formatRoundNumbers)
Below is the answer.
Q ['1.10', '1.20', '1.30', '1.40', '1.49', '1.50', '1.51', '1.60', '1.70', '1.80', '1.90']
A ['1.00', '1.00', '1.00', '1.00', '1.00', '2.00', '2.00', '2.00', '2.00', '2.00', '2.00']
Q ['2.10', '2.20', '2.30', '2.40', '2.49', '2.50', '2.51', '2.60', '2.70', '2.80', '2.90']
A ['2.00', '2.00', '2.00', '2.00', '2.00', '2.00', '3.00', '3.00', '3.00', '3.00', '3.00']
The gotcha is on 2.50 case. Result of rounding 2.50 will be 2.00 instead of 3.00. And, this is a default, and correct behavior on rounding.

Why?

This rounding behavior is named as Round half to even
In short, this is a limitation from hardware. Since I am not going to go through the hardware’s limitation here, I suggest you to read this to have a full picture on them.
In fact, I would like to focus on another naming of this rounding: Banker's Rounding

Banker’s Rounding

Beside surprised by the behavior, I am also surprised on another name of this rounding technique, which is Banker's Rounding.
As the name stated, it is a rounding used by banks. So, why would banks adopt this strange rounding at all? Interestingly, this is because of Fairness.
Earning money is a job of banks (and for all companies). But, banks need to do it in a legal, and fair way. Rounding is essential on bank’s deals. For example, time deposits, and credit card’s loan etc. To round up / round down a number to the nearest integer, there are 9 cases (from 0.1 to 0.9).
Numbers will be evenly distributed among these 9 cases in statistical point of view. Banks round down numbers in 0.1 ~ 0.4 while round up numbers in 0.6 ~ 0.9. Chances for banks paying more or lesser is even (fairness) for these 8 cases. The problematic case is 0.5. If banks round up on 0.5, it will pay much more (5 cases), investors must be angry about that. Vice versa, if banks round down on 0.5, clients must be mad about that.
As a result, banks adopt round half to even to fix this fairness issues. After adopting this rounding, a single 0.5 case will be divided into 2 cases (even or odd cases). Banks will have equal chances on rounding up / down numbers. That’s why it is also named as Banker's rounding
IMO, this is a really clever trick to make every parties happy.

References

​

2020/04/25

Color matters! Enable semantic Highlighting in your IDE NOW

Color matters

As software developers, we read, and write codes every work day. Code with color highlighting is one of critical features provided by IDE.
Recently, there is a new technique semantic highlighting provided by IDEs (vscode, pycharm, etc), which is an advance version of syntax highlighting. I strongly recommend readers to enable it NOW. (I got this technique from this blog post)

Syntax highlighting

Firstly, let me try to convince you why color matters on dealing with codes by showing the syntax highlighting feature on / off.
Below is a snippet captured from Django RegexValidator.
With syntax highlighting No Color
As the feature name syntax highlighting suggested, we can easily tell variables, keywords, and class names from sea of codes.
IMO, I will be dead if there is no syntax highlighting when reading codes.

Semantic highlighting

While syntax highlighting colorizes codes based on coding syntax, Semantic highlighting colorizes codes based on the semantic. Take a look the comparison below if you are not sure the differences between them.
With syntax highlighting With semantic highlighting
In syntax highlighting, variables are all in same color while they have an unique color in semantic highlighting.
Variables are same type of syntax. Therefore, they share same color in syntax highlighting. But, in semantic point of view, they are differences. Therefore, each of them has unique color.
IMO, semantic highlighting is far more useful than the syntax highlighting. By reading the colors, you can tell the scope of a variable.
This is VERY critical for writing / debugging codes. Given a sea of variables inside a function, if they are in same color, you need to understand each of them to find out which one is wrong. With semantic highlighting, your work maybe easier by simply reading colors inside that function.
Honestly, the visual impact between two highlighting is smaller than the one between color on / off. But, I am still strongly recommend you to enable semantic highlighting NOW.
By the help of semantic highlighting, I am more confident to write correct codes at the first time.

Let’s enable semantic highlighting. But how?

Pycharm

Since I am a fan of pycharm, below is the manual for enabling semantic highlighting

Other IDEs

Modern IDEs nowaday have a search function. You can find the switch by just typing semantic highlighting inside that search function.

Customize the color scheme

To save our times on configuring coding colors, there are feature named as color scheme, which pre-configure colors for you. Instead of setup from scratch, I recommend readers to start from picking color themes.
There are lots of builtin color themes for you to select in modern IDEs. If none of them fulfill what you need, you can download color themes, as a plugin, from other developers.
Personally, I am using a color theme from GAP
Of cause, you can still fine tune the colors in each color scheme in your IDE settings.

Tips on testing colors in PYCHARM

  • Switching theme quickly
By hotkey ctrl+`, you can invoke a color menu for you to switch color theme.

References

​

2020/01/18

Kindle books from simplified Chinese to traditional Chinese

Why having this blog

As you may not know, online books in traditional Chinese are much fewer than simplified Chinese. Luckily, we can translate simplified Chinese, or vice versa, to traditional Chinese since, typically, they are just different representation. This is a blog post for recording the studied I have made for this translations.
To be honest, this is just a blog post for summarizing links, and blogs in the same place.

Method one: Convert the book directly

For readers able to read Chinese, please go to this link

Install Calibre

Download Plugin

Install the plugin into Calibre

Guides on using that plugin

  • Follow instructions in operation section
  • Follow instructions from the attachments

Upload your translated book

Once your book is translated, you can send them via Calibre directly. For me, I plug in my kindle, via USB, to my desktop. Then, click send file to the device in Calibre menu. Done.

Method two: Upgrade kindle, and translate them natively

For readers able to read Chinese, please go to this link

Select Firmware from amazon

  • To support translation natively, firmware version must be at least 5.9.6
  • Usually, you can upgrade your firmware via kindle’s menu

Video steps for upgrading firmware manually

Install fonts

  • Unzip the zip file
  • Connect your kindle to the desktop via USB
  • Put one of the ttf under font folder in your kindle

Change language

  • Open your ebook in kindle
  • Change the language in the display menu
  • enjoy

Notes

None of my ebook can rely on this translation. According to the guide from amazon, you are not allowed to use the custom font if your ebook does not support. I have, however, unable to find a way to confirm this requirement from my ebook.
Method 2 is just a record for my study.

Useful links

Epub 2 mobi

azw 2 epub

​

2019/05/13

Renew SSL certificate from GoGetSSL for self hosted Gitlab Server

About

As one of our SSL Certificate will be expired soon, I need to renew such SSL certificate for my gitlab server. This is a blog about how to renew SSL certificate, which purchased from GoGetSSL, and installed them into Gitlab Server. Here is another related blogpost, which talks about certificates, from me in one or two years ago.

Renew From GoGetSSL

As steps for purchasing certificate are really creepy, I would like to mark up some notes here.
  • Login your administrative account in GoGetSSL
  • Locate your expired soon certificate
  • Click Start Renewal. They are text and kind of hidden in a bunch of messages.
  • Complete the bill process
  • Remember to click RENEW instead of NEW ORDER when submitting CSR FORM. Otherwise, your new certificate cannot get remaining days from your last certificate
  • Validate your information as guided in the website

Certificate zip

After completing steps in above section, you should get an email from GoGetSSL which includes a certificate zip for your installation. Below is a list from such zip file.
  • DOMAIN.ca-bundle
  • DOMAIN.crt

Install SSL certificate to the Gitlab Server

As there are some installation guides provided from GoGetSSL, you may be able to find the one you need if you are lucky enough. In my case, I am not :)
Below are steps for the installation
  • Get certificates listed above to the gitlab server
  • Concatenate ca-bundle and crt together
    • This step does not necessary if your certificate does not contain intermediate certificate
    • Please checkout my old blog if you are not sure what is intermediate certificate
    • If you do not concatenate them together, some browser (FIREFOX DAMN) may view your certificate is a bad certificate while some does not (CHROM ROCKS)
mv DOMAIN.crt dummy.crt
cat dummy.crt DOMAIN.ca-bundle > DOMAIN.crt
rm dummy.crt
  • Change certificate’s permission
chown root:root DOMAIN.crt
chmod 644 DOMAIN.crt
  • Override your original certificate in the gitlab server
mv DOMAIN.crt /etc/gitlab/ssl/ORIGINAL_CERT
  • Move the ca-bundle to your system certificate directory
    • These steps may be unnecessary
    • In my Ubuntu system, the system certificate directory is `/etc/ssl/certs
  • Compute the hash of ca-bundle for creating a symbolic link
  • Create a symbolic link for the system to read
    • The symbolic should ends with .0
mv DOMAIN.ca-bundle /etc/ssl/certs
openssl x509 -in DOMAIN.ca-bundle -hash -noout
SOME_OUTPUT
cd /etc/ssl/certs
ln -s DOMAIN.ca-bundle SOME_OUTPUT.0
  • Restart gitlab server to complete the certificate renewal process
 sudo gitlab-ctl restart

Useful debug commands

  • Verify the chain of certificate
 /opt/gitlab/embedded/bin/openssl verify -CApath /etc/ssl/certs/ DOMAIN.crt
​

2018/11/25

A stupid way to semi automate steps for creating Merge Request on gitlab

Hello all. I have been away for writing a blog a while. Today, I would like to share how I semi automate steps for creating a MR on gitlab via command line.

Show me source codes

This is simply a script for filling information, for regular MR contents, and open a browser, which is a GUI for me to verify the contents, to fire MR. It, however, saves my time for filling boring and redundant MR contents. Here we go.

import subprocess

# Where is your project: NAMESPACE/REPO_NAME
MR_URL_ARGVS = {
    'NAMESPACE': 'mondwan',
    'REPO_NAME': 'scripts_for_creating_gitlab_mr',
}

# What will be the arguments for the MR URL
MR_SETTINGS = {
    # 'source_branch': 'feature_branch_1',
    'target_branch': 'master',
    # 'force_remove_source_branch': 'true',
    'title': 'New%20MR',
    # User ID in the gitlab
    'assignee_id': '1158561',
}

# The base url
MR_URL_BASE = \
    'https://gitlab.com/{NAMESPACE}/{REPO_NAME}/merge_requests/new?'.format(
        **MR_URL_ARGVS
    )

# Fill up source branch by current branch name via system git command
currentBranchName = subprocess.check_output(
    'git rev-parse --abbrev-ref HEAD'.split(' ')
).strip('\n')
MR_SETTINGS['source_branch'] = currentBranchName

# Create params list for the MR which will be pasted at the END of URL
getParams = '&'.join([
    'merge_request%%5B%s%%5D=%s' % (k, v) for k, v in MR_SETTINGS.items()
])

# The final url
url = MR_URL_BASE + getParams

# Launch a browser for given url with command line in ubuntu
print 'gnome-open "%s"' % url
Below explain how it works part by part.

How it works

If you studied carefully, gitlab accept a hand made URL for creating Merge request.
We can prefill whatever information in that MR if we can craft a specific URL.
Below is how to craft the first part of the URL, where variables are the namespace and repository name.

# Where is your project: NAMESPACE/REPO_NAME
MR_URL_ARGVS = {
    'NAMESPACE': 'mondwan',
    'REPO_NAME': 'scripts_for_creating_gitlab_mr',
}

# The base url
MR_URL_BASE = \
    'https://gitlab.com/{NAMESPACE}/{REPO_NAME}/merge_requests/new?'.format(
        **MR_URL_ARGVS
    )
The next question is how can I fill text into a field like title, contents, or source branch. Get Params is the answer.
For example, if you append string merge_request%5Btitle%5D=New%20MR at the end of the URL, title of that page will be New MR.
Below shows how to create a MR where title is New MR, assigned to an user with id 1158561, and set master to be the target branch

# What will be the arguments for the MR URL
MR_SETTINGS = {
    # 'source_branch': 'feature_branch_1',
    'target_branch': 'master',
    # 'force_remove_source_branch': 'true',
    'title': 'New%20MR',
    # User ID in the gitlab
    'assignee_id': '1158561',
}



# Create params list for the MR which will be pasted at the END of URL
getParams = '&'.join([
    'merge_request%%5B%s%%5D=%s' % (k, v) for k, v in MR_SETTINGS.items()
])
You may wonder how can I know what should be the key in order to fill up a field. The answer is looking them up via your browser’s console. For example, I would like to look up the key of source branch. I will see something like that in the console after watching the corresponding DOM element from the HTML.
As you can see in the diagram, we can locate merge_request[source_branch] in the HTML. That’s the key (source_branch) we need.
For me, it will be convenient if my script is able to fetch the name of current branch and put that in to the source branch field.

# Fill up source branch by current branch name via system git command
currentBranchName = subprocess.check_output(
    'git rev-parse --abbrev-ref HEAD'.split(' ')
).strip('\n')
MR_SETTINGS['source_branch'] = currentBranchName
Finally, I would like to launch a browser through command line by using gnome-open

 # The final url
url = MR_URL_BASE + getParams

# Launch a browser for given url with command line in ubuntu
print 'gnome-open "%s"' % url
Then, I can copy and paste that URL into the command line. A browser, for me it is Firefox, will be jumped out eventually in Ubuntu.

The repository for this script

Alternative

For advance developers, you may try to automate the entire process by using official APIs. For python developers, you can try to code them up with this cli library.
Although I have not tried to code this alternative, I guess this is much more time consuming than my approach, in term of time spent on development, listed above. One thing, however, I can sure is that this alternative is much more efficient than my approach.

Change logs

20181125: Add alternative section, refine some of the wordings
​