How to create 2d fixed-size array in Swift

Recently I am doing some code tests and found that fixed-size array creation is not as simple in Swift compare to other languages, i.e.

// In C++

int array1[64];    // 1-dimension array size 64
int array2[64][64] // 2-dimension array size 64x64

After a bit digging, the way to do it in swift:

// in Swift:

var array1 = [Int?](repeating: nil, count: 64) // 1 dimension array

var array2 = [[Int?]](
 repeating: [Int?](repeating: nil, count: 64)
 count: 64
) // 2-dimension array size 64x64

// Access it just like normal

array2[4][2] = 42
print(array2[4][2]) // output: 42

So a 3d array would be:

// in C++

int array3[3][3][3];

// in Swift !!!!!!

var array3 = 
  repeating: [[Int?]](
    repeating: [Int?](
      repeating: nil,
      count: 3),
  count: 3),
count: 3)

Now you know how, you can try 7-dimension, happy coding 🍳

Flutter showDialog()

Want to present some information, an alert, some detail, a warrant, an offer? showDialog is your friend, description:

showDialog(BuildContext context, ((BuildContext) → Widget) builder);

it takes two arguments:

  • context: the context to show the dialog.
  • builder: the method to build the content, taking a BuildContext as input and a Widgetas return value.

Actual example:

