Superman

Superman is dumb. 

For someone with godlike power, he sure is not that bright. He could have eliminated his arch enemies easily without harming him from far. He could have ruled the earth as a benevolent dictator. Instead, he is permanently handicapped by his unrealistic moral constraints, failing to take action, letting the bad guys grow stronger. I was never a fan of his. 

That was what I used to think. 

But as I get older and older, I am starting to realize his true power and strength. His true power is his sense of justice and his strength, his self-control. 

Can you imagine a Being, as powerful as him, and who could get away with anything if he wishes – preserving the justice risking his life? I can’t.

That is his real superpower.

Angular JWT authentication (#7 of 100 projects)

This project took me really long to finish. I spent so much time trying to write a comprehensive blog post on explaining the project. But I realized my goal is to create 100 projects in using Angular framework, not to produce 100 how-to tutorials on Angular.

So this post is rather an update on what I’ve done than a guide post.

In this project, I’ve created a website with a dashboard which is password protected. JWT authentication is implemented using a backend created in Django and hosted in my c9.io instance.

In this project, I’ve created the following:

  • A password protected dashboard component
  • An authentication service to post request to backend API
  • A login component
  • An http interceptor to include JWT token in the http request

Source code: https://github.com/zkkmin/angular-jwt-login

Live demo site at https://friendly-saha-a8644a.netlify.com

username: iunicorn
password: sunandstar

Angular concentration game #6

concentration

This project has taken more then what I’ve intended. In this project, I am creating a memory game called concentration. There are several versions of concentration game. But I’ve implemented the simplest one.

The Game

  • There 2 pairs of cards with number 1 to 8.
  • The cards are laid face down.
  • Each turn, the player click a pair of cards to flip.
  • If the pair matches, the player score points.
  • If the pair is not matched, the pair of cards turns back to face down.

It is a pretty simple project. But it had taken me more time than I should have because I have overcomplicated the overall game design.

Following are the steps I’ve taken to develop the game.

Design game engine

  • Card object
    • cardNumber
      • A string value which will be used to compare between two cards for similarity
    • image
      • A URL to image resource of the card
    • isFaceup
      • To keep track of the current state of the card
    • done
      • To keep track of whether the card is already matched
  • Deck object
    • cards
      • An array of card objects
    • shuffle( )
      • Shuffle cards
    • flipDown()
      • To put all the cards in the deck face down
  • Game object
    • score
      • current score of the player
    • move
      • total number of moves made by player
    • match
      • total number of matched pairs
    • deck
      • a deck to play
    • deal( )
      • call shuffle of the deck
    • checkScore( )
      • compare two cards which are facing up for similarity

Provide game functions in service

Create a service called game. Inside the game.service.ts file define two functions as follow:

  • createDeck(count: number)
    • Create and return a deck of card with the provided number of cards
  • getGame(deck: Deck)
    • Create and return a game object using the provided deck

Components

  • CardComponent
    • Uses card object as the data model
    • Implements flipping on click event
  • GameBoardComponent
    • Uses a list of CardComponents to create the game board to play

Design game board page

  • Create simple and ugly page to stop myself from wasting too much time fiddling with CSS and colors

Lesson learned: Keep it simple and stupid.

Live project link: https://keen-allen-a7c7db.netlify.com/

Github: https://github.com/zkkmin/concentration

 

Angular dharma page #5

DharmaPage

This is the number 5 of my 100 angular projects. This project is based on the previous one Angular dhamma player #4.

This project has two components; the main page and audio track player page. On the home page, four images of famous Burmese Monks are shown in card style. When the user clicked on a card, they are brought to a player with the dhamma talks of the selected monk.

Basically, I am trying to learn how to use the Angular router for navigation between different components in a single page application.

Everything went well, except for one thing. I have been spending way too much time messing around with CSS and colors instead of focusing on functionality.

So, from now on I will spend less time on design aspect and more on functional aspects for future projects.

Live project link: https://inspiring-benz-2fb43a.netlify.com

Github: https://github.com/zkkmin/dharma-page

 

Angular random quote #3

This is the third project of my ongoing challenge, 100 angular projects.

In this project, I created a web page which fetches a random quote from an API endpoint and displays it on the page.

Screen Shot Muse

I have learned a few new concepts while creating this simple web application, such as

  • using services to separate fetching data from components
  • using observable and Angular HttpClient for fetching data asynchronously and providing a way for the data to be consumed from a component
  • calling child component’s function from parent component using @ViewChild

Service, Observable and HttpClient for asynchronous API call


import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class QuoteService {
private quoteUrl = "https://talaikis.com/api/quotes/random/";
getQuote(): Observable <{}> {
return this.http.get(this.quoteUrl)
};
constructor(
private http: HttpClient
) { }
}

Using service to get a random quote from a component


import { Component, OnInit } from '@angular/core';
import { QuoteService } from '../quote.service';
@Component({
selector: 'app-random-quote',
templateUrl: './random-quote.component.html',
styleUrls: ['./random-quote.component.css']
})
export class RandomQuoteComponent implements OnInit {
constructor(private quoteService: QuoteService) { }
getQuote(): void {
this.quoteService.getQuote()
.subscribe(quote => {
this.quote = '"' + quote['quote'] + '"';
this.author = '~' + quote['author']
});
}
quote: string;
author: string;
ngOnInit() {
this.getQuote();
}
}

Calling child component’s function from the parent component


import { Component, ViewChild } from '@angular/core';
import { RandomQuoteComponent } from './random-quote/random-quote.component'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild(RandomQuoteComponent)
private randomQuoteComponent: RandomQuoteComponent;
title = 'Muse';
onClickMe() {
this.randomQuoteComponent.getQuote();
}
}

