Thursday, October 27, 2016

Nodejs module.exports and singleton


Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.

Module Caching Caveats

Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from node_modules folders), it is not a guarantee that require('foo') will always return the exact same object, if it would resolve to different files.

Additionally, on case-insensitive file systems or operating systems, different resolved filenames can point to the same file, but the cache will still treat them as different modules and will reload the file multiple times. For example, require('./foo') and require('./FOO') return two different objects, irrespective of whether or not ./foo and ./FOO are the same file.

Most Node developers have figured out that if two files in your project require the same module, like this:
var shared = require('shared');

var shared = require('shared');
... Then they will get back the same object, because Node caches requests for the same module.
But you might not realize (I sure didn't!) that if your project is based on npm modules that both require the "shared" module as a dependency, like this:
var shared = require('shared'); 

var shared = require('shared');
... And you install their dependencies with npm, there will be two copies of "shared/index.js" hanging about:
The cache mechanism of "require" does not consider these to be the same file. In my tests, the two modules get different objects back from require('shared').

 Here's a simple example, taken from my upload fs module, of an npm module that does this the right way:
// Export a convenience function that creates an instance
module.exports = function() {
  return new uploadfs();

// The actual constructor function, which is also a closure 
// holding all the private state information

function uploadfs() {
  // Reference to "this" that won't get clobbered by some other "this"
  var self = this;
  // Private state variables
  var tempPath;
  var backend;
  var imageSizes;
  var orientOriginals = true;

  // Public method: initialize the object
  self.init = function(options, callback) { ... }

  // Private functions can exist in the closure too; they can see the state but
  // outsiders can't touch them

  function private() { ... }

These problems might not just be obvious in daily jobs, but when it comes to event emitters this becomes a critical problem, you might be receiving events one place and not other. Probably now you know why.

Android Recyclerview vs ListView with Viewholder

With the advent of Android Lollipop, the RecyclerView made its way officially. The RecyclerView is much more powerful, flexible and a major enhancement over ListView. I will try to give you a detailed insight into it.

1) ViewHolder Pattern

In a ListView, it was recommended to use the ViewHolder pattern but it was never a compulsion. In case of RecyclerView, this is mandatory using the RecyclerView.ViewHolder class. This is one of the major differences between the ListView and the RecyclerView.
It makes things a bit more complex in RecyclerView but a lot of problems that we faced in the ListView are solved efficiently.

2) LayoutManager

This is another massive enhancement brought to the RecyclerView. In a ListView, the only type of view available is the vertical ListView. There is no official way to even implement a horizontal ListView.
Now using a RecyclerView, we can have a
i) LinearLayoutManager - which supports both vertical and horizontal lists,
ii) StaggeredLayoutManager - which supports Pinterest like staggered lists,
iii) GridLayoutManager - which supports displaying grids as seen in Gallery apps.
And the best thing is that we can do all these dynamically as we want.

3) Item Animator

ListViews are lacking in support of good animations, but the RecyclerView brings a whole new dimension to it. Using the RecyclerView.ItemAnimator class, animating the views becomes so much easy and intuitive.

4) Item Decoration

In case of ListViews, dynamically decorating items like adding borders or dividers was never easy. But in case of RecyclerView, the RecyclerView.ItemDecorator class gives huge control to the developers but makes things a bit more time consuming and complex.

5) OnItemTouchListener

Intercepting item clicks on a ListView was simple, thanks to its AdapterView.OnItemClickListener interface. But the RecyclerView gives much more power and control to its developers by the RecyclerView.OnItemTouchListener but it complicates things a bit for the developer.
In simple words, the RecyclerView is much more customizable than the ListView and gives a lot of control and power to its developers.

Build the Android Source for helios x20

  Image result for helio x20


Please refer to AOSP website and follow all the instruction mentioned there. Read and prepare carefully through the link, .

Pay attention to the following key points:

