# Learning RxSwift’s Github Sample

## Introduction

The first example RxSwift mock Github sign-up view controller. It checks availability of user name, password. Then simulate a sign-up process.

## Listen User Input

This is easy to do with Rx framework. The rx_text field of UITextField is defined in RxCocoa is just what you want.

It tracks textViewDidChange wrap all changes into Observable, which is an basic event sequence can be Observed by Observer.

And handling tapping on a button is as easy as

## Build Basic Observables

In a common sign-up process, we have to check

1. User name is empty or includes illegal character
2. User name has been signed up
4. Request can be handled correctly or not

We build 4 observables, i.e. event stream to handle them separately.

### 1. Check User Name

This is a flatmap function for Observable. (Definition on flatmap can be found in this post. Functor, Monad, Applicative in Swift

# Update UI With Observer

Sometimes I need to update UI from different Fragments. But it seems that writing update method in each Fragment is absurd if I have a lot of Fragment to handle with.

Here is a better solution by using Observer pattern, IMO.

### Sample

1. Define an EventObject, which is a event(or message) will be passed to Observer.
1. Define an Observable, which will dispatch event or message to Observer.
1. Caller. Use a shared instance of Observable to dispatch event to Observer.
1. Receiver, which implements Observer interface.

# Functor, Monad, Applicative in Swift

Some Implementation in Swift.

### Functor

Let $C$ be a constructor which takes a variable as parameter.

$C$ is a Functor if $C$ has the following ability.

For example, we can write such a function functor or map.

And we can chain functors like this.

We can also do it like Haskell

$C$ is a Monad if $C$ has the following ability. This is also called as flatmap.

### Applicative

$C$ is a Applicative if $C$ has the following ability.

# Remove Border From Android Dialog

In android development, Dialog are DialogFragment are very common UI parts. They come with a default border, with black or white background depending on android system version.

The default border, which is actually a drawable, is defined in android themes file.

panel_background in <item name="windowBackground">@drawable/panel_background</item> is a 9-patch image file.

We can remove the border by defining windowBackground property, in our own custom style file, to replace the default one.

Or, use the following one-line code solution.

Also, there are other dialog styles defined in android themes file.

# Codility Calcium 2015

## Introduction

This is an solution in java of Codility Calcium 2015.

You can find problem definition here. https://codility.com/programmers/challenges/

The key logic is using binary search to limit the answer area.

For each iteration of binary search, detail steps are written in the following code.

## Optimization for 100% solution

This problem is very time strict for java.

For large data set, my old answer which use many Collections always runs for 6+ seconds, but time limit is only 4 seconds.

So I replace almost all of them with array in heavy calculation part, to reduce time consuming of GC.

This results an 3+ seconds for each iteration of binary search.

https://codility.com/cert/view/certXKYPW7-D87MFQHQEGCKWRV9/details

# Longest Increasing Subsequence

## Introduction

In computer science, the longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence’s elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible.

For example, a longest increasing subsequence of 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 is 0, 2, 6, 9, 11, 15.

## An O(N2) Solution

We define a $dp$ table, which $dp[i]$ is the length of a longest subsequence which ends at $inputs[i]$.

For each $inputs[i]$, we search every inputs before it, and choose the longest possible $dp$ value from them, fill it in $dp[i]$.

## An O(N*Log(N)) Solution

We define a $seq$ table, which $seq[i]$ is the ending number of subsequence whose length is $i$.

#### Note that, $seq$ is always in increasing order.

Because if these exist $i < j$ and $seq[i] > seq[j]$, which means a longer subsequence end with a smaller number.

Then we could generate a new subsequence, which length is $i$, by removing $j - i$ numbers from tail of $j$-length subsequence. The ending number of the new subsequence will be smaller than $seq[i]$.

Therefore, we can use binary search in each iteration, to find the largest $seq[k]$ which is smaller than $inputs[i]$. If $k$ can be found ($k > -1$), then we update the number stored in $seq[k]$ with $inputs[i]$ if $inputs[i] < seq[k]$.

This yields an O(N*Log(N)) solution.

# Swift String Operations

String operations of Swift seems to be easy to handle, but we should take care of them in development.

For example, this is a common code snippet which stays on the top spot, by searching ‘swift substring’ from www.google.co.jp.

But, it is not correct. NSString’s implementation is based on UTF-16 and handing index for it is just confusing.

Take a look at the following test.

Because index in NSString format is different from index in String format. The text is counted as length 2 in NSString, but only 1 in String.

So using substring in NSString only get half of it, from its binary expression. Then certainly, it cannot be decoded correctly.

Swift Online Guide has a detail explanation for this problem.

We should use String.Index to handle different byte length of each character, and also decomposed and precomposed characters.

Because String in Swift is implemented as Unicode Scalar, or UTF-32, is always 4-byte long for each character and it default behaviour can handle composed characters.

# Surrogate Support for Swift’s String

String in Swift does not support UTF16 surrogate in default.

A Unicode scalar is any Unicode code point in the range U+0000 to U+D7FF inclusive or U+E000 to U+10FFFF inclusive. Unicode scalars do not include the Unicode surrogate pair code points, which are the code points in the range U+D800 to U+DFFF inclusive.

Therefore, I wrote a support class for it. :)