Live address: http://5b3705ca02ed8359970e2262.silly-perlman-68e0f4.netlify.com/

Git: https://github.com/zkkmin/muse

 

Hello angular with style #2

Screen Shot 2018-06-28 at 4.19.43 PM

This is the second post from the series of 100 angular projects I am doing. You can check out the first post here.

Based on the previous hello world project, I decided to have a little fun by adding CSS framework Bulma which is the new cool kid on the block. Watch out Bootstrap!

First I added the Bulma in the project using npm install:

npm install --save bulma

Second I imported the Bulma in src\styles.css:

 @import "~bulma/css/bulma.css"

Now Bulma styles are available globally. Afterward, I created two components for header and footer.

ng generate component components/header
ng g component components/footer  ## g is shorthand for generate

This will create header and footer components in src/app/components folder.

Edit the header.component.html, footer.component.html, and app.component.html for the Bulma hero layout look.

Let’s create a header with only a brand logo.


<nav class="navbar">
<div class="navbar-brand">
<a class="navbar-item">
<img src="https://bulma.io/images/bulma-logo.png">
</a>
</div>
</nav>

And create a footer with license information.

Finally, add those components into the main app.component.html.


<!–The content below is only a placeholder and can be replaced.–>
<section class="hero is-info is-fullheight is-bold ">
<div class="hero-head">
<app-header></app-header>
</div>
<div class="hero-body">
<div class="container has-text-centered">
<h1 class="title">
{{ title }}!
</h1>
<img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
<h2 class="subtitle">
This is my very second Angular project.
</h2>
</div>
</div>
<div class="hero-foot">
<app-footer></app-footer>
</div>
</section>

That’s it. We are done.

This time, I used Netlify for deployment. It is very easy and it works.

Live address: https://eloquent-dijkstra-37b634.netlify.com/

Git: https://github.com/zkkmin/hello/tree/hello-bulma

 

Database connection leak while using threads in Django

Oftentimes we need to call a third party API in our web application. The recommended way would be using a task runner and task queue like Celery and RabbitMQ.

But sometimes, in a small project it is overkill to use Celery. Especially for a small traffic web site. On the other hand, I don’t want to call external API directly because it will block the request and user may have to wait, and that is never a good thing, small traffic or not.

So I decided to use different thread to call API. And it worked for my purpose.


from threading import Thread
class APIThread(Thread)
def __init__(self, data):
self.data = data
Thread.__init__(self)
def run(self)
# call external api
# process return value
# create new thread to call api
def make_thread(data)
APIThread(data).start()

Everything was fine until I write the unit tests. When I run the tests, an error was thrown at at the end, saying the test database cannot be dropped because there was another user using it.

Usually Django will automatically close the database connections when they exceeds maximum age defined or are not usable any longer.

There was a database access using Django model object in the new thread. After a quick search on google, I found out that the database connection were not closed even after the threads execution finished. The connections need to be manually closed.


from threading import Thread
from django.db import connections
class APIThread(Thread)
def __init__(self, data):
self.data = data
Thread.__init__(self)
def run(self)
# call external api
# process return value
# Django model database access
# close all connections in the thread
for conn in connections:
conn.close()
# create new thread to call api
def make_thread(data)
APIThread(data).start()

By placing the above code at the end of the thread function body solved the problem.

On a separate note, if you are using uWSGI in deployment, you need to add

--enable-threads

argument to enable multi threading.

 

 

 

Exploring OneMap REST API in Swift Playgrounds

I had posted how to add OneMap into your iOS application in previous post. In this tutorial we will try one of the OneMap REST APIs in Swift Playgrounds and see the return results. Xcode Playgrounds is perfect for experimenting with new APIs interactively. We are going to use Address Search API from OneMap.

This allows searching of address data for a given search value.  This also allows support of commands such as AND, OR, including word (+), excluding word (-), and exact phrase search using quotation marks. It will return search results with X,Y coordinates of the searched location.  http://www.onemap.sg/api/help/

First create a new Playgrounds file in xcode. Then import XCPlayground module. After that call XCPSetExecutionShouldContinueIndefinitely and set it true so that execution will continue and we can see the return result from asynchronous REST API calls.


import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

view raw

gistfile1.swift

hosted with ❤ by GitHub

Next, we are going to use NSURLSession to make the REST API call to OneMap service. I use the example URL available in their api help page.

After that we pass the url string to dataTaskWithURL function of the session object and implement a completion handler function to tackle the return result from async call.


session.dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {
(taskData, taskResponse, taskError) -> Void in
var jsonReadError: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(taskData, options: NSJSONReadingOptions.MutableContainers, error: &jsonReadError) as NSDictionary
for (key, value) in jsonResult{
println("\(key) : \(value)")
}
let arr = jsonResult["SearchResults"] as NSArray
println("\(arr[0])")
println("\(arr[1])")
println("\(arr[2])")
println("\(arr[3])")
println("\(arr[4])")
let categ = arr[1]["CATEGORY"]
let searchval = arr[1]["SEARCHVAL"]
let xval = arr[1]["X"]
let yval = arr[1]["Y"]
println("\(jsonReadError)")
println("\(taskData)")
println("\(taskResponse)")
}).resume()

view raw

gistfile1.swift

hosted with ❤ by GitHub

We can convert the result JSON data using NSJSONSerialization.JSONObjectWithData method and cast it as NSDationary. And then we can write println statement on the elements of  NSDationary result. The values of the result will be shown interactively at the right column of Playground. We can change the parameter values in the url string and see the result changes interactively.

onemapplaygroundWe will use this API call in the next post, adding OneMap Search Function in iOS App.