GUN/Linux distribution selecting: We strongly recommend you install Ubuntu 14.04 (Trusty) to  build the environment;
Java Development Kit (JDK): OpenJDK 7 for Android 6.0 (Marshmallow) on Ubuntu;
Device binaries: MediaTek X20 SLA source part including the device binaries;

Establishing a Build Environment

Refer to AOSP website ( ) and follow the below key points:

The Android build is routinely tested in house on recent versions of Ubuntu LTS (14.04)
Installing the JDK 7

$ sudo apt-get update
$ sudo apt-get install openjdk-7-jdk

Installing required packages

$ sudo apt-get install git-core gnupg flex bison gperf build-essential \
  zip curl zlib1g-dev gcc-multilib g++-multilib libc6-dev-i386 \
  lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z-dev ccache \
  libgl1-mesa-dev libxml2-utils xsltproc unzip

Using a separate output directory

$ export OUT_DIR_COMMON_BASE=<path-to-your-out-directory>

Downloading the Source

Refer to AOSP website ( ) and follow the below key points:

Installing Repo

$ mkdir ~/bin
$ PATH=~/bin:$PATH
$ curl  > ~/bin/repo
$ chmod a+x ~/bin/repo

Downloading the AOSP

$ mkdir ~/develop/x20
$ cd ~/develop/x20
$ repo init -u  -b android-6.0.0_r1
$ epo sync –j8

Downloading Linux Kernel

$ cd ~/develop
$ git clone

Downloading MediaTek SLA

$ cd ~/develop
$ curl

 Merge the Source