SwiftSurrogate on Github

Now you can decode Swift String from UTF16 surrogate pair like this.

# Generics Enum in Swift

If we want handle different data type, according to the result of calling some APIs. We may need the code like this.

But the code above cannot be compiled.

### How can we actually do this

We can use Container Class.

But it is awful to write bunch of code for creating container classes, for each type you need.

### Better Solution?

Here is a very useful lib. https://github.com/robrix/Box

It provide a container class called Box

### Finally

We can rewrite above code into this. Much more elegant.

# checkstack.plを遊んでみた

どうやって調べるのを調べたら、Linux OSに付いているcheckstack.plを見つけた。

ソースをgistに上げました。checkstack.pl

ちなみに、154行目のnext if ($size < 100);をコメントアウト済み。 そうすれば、スタックサイズが100以下のメソッドもリストアップしてくれた。 ### テスト用のソース ### 使う macなのでobjdumpではなくgobjdumpを使う。homebrewでインストールすると便利 g++ stack_test.cpp gobjdump -d a.out | checkstack  ### 結果 0x000100000e14 __Z14func_arr_int_2v []: 16 0x000100000e33 __Z14func_arr_int_2v []: 16 0x000100000e44 __Z14func_arr_int_3v []: 32 0x000100000e63 __Z14func_arr_int_3v []: 32 0x000100000e74 __Z14func_arr_int_4v []: 32 0x000100000e93 __Z14func_arr_int_4v []: 32 0x000100000ea4 __Z10func_pointv []: 16 0x000100000ebe __Z10func_pointv []: 16 0x000100000ed4 _main []: 32 0x000100000f09 _main []: 32 0x000100000f14 __ZN5PointC1Eff []: 16 0x000100000f39 __ZN5PointC1Eff []: 16  今のコンパイラって結構やってくれるな。 func1ではレジストで操作したからスタック消費はなし。 func_arr_int_1がスタック消費がないのは驚いた。size = 1のarrayは最適化されてなくなったみたい。 x64マシンなので、メモリー最小単位は16byteになるのか？ func_arr_int_2は16byte。func_arr_int_3は実際24byteだと思うが、スタックサイズは32byteになった。メモリーは２単位取ったね。 ### checkstack.plの原理  elsif ($arch =~ /^x86(_64)?$/ ||$arch =~ /^i[3456]86$/) { #c0105234: 81 ec ac 05 00 00 sub$0x5ac,%esp
# or
#    2f60:    48 81 ec e8 05 00 00       sub    $0x5e8,%rsp$re = qr/^.*[as][du][db]    \$(0x$x{1,8}),\%(e|r)sp$/o;$dre = qr/^.*[as][du][db]    (%.*),\%(e|r)sp\$/o;
}