// Upon a user action, calls
void userDidSomething(){
   showDialog(context: context, builder: box);

// A Button, tap and dismiss action
Widget box(BuildContext context) {
    return RaisedButton(
          child: Text("Alert - Tap to dismiss"),
          color: Colors.yellow
          onPressed: () {

What’s next?

  • Try AlertDialog for proper dialog box
  • Try nesting the RaisedButton in some other layout elements

Happy Coding 🙂

Mindflow: Flutter deal with Future! in 6 Steps

With a Swift background, Flutter+Dart require a different thought-process. Future<T> is associated with async calls and it could be hard to re-route your brain in a one go. In this article I am sharing my experience on how the mindflow when dealing with Future<T> using SharePreferences as an example, from start to a 1-liner in 6 steps.

1. Direct mindflow:

This is how a method looks like with the consideration of existing of Future<T>, it doesn’t work since SharedPreferences.getInstance() returns Future<SharedPreferences> instead of SharedPreferences.

static int getCount(){

// This will return Future<SharedPreferences>, unwarp is needed.
final preferences = SharedPreferences.getInstance();

// Future<SharedPreferences> causes error
// because SharedPreferences has .getInt()
// but Future<SharedPreferences> does not have .getInt()
final value = preferences.getInt("attributeName");

return value;

2. Fix the Future!

To handle Future<SharedPreferences>, add async and await. But the value can be null!

// async is needed to use the keyword await
// async also require Future<int> instead of int
static Future<int> getCount() async {

// Keyword await "unwarp" Future<SharedPreferences> to SharedPreferences
final preferences = await SharedPreferences.getInstance();

// .getInt() works normally now,
// but null can be return if "attributeName" does not have a value
final value = preferences.getInt("attributeName");

return value;

3. Fix the null value!

Change the final to var for value to be validated:

// async is needed to use the keyword await
static Future<int> getCount() async {

// Good now
final preferences = await SharedPreferences.getInstance();

// Change final to var so value can be validated
var value = preferences.getInt("attributeName");

// Validating value
if (value == null){
value = 0;

return value;

4. Shorthand for if …

if … could be a bit blocky, we could replace it with (condition) ? (true) : (false):

static Future<int> getCount() async {

// Shortent this too
final pref = await SharedPreferences.getInstance();

// Replace if with (condition) ? (true) : (false)
var value = pref.getInt("attributeName") == null ? 0 : pref.getInt("attributeName");

return value;

5. Remove more

Future<T> can be stacked with (await Future<T>) to get T within the async method.

static Future<int> getCount() async {

// Remove this line too

// Replace it with (await Future<SharedPreferences>) to get SharedPreferences
var value = (await SharedPreferences.getInstance()).getInt("attributeName") == null ? 0 : (await SharedPreferences.getInstance()).getInt("attributeName");

return value;

6. One-liner!

1-liner, just return the value :

static Future<int> getCount() async {
return (await SharedPreferences.getInstance()).getInt("attributeName") == null ? 0 : (await SharedPreferences.getInstance()).getInt("attributeName");

Github Page Notes + 404 Fix

There is always way too many options to host a website, free or paid. Among the free options there are often catches for the “free” hosting, usually involve injection of ads in the site, resulting in rather unprofessional look. I found that Github Site seems to have the right balance with the only catch being the fixed domain name being, which is done by many other “free” hosting anyway.

There’s the notes on the steps I think would be handy each time you have to create a new GitHub Site:

  1. Decide what the username suitable, give the fact that will be the address of the site.
  2. (Optional) create alias with your email services provider. Instead of a new mailbox, mails sending to all alias will end up in your main mailbox to saving time and cost to manage. Alternatively, if you don’t have a domain name, open a mailbox with Gmail, Hotmail, etc and setup forwarding would work nearly the same way.
  3. Create a public repository name All CLI, Github Desktop or Bitbucket would works, the website will be public anyway, don’t waste the private repo quota.
  4. Add the website file, commits the adding and push the changes to the remote repo.
  5. Wait a few minutes.
  6. Verify the site by visiting
  7. Profit!

In case that website is showing where “404 There isn’t a GitHub Pages site here.” show up and being consistence every after a few minutes of waiting, as asked on Stack Overflow. Like this:

Screen Shot 2019-01-29 at 16.30.51.png
  • Try updating (or creating) a
  • commit
  • push

Hope this note help me and help you in the future 🙂

Better world engineering (2) – Intro – The Minecraft Philosophy

Human-being are commonly known to shift their eating habits to more agricultural based according to the history. From those ages when hunting and gathering were necessary to keep your love ones fed and alive, the lifestyle of be able to feed many more without risking a life going into the jungle. Human had been trying to make the life easier for themselves and the people around them. The discovery and evolvement of the starch-rich potato farming technique is also commonly recognised to have direct impact on the the boost in human populations. If life is a game, farming is the ultimate cheat-code.

The rise of the game Minecraft has been phenomenal. Originate from the idea of mining minerals in an procedurally generate world, to a children’s game with vibrant  colours, and finally arrived at a point to support 3D world creations in a creative ways. People had spend countless hours building worlds, some of them depicted franchise we love, cities in the lord of rings, the game of thrones and Star war, all of them have a blocky-version represented in Minecraft. Often, multiple people spend a ridiculous numbers of hours to create a Dead Star, not because they are paid nor asking people anything in return. They do it because they love it and they understand these hours they are going to spend are only once and for all. Meaning once the project is completed, it will literally be a result that is long lasting, nearly forever for the people who love their works to enjoy. The concept of permanent creation already sounds awfully familiar to the original intention of agricultural development in the human history.

For those aren’t familiar in Minecraft as a game, there is a system in Minecraft called redstone mechanics. The best way to describe it is that redstone me is a Minecraft block representation of logic-gates in electronic in real life. Electronic logic-gates is what make computer electronic possible in the first place. Enthusiasts have succeed in the redstone mechanics to create calculator, clocks, and even a 16-bit computer!

Now for those who aren’t caught up with multiplayer settings of Minecraft, there are communities which dedicate to creative builds and doing it in survival mode instead of creative mode. Meaning that building resources are limited, so as food items and any consumables. This is how the specialist of “food-farm”, later on item farm, emerged. These people make use of redstone mechanics and to create systems that “farm” and collect renewable items. The question is a simple but a milestone in human history: How to build a system to infinitely create a particular resource, building it once, to supply the need of everyone on the same server, and so no one would ever have to do it in the future?

Technological advancements we have today is already capable of “farming” of many resources with full automations, so as the automation of the resource chain all the way to raw materials that consumed in the farming process, and also the automation of recycling the waste and byproducts. Most of the goods we see today can mostly be produced fully automated, but this is not the case in actual production because two things gets in the way: the need of profit and the unwilling to do it once and for all. All because the wrong question was asked: how to build a system to create a predefined quantity of product, with lowest periodic input, and to maximise the profit.

Our motivations inspire our questions, the questions drive our discoveries, our discoveries enable us to build systems and foundations that shapes our lives. What lifestyles are we building when we change our question to: 

What do I need to maximise my profit?

from the original: 

What do I need to invent once and for all to supply enough food and the tailored transportation system so that no one will ever be hungry again?

In my line of work, as a software architect, I witnessed the many crossroads of creating a better inventions that benefits the user against a version for better profit / doing it passively by engaging the user for longer time. The food industry is one of the most infamous to make people eat things that do not benefit them the most, so as the many other industries. We constantly joke around to say, no one is willing to invent near-unlimited power that doesn’t breakdown because the inventor will be assassinated immediately by big corporations who prey on the power bills. In a world driven by profit, our world, it might not be too far from truth.

What do we need to do it once and for all to supply enough resources for our love ones, which should be defined as everyone, so work will forever be an optional task, and people just need to do what they like to do and only?

Right questions, right answers, one solution at a time, one article at a time – collectively.


The content will be updated and modified continuously. Feedbacks are welcome for any improvement and addressing any inaccuracy.

Copyright © Marco S.I. Leong, 2018


Better world engineering (1) – Into – Let’s build the wall again

A question is the best way to start off our journey – Does the world today make sense to you? The common responses can be describing how bad it is or how good it is. Advancements, technology, happiness index, lifespan on one side, or another extreme, diseases, disasters, corruption, pollution, stress, war, etc. Some would response to the questions by describing how the history is contributing to the world we see today. Some would start of with defining “good” and arrive at the concept that there are different standard from person to person. Let me ask the question again: Does the world make sense to you? Yes or No.

If the answer is Yes. You are already living in a perfect world and wish you all the best staying in the cocoon. Ignorance does not imply innocence. In fact, some of you who said Yes might just be indifference to those would outside of your circle of care. You are not the target audience of the Better world engineering series. Let’s not waste your time of doing more read.

For those who said No, have you ever wonder why is it so? The social construct we are witness is working but there is something not quite right. Assume that the human society is group of gears – interconnecting with each other – the system we see today isn’t exactly smooth. People would say that the advancement to create a better world has not been invented yet. I argue, there are only two main reasons:

  1. Regardless of whoever is leading the development of the society. They are attempting to add new gears into the system while the system is running at 10,000 rpm – and people just wonder why there are so many social conflicts, unemployment, dissatisfaction and unfulfillment in life.
  2. The force to drive the development of the society has changed. The original idea should be to make live better for yourself and your neighbour. Now it turns into work for a job that you don’t like -> to increase the purchasing power -> to buy something that you are told you want.

These two concepts are correlated. The force to make living better has driven human race from hunting-and-gathering to invest their effort in agricultural advancement in order to feed more people. Later down the history, to build up the wall to shield oneself and people they care from the unknown at night. Bigger walls to protect their villages, better roads connecting city for safer trades. Better medicine to cure people we care. And more cities when we are overpopulated – when we see that quality of life drops. We have forgotten how to build new cities.

To be accurate, we are not allow to build a new city because we have insufficient funds in our bank account. In fact, we are not allow to build anything because of different laws, because the government suddenly owns all the lands some point in the history and we somehow need approval from them before we can even start exploring the option to build ourselves a life.

It is counter intuitive when we are told that moving to the city is the best things we can do – jacking up the pricing of the real estate and asking us to pay more for less – while the only right thing to do is to expand from the existing city. In our society today, we are told to the exact opposite for the benefit of those who came up and enforce the false story.

We used to surround people that we loved most, our circle-of-care, with the best resource and exhausting our ingenuity. The walls (resources) today we see are misplaced and beyond our control.

It is time to build the wall again.

The content will be updated and modified continuously. Feedbacks are welcome for any improvement and addressing any inaccuracy.

Copyright © Marco S.I. Leong,  2018


How much will Pokemon Go cost you?

Screen Shot 2016-07-06 at 15.36.48.png



Creative Commons License

Pokemon(TM) is owned by Nintendo.

Some people really need a punch in the face by Marco Leong is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

This image is created under fair-use: Copyright Disclaimer Under Section 107 of the Copyright Act 1976, allowance is made for “fair use” for purposes such as criticism, comment, news reporting, teaching, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational or personal use tips the balance in favor of fair use.

So Pixelated!

So Pixelated! (Pokemon Pixelmon Meme)

Pokemon Pixelmon.png


Creative Commons License

Pokemon(TM) is owned by Nintendo.

Some people really need a punch in the face by Marco Leong is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

This image is created under fair-use: Copyright Disclaimer Under Section 107 of the Copyright Act 1976, allowance is made for “fair use” for purposes such as criticism, comment, news reporting, teaching, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational or personal use tips the balance in favor of fair use.

PDF password recovery free

There is always this password, this pdf, being secured by you. In fact too secured that you can never remember the password. Instead of move the PDF to trash there some way to recover the password.

There are a bunch of PDF password recovery/cracking software charging a few to tens of dollars. While in the wonderful work of Unix/Linux you, this kind of tool is free. There is one that I found recently:


To install, on Ubuntu

sudo apt-get install pdfcrack

on OS X, install brew and:

brew install pdfcrack

You will be prompt to enter password to install the tool

To start the recovery, simply:

pdfcrack "/usr/jonsnow/Download/birthcert.pdf"

To save use control-C to exit the tool, the tool will attempt to save.

The recovery process may takes hours to days depends on the security setting of the PDF. You will be prompted with the recovered password in command prompt upon succeed.


Let me know if it saved your day 🙂

* Be sure you have the right to perform recovery, i.e. you own the file but forget the password. Any wrong doing will still be wrong doing, so don’t do it.

* For Windows users, make friend with unix/linux people. They are like dentists, scary but really helpful.

pdfcrack [Official link]