Friday, October 13, 2017

STDIN, STDOUT, and STDERR

Have started scripting again, and have forgotten all about stdin, stdout, and stderr - and the various syntaxes. Time for a refresher.

Ok, so if I was to do an ELI5:
Every process is initialized with three open file-descriptors: stdin (standard input), stdout (standard output), and stderr (standard error).

  • stdin (file handle 0) is where the process gets input from you (usually from the keyboard or from pipes)
  • stdout (file handle 1) is where process output is displayed (usually sent to the console or a file or a pipe)
  • stderr (file handle 2) is basically stdout for errors (usually to stdout unless redirected elsewhere)

Let's take this for example:
myscript <infile 2>errfile

  • A process is created for myscript.
  • infile is opened as standard input for myscript (file handle 0)
  • errfile is opened as standard error (file handle 2)
  • myscript output is sent to /dev/tty by default (file handle 1)

Separating stderr from stdout is a great idea when you know command execution will result in errors, and you don't want them cluttering up valid entries in your stdout. Great example is when you're grepping for something. Most of the time, you get one or two hits, yet stdout is filled with "Permission denied" entries for protected directories. What to do?

grep needle /home/haystack/* > results.txt
Valid results redirected to results.txt; bad results displayed on the console.

grep needle /home/haystack/* 2> errors.log
This time, stderr (2) is redirected to errors.log, while valid results are displayed on the console.

grep needle /home/haystack/* &> output.txt
With this, everything (stdout and stderr) is redirected to output.txt, with nothing sent to tty.

If you want all results displayed on screen and saved on file, pipe them to tee:
grep needle /home/haystack/* |& tee output.txt

If your version of bash is giving you a syntax error, try this less elegant version:
grep needle /home/haystack/* 2>&1 | tee output.txt
This basically redirects stderr (2) to stdout (1).
1>&2 redirects stdout (1) to stderr (2).

What if you simply do:
grep needle /home/haystack/*  | tee results.txt
You get stdout on the screen and in the file, but the console will also display stderr.

Note that the above examples will overwrite if the file exists. Use >> and tee -a to append.

Wednesday, October 4, 2017

Xiaomi Xiaofang 1080P Wireless IP Camera Review

Found some time to finally sit down and write a review of the Xiaomi Xiaofang WiFi IP camera. The camera itself is a glossy white 50mm plastic cube - lens assembly in front, speaker, status LED and USB ports (full-size and micro-USB) at the back, and microSD slot, air vent and reset button at the bottom. The articulated arm and swivel base adds another 6mm to the height. Weight is 100g.

For the price, I'm very impressed with what it supposedly can do.

  • 1080P (1920x1080) full HD resolution video feed via the f2.0 aperture 110-degree lens. If you position two Xiaofangs together, the app supposedly creates a 220-degree panorama.
  • The lens assembly also has an IR-cut double filter with 2 infrared LEDs, which provides night vision up to 9 meters. (You can hear a click when the filter cuts in.)
  • The Mi Home app for the Xiaofang has a Speak button, which enables the intercom functionality.
  • The camera also come with smoke and CO alarm monitor function. Basically, it uses sound recognition to detect that the smoke or CO alarm has triggered, and then sends you a notification.
  • The camera can be configured to record video constantly onto the microSD card (64GB max) or only when motion is detected. Taking of timelapse photos also supported. The videos are also synced to Xiaomi's cloud storage (free!), so you can access/view them remotely.
  • While watching the realtime video feed, you can take stills or record video.
  • Network connection is via WiFi (2.4GHz 802.11 b/g/n). Remote access via WiFi or cellular network.
  • The camera requires 5VDC 1A and is powered via the microSD port. Given that USB ports are almost everywhere (heck, you can even use powerbanks), that opens up options where the Xiaofang can be installed. Add that magnetic base into the mix, the options are limitless!

Initial setup is a bit tricky though, if you don't understand Chinese/Mandarin.
  1. First off, download the Mi Home app from the Google Playstore. The retail box comes with a QR code, which should give you the link, or just do a search from within the Playstore.
  2. Set your location/locale to Mainland China, or the camera will not work. Apparently, it's not supposed to be used outside of China.
  3. Log in to your Xiaomi account, or create one if you don't have one yet.
  4. Click on the "+" icon to Add Device. Select the Xiaomi Xiaofang from the list. Note that you might see two entries. Choose the one with the shorter title, as the other one is for WiFi Direct mode.
  5. Apply power to the camera.
  6. Long press the setup button at the bottom, until you hear a voice prompt, which says/means "Waiting for connection".
  7. At this point, enter the credentials for the WiFi network that the camera is supposed to connect to using the Mi Home app.
  8. Point the camera to the Mi Home, which should now be showing a QR code. Another voice prompt will indicate successful connection.

Note that the camera's default setting is to auto-record. Might want to turn that off.

Been playing with the camera for a couple of days now, and so far so good. Most of the features work as advertised - speak, audio, full screen, look back, timelapse, night vision, and dormancy. There are a few times when I cannot connect to the device, but it's easily fixed with a power reset. Not so convenient when you're in a remote location.

Motion detection is a bit sensitive. The clouds would pass by, changing the sunlight patterns on the blinds, and that's enough to trigger motion detection. Downloading videos also take a while, probably because they're coming from some server in China. Motion-detect videos seems to be limited to 16 seconds.

The camera comes with firmware version 3.0.3.56. The app has been nagging me to upgrade to 3.2.0.30, which I'm holding off, as there are reports that after upgrade:

  • IR LEDs do not turn off even during daytime
  • Camera not working when used outside China (geoblocked?)
  • microSD card not detected

There is an option to lock down access the camera with a PIN password or fingerprint, but not sure how secure that really is. *cough* backdoor *cough*

For those who don't want the video feeds going to China, there is an option to apply some hacks via the microSD card to disable cloud service and stream via RTPS. That said, some of the functionalities become broken. Installation instructions here.

All in all, a neat little WiFi security camera.

Saturday, September 30, 2017

LineageOS 14.1 on the Galaxy S4 Mini

Ever since the wife started using the LG G Pro 2 (D838), the Samsung Galaxy S4 Mini (GT-I9195T) has been gathering dust on a shelf. Decided to put a custom ROM on it, and was pleasantly surprised that it's already running CM13.1 (Android 6.0.1). Can't remember when I did that. And given that it already has a TWRP custom recovery on it, flashing LOS14.1 on it is a cinch.

Download latest firmware here:
https://download.lineageos.org/serranoltexx

Get Google Apps here:
http://opengapps.org/
Choose either the pico, nano, or micro variant of the Android 7.1 gapps (ARM platform).

If you want to get root, download the addonsu package from https://download.lineageos.org/extras

Copy all three files to a microSD card, and let's start.

  1. Boot into recovery (Vol Up & Home & Power).
  2. Wipe the Cache, System, and Data partitions.
  3. Flash the LOS firmware, gapps, and the addonsu zips.
  4. Reboot system.

First boot takes a very long time, so don't be tempted to restart the phone. Just let it finish its work. Once booted, Go to Settings, About Phone. Tap the build number seven times to enable Developer Options. Change root access to your desired method.

Sunday, September 17, 2017

Xiaomi Mijia Infrared Motion Sensor Dimmable LED Night Light Review

For this post, I'm reviewing the Xiaomi Mijia night light. Well, the title pretty much mentions all the features of this item.
  • The light has 120-degree sensing angle and sensing distance up to 5 to 7 meters. Using advanced photosensitive sensor and human infrared sensor technology with anti-infrared interference function, the light can turn on automatically in the dark and light up for 15 seconds.
  • The light is powered by 3 AA batteries (not included). In standby mode, ultra-low power consumption of only 0.25mW. Toggle switch chooses between two luminance levels - 0.7Lm and 3.8Lm, with battery life of 12 months and 6 months, respectively.
  • Applied Fresnel ultra-thin lens to enhance the sensor performance. Fish scale total reflection structure reflect the light to the diffuse reflector and the light spreads evenly in the lampshade to bring a better visual experience.
Okay, first impression. The night light is much smaller than what I expected, having only seen it from the online product listings. The build and finish is excellent though - clean and minimalist. The top and side surfaces of the night light is very smooth, with some grooves at the bottom to provide some grip. Still took me a while to open up the night light to install the three AA batteries.

It works as advertised. Doesn't activate or turn on during daytime. In the dark, it senses movement almost instantaneously, even from afar, and lights up. Even at 3.8Lm, the 2700K warm white light is not too glaring, yet bright enough to light up its immedate surroundings. Light comes out from a circular strip around the top surface. Output is quite uniform and even.

In terms of installation, it can be attached to flat surfaces via double-sided tape. A plastic film with a hole can be stuck to the night light, which can them be suspended/mounted on a hook or nail. In my case, it's just positioned on the floor facing the hallway entrance. Turns on every time someone passes by.

Tuesday, September 12, 2017

Book 2017.09.12 - The Boy Kings: A Journey into the Heart of Social Network

As employee number 51, Katherine Losse writes about her stint at Facebook. From her start as a lowly $20/hour customer support to internationalization product manager to Mark Zuckerberg's ghost writer.

It was an interesting read on how Facebook developed into the all-encompassing behemoth it is now - Mark's obsession on being "technical" and making everything "transparent". Lots of anecdotes about the boy kings and personalities who make up Facebook and philosophical musings about real life, friendships, connections, and technology.

The tl;dr version - Facebook may be good for your "social" life, but not your social life.

After five long years with Facebook, Kate had enough of the cult, and sold off her Facebook shares (pre-IPO), and moved to Marfa, Texas to write this book.

The parting paragraph: "I think that this may be the truth of these technologies that we carry around: We film and post and read social media constantly in order to capture something, some exciting moment or feeling or experience that we are afraid to miss, but the things about life that we most want to capture may not be, in the end, capturable. And, perhaps, planning and efficiency themselves, the things that technologies like Facebook want to make easy and constant, are not as easily grasped as we think. Because, in all of our newfound efficiencies, what have we lost? What, like the moment at the Ice Plant when the glass shattered, is too unplanned and ephemeral to predict and capture with our technologies? Should we keep trying, or should we take a breath, and let some things go unshared and unrecorded, realizing that this ineffability may be the essence of life itself?"

Sunday, September 10, 2017

張惠妹 - 快樂眼淚

張惠妹 - 快樂眼淚

作詞:林夕
作曲:楊陽
編曲:吳慶隆



看著你久違卻 熟悉的臉龐
kan zhuo ni jiu wei que shu xi de lian pang
那些煙遠往事 畫上了圓滿
na xie yan yuan wang shi hua shang liao yuan man
因為你快變成 別人的新郎
yin wei ni kuai bian cheng bie ren de xin lang

你終身的對象 一定很理想
ni zhong shen de dui xiang yi ding hen li xiang
否則你又何必 終止糾纏
fou ze ni you he bi zhong zhi jiu chan
只好微笑祝福 你們的浪漫
zhi hao wei xiao zhu fu ni men de lang man

Chorus:
我終於變得不多愁善感
wo shi zhong bian de bu duo chou shan gan
回憶還像心跳那麼難忘
hui yi huan xiang xin tiao na me nan wang
擁抱的熱 還留在我們的身上
yong bao de re huan liu zai wo men de shen shang
緣分卻不能反抗
yuan fen que bu neng fan kang
愛人不變朋友實在太難
ai ren bu bian peng you shi zai tai nan
希望離別 能讓以後
xi wang li bie neng rang yi hou
更快樂 更幸福 更美滿
geng kuai le geng xing fu geng mei man

漫長路上你幫我背的行囊
man chang lu shang ni bang wo bei de xing nang
因為有你的汗 變成珍藏
yin wei you ni de han bian cheng zhen cang
我給你的補償 是為你打扮
wo gei ni de bu chang shi wei ni da ban

Repeat Chorus

那次大雨中下班
na ci da yu zhong xia ban
你拿一把雨傘 來接我
ni na yi ba yu san lai jie wo
想起來 難免傷感
xiang qi lai nan mian shang gan

感謝你愛我一場
gan xie ni ai wo yi chang
難得敘舊笑談
nan de xu jiu xiao tan
依然溫暖
yi ran wen nuan
有浪漫 沒緣分
you lang man mei yuan fen
總不算遺憾
zong bu suan yi han

我終於變得不多愁善感
wo zhong yu bian de bu duo chou shan gan
回憶還像心跳那麼難忘
hui yi huan xin tiao na me nan wang
擁抱的熱 還留在我們的身上
yong bao de re huan liu zai wo men de shen shang
緣分卻不能反抗
yuan fen que bu neng fan kang
愛人不變朋友實在太難
ai ren bu bian peng you shi zai tai nan
希望離別 能讓以後
xi wang li bie neng rang yi hou
更快樂 更幸福 更美滿
geng kuai le geng xing fu geng mei man
我快樂 的眼淚 在流轉
wo kuai le de yan lei zai liu zhuan

Sunday, September 3, 2017

Downloading Segmented Vimeo Videos

Have blogged about this before. Downloading Vimeo videos used to be a matter of clicking the download button that appears below the video player. Download disabled? No problem. Just plug in the Vimeo video URL to the many online video downloaders that supposedly can do the job. youtube-dl might even do the job.

Lately, I've noticed that a lot of the premium Vimeo videos are chopped up and sent to the client browser as m4s segments. I've written a blog post before re: downloading Brightcove videos, but this one is totally different. As far as I can tell, there is no main mp4 link that can be obtained. You'll have to save all these m4s segments and somehow piece them all together to get the complete video.

Did a bit of research, and looks like someone already wrote a python script that should be able to do this. Installation is pretty simple:

  1. Install additional requirements using pip install.
  2. Install ffmpeg.
  3. Extract the master URL (http://...master.json?base64_init=1) and plug into the vimeo-download command.

vimeo-download.py script should probably work fine with a Windows python and ffmpeg installation, but I decided to go with Linux. See my blog post about Linux VM. As mentioned, python comes pre-installed in Linux Mint, but not pip.

sudo apt-get update && sudo apt-get -y upgrade
sudo apt-get install python-pip

Once pip in installed, it's time to install the additional required packages:

pip install -r requirements.txt

Got an error message saying: ImportError: No module named setuptools

sudo pip install -U setuptools

Next error message is about OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/asn1crypto'

sudo pip install -r requirements.txt

Which now works fine until we get to:

build/temp.linux-x86_64-2.7/_openssl.c:12:24: fatal error: pyconfig.h: No such file or directory compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

This requires additional packages to be installed.

sudo apt-get install python-dev

Then we get: build/temp.linux-x86_64-2.7/_openssl.c:434:30: fatal error: openssl/opensslv.h: No such file or directory

sudo apt-get install build-essential libssl-dev libffi-dev

All the packages from requirements.txt were installed after these additional commands.

Next up is the ffmpeg installation. As instructed in the installation notes, tried to set mc3man/trusty-media as a PPA repository. Got the below error message, which indicates xenial (Linux Mint 18) is too new and not supported by the PPA.

This PPA does not support xenial

Why not just get ffmpeg from the official repositories? Which is what I did.

sudo apt-get install ffmpeg

Next question: How do we extract the master URL of a segmented vimeo video?

  1. Enable Developer Tools (Ctrl + Shift + I)
  2. Go to the Network tab.
  3. Play the Vimeo video.
  4. Look for the entry which says master.json?base64_init=1
  5. Right-click and Copy link address

Usage syntax is:
python vimeo-download.py --url "http://...master.json?base64_init=1" --output <optional_name>

From that master.json URL, we get the base video and audio URLs, and all the segments are retrieved. The v.mp4 video file and the a.mp3 audio file are muxed using ffmpeg to come up with the final vimeo video in the output directory.

Linux Virtual Machine

Sometimes, it's easier to get something done in Linux, compared to Windows. Yet, it might be a one-time job that doesn't warrant a special partition on the hard disk, or even a live CD-ROM or USB stick. For those time, you just want to run Linux on a virtual machine. You can delete the VM once you're done, or just keep VM file the run it again the next time you need it.

For desktop virtualization, it's a tossup between VMWare and Oracle's VirtualBox. Decided to go with the latter, since it's open-source and I feel easier to install and configure. Lots of pre-built images to choose from, but I decided to build the VM from scratch. It's just a matter of creating the VM and specifying the memory and hard disk space. On first boot, specify which Linux ISO to boot from and do a clean install.

Started off with Ubuntu Server, since I have no need for a GUI. For some reason, I was not able to install the VirtualBox guest additions. Tried:

sudo mkdir --p /media/cdrom
sudo mount -t auto /dev/cdrom /media/cdrom/
cd /media/cdrom/
sudo sh VBoxLinuxAdditions.run

and:

sudo apt-get install virtualbox-guest-utils

Seemed to do something, yet not able to get full-screen window and cut-and-paste between host and guest, so I guess it didn't work.

Moved on to Lubuntu. Window resolution was so low that the installation screens are cropped out. Managed to get the OS installation going. Again, had a hard time getting the guest additions working, even though I got the Guest Additions CD image mounted.

Lastly, I tried Linux Mint 18. With this, everything just worked. No cropped installation screens. Full-screen window *before* I installed guest additions. And now I can open multiple terminals, do cut-and-paste between host and guest, and shared folders. Bonus points - python comes pre-installed (but not pip).

Tuesday, August 29, 2017

張惠妹 - 如果你也聽說

張惠妹 - 如果你也聽說

作詞:李焯雄
作曲:周杰倫
編曲:吳慶隆

伴奏版



突然發現站了好久 不知道要往哪走
tu ran fa xian zhan le hao jiu bu zhi dao yao wang na zou
還不想回家的我 再多人陪只會更寂寞
hai bu xiang hui jia de wo zai duo ren pei zhi hui geng ji mo
許多話題關於我 就連我也有聽過
xu duo hua ti guan yu wo jiu lian wo ye you ting guo
我的快樂要被認可 委屈卻沒有人訴說
wo de kuai le yao bei ren ke wei qu que mei you ren su shuo

夜把心洋蔥般剝落 拿掉防衛剩下什麼
ye ba xin yang cong ban bo luo na diao fang wei sheng shen me
為什麼脆弱時候想你更多
wei shen me cui ruo shi hou xiang ni geng duo

Chrous:
如果你也聽說 有沒有想過我
ru guo ni ye ting shuo you mei you xiang guo wo
像普通 舊朋友 還是你 依然會心疼我
xiang pu tong jiu peng you hai shi ni yi ran hui xin teng wo
好多好多的話想對你說 懸著一顆心沒著落
hao duo hao duo de hua xiang dui ni shuo xuan zhe yi ke xin mei zhao luo
要怎麼負荷 捨不得又無可奈何
yao zen me fu he she bu de you wu ke nai he

如果你也聽說 會不會相信我
ru guo ni ye ting shuo hui bu hui xiang xin wo
對流言 會附和 還是你 知道我還是我
dui liu yan fu he hai shi ni zhi dao wo hai shi wo
跌跌撞撞才明白了許多 懂我的人就你一個
die die zhuang zhuang le cai ming bai le xiu duo dong wo de ren jiu ni yi ge
想到你想起我 胸口依然溫熱
xiang dao ni xiang qi wo xiong kou yi ran wen re

許多話題關於我 就連我也有聽過
xu duo hua ti guan yu wo jiu lian wo ye you ting guo
我想我寧可都沉默 解釋反而顯得做作
wo xiang wo ning ke du chen mo jie shi fan er xian de zuo zuo

夜把心 洋蔥般剝落 拿掉防衛剩下什麼
ye ba xin yang cong ban bo luo na diao fang wei sheng xia shen me
為什麼脆弱時候想你更多
wei shen me cui ruo shi hou xiang ni geng duo

Repeat Chorus

如果你也聽說 有沒有想過我
ru guo ni ye ting shuo you mei you xiang guo wo
像普通 舊朋友 還是你 依然會心疼我
xiang pu tong peng you hai shi ni yi ran hui xin teng wo
跌跌撞撞才明白了許多 懂我的人就你一個
die die zhuang zhuang cai ming bai le xiu duo dong wo de ren jiu ni yi ge
想到你想起我 胸口依然溫熱
xiang dao ni xiang qi wo xiong kou yi ran wen re
如果你想起我 你會想到什麼
ru guo ni xiang qi wo ni hui xiang dao shen me