$ cd ~/develop
$ mv linux ~/develop/x20/kernel-3.18
$ tar vxfz sla.tar.gz
$ cp –rf sla/* ~/develop/x20/

Build the Android Source

Refer to AOSP website ( ) and follow the below key points:

Clean up

$ make clobber

Set up environment

$ source build/

Choose a target

$ lunch full_amt6796_64_open-eng

Build the code

Build everything with make. GNU make can handle parallel tasks with a -jN argument, and it's common to use a number of tasks N that's between 1 and 2 times the number of hardware threads on the computer being used for the build. For example, on a dual-E5520 machine (2 CPUs, 4 cores per CPU, 2 threads per core), the fastest builds are made with commands between make -j16 and make -j32.

$ make -j8

or make one by one manually

$ make pl -j8
$ make lk -j8
$ make kernel -j8
$ make bootimage -j8
$ make systemimage -j8

Note that, the Android OS for x20 96Boards is open source, but excluding HAL part, and the preloader part.

So, there is no need to execute "$ make pl -j8".

Images in the out directory


Follow up with next blog to know how to install android on the board

Install Android on Halios x20

Image result for android install

If you build your own image or get some special image from official website, you need follow the bellowing instruction to download the image onto the X20 96Boards.

Linux User

Prepare tools: xflash & fastboot

xflash is dedicated Flash Tool developed by MediaTek, you can download the Linux version for Ubuntu 14.04 via

$ cd
$ curl -c 
$ tar vxfz xflash.tar.gz
$ cd xflash
$ cp xflash ~/bin/
$ chmod 755 ~/bin/xflash
$ cp /usr/lib/
$ chmod 644 /usr/lib/

fastboot, to flash the board using one of the system images, confirm that you have the fastboot tool in the platform-tools/ directory of the Android SDK. Be sure that you have the latest version of the Android SDK Platform-tools from the SDK Manager.
After you confirm that you have the fastboot tool, add the tool to your PATH environment variable so the tool can be found when you flash the board.

Also, you can install fastboot tool from Ubuntu yum repository:

$ sudo apt-get install android-tools-fastboot

Download the image

Copy the image files to your linux home directory, enter into the image files directory then execute the following commands:

$ xflash enter-fastboot MT6797_Android_scatter.txt

Make sure that you have set the board into USB Device Mode, connect the board to your Linux PC via Micro USB cable.

Now, power on the board, the xflash tool will continue to download and write the board.

If everything is OK, please go ahead to execute the rest part of commands:

$ fastboot devices
$ fastboot flash gpt PGPT
$ fastboot flash preloader preloader_amt6797_64_open.bin
$ fastboot flash recovery recovery.img
$ fastboot flash scp1 tinysys-scp.bin
$ fastboot flash scp2 tinysys-scp.bin
$ fastboot flash lk lk.bin
$ fastboot flash lk2 lk.bin
$ fastboot flash boot boot.img
$ fastboot flash logo logo.bin
$ fastboot flash tee1 trustzone.bin
$ fastboot flash tee2 trustzone.bin
$ fastboot flash system system.img
$ fastboot flash cache cache.img
$ fastboot flash userdata userdata.img
$ fastboot reboot

If everything goes success, the board will reboot and be patient to wait for about 5 minutes for the Android initial boot up.

If you have any questions when you download your own build image, please feel free to discuss in comments. If you are compiling the android images, click here for more info.

For Windows User

Prepare tools: xflash & fastboot

xflash is dedicated Flash Tool developed by MediaTek, you can get it from the sla.tar.gz, it was stored in the sub directory: .\vendor\mediatek\proprietary\system\core\xflash\bin\win

Just copy the following files to your local tool directory and add the tool directory to your PATH environment variable.


For more details, please refer to the thread: and follow step 8~12 of "For Windows User" section.

fastboot,  to flash the board using one of the system images. You can just use the fastboot tool which has been prepared by above section. If you like, you can replace it by yourself. e.g.: follow step 1~16 of "For Windows User" section described in

Download the image

Copy the image files to your local image directory, downloand the batch file ( ), and extract into the image files directory.

Open command prompt on your computer (“Start -> run -> cmd”). On the cmd window type "cd" to change into the image directory, then execute the batch file: xflash_x20.bat

Sometimes, you need to modify the xflash_20.bat file to fit your requirements and target image files. e.g.: ignore partition table image (PGPT).

Wednesday, October 26, 2016

Hands on Helio x20 dev board

Mobile is driving Innovation

Smartphones have become an integral part of our lives, whether it is connecting with family and friends, enjoying music, taking pictures, shooting video, or exploring the wealth of information available on the internet. This has led to a thirst for ever-longer battery power and an efficient, smooth user experience. 

Consumers desire power and efficiency

A desire for faster data plans, increasingly complex apps, and larger screens capable of supporting higher resolutions requires more efficient chips for smartphones. Yet the advance in battery technology for mobile devices simply isn't keeping pace.

Designing a mobile device is no longer just about perfecting its computing power, design, and user interface; it's about doing all these things while driving far less power consumption and greater efficiency.

I'am sure Mediatek take the pride ins announcing the solution

MediaTek helio X20 / X25 - the world’s first mobile processor with Tri-Cluster CPU architecture and ten processing cores (Deca-core). Delivering extreme computing performance with unmatched power efficiency, the new MediaTek helio X20 / X25 processor is set to revolutionize the smartphone industry and address the growing global demand for flagship mobile devices.

MediaTek helio X20 / X25 provides three processor clusters, each designed to more efficiently handle different types of workloads. Much like adding gears to vehicles, dividing the cores into three clusters provides a more efficient allocation of tasks for optimum performance and extended battery life.

It can delegate simple tasks to one cluster of cores, while directing more-complex (and more-power-hungry) tasks to the other clusters. If the smartphone is doing only simple tasks - such as sending text messages or running the calculator - on one cluster, the other clusters can power down, and therefore drive smoother performance and extended battery life.

Performance is  the Key features 

MediaTek helio X20 / X25 delivers state-of-the-art camera, display, gaming, and audio features for today’s most demanding apps.

The MediaTek helio X20 / X25 introduces dual main cameras and features a built-in 3D depth engine as well as multi-scale de-noise engines, for faster response time between shots and unprecedented detail, color, and sharpness, even under extreme conditions.

Display is refreshed at an accelerated 120 frames per second for crisp and responsive scrolling of web content and maps, and uncompromised motion viewing supporting mobile games with high-resolution graphics.

A sensor hub on the embedded ARM Cortex-M4 processor operates on an isolated, low-power domain to support diverse always-on applications, such as MP3 playback and voice activation.

The MediaTek helio series is MediaTek’s flagship mobile processor family, targeting the high-end market segment. The MediaTek helio X Series comprises two product lines: MediaTek helio X10 and MediaTek helio X20 / X25. Launched in March 2015, MediaTek helio X10 is an octa-core solution using a dual-cluster and offers uncompromised multimedia performance. Released recently, MediaTek helio X20 /25 is our state-of-the art mobile computing solution with 10 processing cores organized in a Tri-Cluster. Although MediaTek helio X20 / X25 are closely related and belong to a single product line, the X25 benefits from even more extreme performance thanks to further-enhanced CPU & GPU frequencies. For the most advanced multimedia innovations and highest-end features, choose MediaTek helio X Series.

Build the Android Source

Here is short version of what you will find when you download the Android source. I will leave out some minor directories and dig deeper into a couple of the important ones. Basically what you will get (based on the current Marshmallow release), in alphabetical order:


The C-runtime for Android. Note that Android is not using glibc like most Linux distributions. Instead the c-library is called bionic and is based mostly on BSD-derived sources. In this folder you will find the source for the c-library, math and other core runtime libraries.


Boot and startup related code. Some of it is legacy, the fastboot protocol info could be interesting since it is implemented by boot loaders in a number of devices such as the Nexus ones.


The build system implementation including all the core make file templates. An important file here is the script that will help you a lot when working with the platform source. Running this script in a shell will enable commands to setup environment variables, build specific modules and grep in source code files.


To ensure devices maintain a high level of quality and offer a consistent user experience, each device must pass tests in the compatibility test suite (CTS). The CTS verifies devices meet a quality standard that ensures apps run reliably and users have a good experience. The test suite to ensure that a build complies with the Android specification.


The source code for the implementation of the Dalvik Virtual Machine. The Android runtime (ART) is the heart of Android. It's a fast, ahead-of-time compiled runtime with modern garbage collection designed to scale. Android applications are compiled to Dalvik bytecode and run with ART. This section includes detailed information such as the Dalvik Executable format specification, and design information on the runtime itself.


Projects related to development such as the source code for the sdk and ndk tools. Normally not a folder you touch when working with the platform for a target.


Product specific code for different devices. This is the place to find hardware modules for the different Nexus devices, build configurations and more.


Contains source code for all external open source projects such as SQLite, Freetype and webkit.


This folder is essential to Android since it contains the sources for the framework. Here you will find the implementation of key services such as the System Server with the Package- and Activity managers. A lot of the mapping between the java application APIs and the native libraries is also done here.


Hardware related source code such as the Android hardware abstraction layer specification and implementation. This folder also contains the reference radio interface layer (to communicate with the modem side) implementation.


Apache Harmony.


Helper functions for use with JNI.


not part of the default source download but you can get access to this code either by downloading it manually or by adding the repository to the repo tool. Contains the sources for the Android version of the Linux kernel.


the build output will be placed here after you run make. The folder structure is out/target/product/. In the default build for the emulator the output will be placed in out/target/product/generic. This is where you will find the images used by the emulator to start (or to be downloaded and flashed to a device if you are building for a hardware target).


contains the source code for the default applications such as contacts, calendar, browser.


contains files that are distributed in binary form for convenience. Examples include the cross compilations toolchains for different development machines.
System - source code files for the core Android system. That is the minimal Linux system that is started before the Dalvik VM and any java based services are enabled. This includes the source code for the init process and the default init.rc script that provide the dynamic configuration of the platform


Various IDE tools.

Beyond the above you also have the hidden .repo directory that contains the source for the repo utility. It also holds the manifest specifying what git repositories you want to track for this Android source project. If you have your own additions you could automatically track them by adding a local manifest here.

For modifications of the platform framework there are some instructions available in the device/sample folder of the source code tree. That will show you how to add APIs to Android without having to modify the core framework.