2017年10月25日 星期三

database 到底要不要對 boolean 值打 index 呢?

真實情況是: it depends


but depends on what?

主要可以根據以下兩個基本的原則來 depends

boolean index 會有效能上幫助的時機:

1. 跟其他欄位一起打 index
2. 某一部分的 records 暫少數的時候,例如 true 的有 9000 筆而 false 只有 100 筆

https://stackoverflow.com/questions/42972726/postgres-sql-create-index-for-boolean-column

https://stackoverflow.com/questions/10524651/is-there-any-performance-gain-in-indexing-a-boolean-field


2017年10月22日 星期日

整理 SASS 的方法

教了很多整理 SASS 的方法,主要是用 mixins

https://www.toptal.com/css/sass-mixins-keep-your-stylesheets-dry

偷懶也可以直接使用 Sass mixin libraries,例如文中提到的 bourbon 和 andy

http://bourbon.io/
http://gillesbertaux.com/andy/

SASS 做 theme 的起手式

不錯的文章

* 最外層的 container 控制 theme 基本元素
* 加上 themable 的 mixin 並設參數讓 theme 更彈性
* 用 each 方法 loop 參數,讓 themable 更彈性,只需要接受 name 和 map 兩個參數
* lighten & darken 方法做到 hover 效果


https://www.toptal.com/sass/theming-scss-tutorial

摘要算法和對稱加密算法

摘要算法不可逆,對稱加密可逆

所謂對稱加密就是用私鑰(也就是密碼)幫訊息加密,所以只要再用私鑰就能解密,例如 AES 算法

而摘要算法呢?就是沒有私鑰的概念,只要是一樣的字串加密出來的內容就會是一樣的,但是摘要算法會確保加密出來的字串無法(應該說:很難)被逆推回原本的值,所以常常用來做 API 訊息的驗證,常見的算法有 MD5 和 SHA 系列


由於以上特性,對稱加密通常用來保護隱私相關的東西,而摘要算法則是確保文檔的正確性,以下舉例說明用法

對稱加密:
最長用來做點對點加密,確保中間人不能得到訊息原文,可以用作在通訊軟體加密

摘要加密:
常用在 API 訊息認證,最常用的作法就是在要傳送的 Params 時多加 API key 到的 Params 裡面, 由於攻擊者不知道公鑰所以即使要竄改 params 內容也沒辦法重新產生正確的加密字串

2017年10月21日 星期六

deploy nodejs to server using capistrano and nvm and pm2

這給了大概流程

http://jameshuynh.com/nextjs/react/capistrano/nvm/pm2/2017/10/07/deploy-nextjs-app-with-capistrano-3-nvm-and-pm2/


Server 安裝 zsh

不能 sutocomplete 太痛苦了

```
apt-get install zsh
curl -L https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | sh
```

然後默認zsh


```
chsh -s /bin/zsh
```


遇到問題:

```
$ chsh -s /bin/zsh
You may not change the shell for 'apps'.
$ which zsh
/usr/bin/zsh
$ chsh -s /usr/bin/zsh
You may not change the shell for 'apps'.
```

切換到 root 後跑

```
$ chsh -s /usr/bin/zsh apps
```

解決

http://blog.poetries.top/2016/06/26/Ubuntu%E4%B8%8B%E5%AE%89%E8%A3%9D-Zsh-%E5%8F%8A-Oh-my-zsh/

Host key verification failed.

問題:

```
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
SHA256:qsKeZfZAS3BCLZw6OT1a6I1U9MzfZpEfCZDmY63+VQ8.
Please contact your system administrator.
Add correct host key in /Users/wayne/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /Users/wayne/.ssh/known_hosts:10
ECDSA host key for xxx.xxx.xxx.xxx has changed and you have requested strict checking.
Host key verification failed.
```


試了:


列出現在的

ssh-add -l


ssh-add ~/.ssh/id_rsa


ssh-copy-id username@remote_host

~/.ssh/authorized_keys

最後:

把 xxx.xxx.xxx.xxx 的 key 從 .ssh/known_hosts 刪掉


http://smelon.blog.51cto.com/877877/245405

2017年10月19日 星期四

read only active record model

```rb
def readonly?
  true
end
```

https://til.hashrocket.com/posts/7cd7e55929-read-only-models


https://stackoverflow.com/questions/5641410/is-there-an-easy-way-to-make-a-rails-activerecord-model-read-only

rails singleton class



```rb
# File activesupport/lib/active_support/core_ext/object/singleton_class.rb, line 3
  def singleton_class
    class << self
      self
    end
  end
```

2017年10月18日 星期三

rails console 的實用技巧



reload!

app
app.get "/movies"


helper
helper.link_to("Movies", app.movies_path)





https://pragmaticstudio.com/blog/2014/3/11/console-shortcuts-tips-tricks




另外還有最屌的,如果有裝 pry 的話,在 home 目錄下的 `.pryrc` 加上

```ruby
def me
  @me ||= User.find_by_email("wayne.5540@gmail.com")
  @me
end
```

就可以一開啟 console 直接打 `me` 找到自己了!

react functional setState

```js
this.setState((prevState, props) => (
  { hello: "world" }
))
```

這是很重要的,不然 setState 有可能會一起執行,變成

Object.assign({}, {hello: "world"}, { hello: "Wayne" })

這樣第一次執行的 setState 就會被蓋掉

https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b

2017年10月17日 星期二

在網站上加上音效

原來是這樣加的XD

```js
            var sound = document.getElementById("msgSound");
            if (sound) {
              sound.play();
            }
```

2017年10月15日 星期日

用 nvm 裝 nodejs


裝 nvm
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.5/install.sh | bash

nvm install v8.7.0

npm install pm2 -g



裝機筆記

## 裝機器

https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-16-04


* Ubuntu 16.04LTS

Local
```
ssh root@HOST
```

Server
```
apt-get update && apt-get upgrade


dpkg-reconfigure tzdata
```

如果 apt-get update 卡住:https://zach-adams.com/2015/01/apt-get-cant-connect-to-security-ubuntu-fix/


## securing-your-server

### 新增 User

Server

```
adduser apps
adduser apps sudo
passwd apps
mkhomedir_helper apps

exit
```

測試登入
Local

```
ssh apps@HOST
```

### 增加 ssh key

Local

```
ssh-copy-id -i ~/.ssh/id_rsa.pub apps@HOST
```
* 如果沒有 ssh key 記得要先 [generate 一組](https://help.github.com/articles/connecting-to-github-with-ssh/)
* 如果沒有 ssh-copy-id 就跑 `brew install ssh-copy-id`


### Disable Password Authentication

Server

```
sudo vim /etc/ssh/sshd_config
```

Set
```
PasswordAuthentication no
```

```
PubkeyAuthentication yes
ChallengeResponseAuthentication no
```


### deploy 前準備

Server
```
sudo apt-get install git
```

Local
```
ssh-add -L
如果沒有就
ssh-add ~/.ssh/id_rsa
```



學習使用 tmux

tmux 搭配 vim 似乎是很好的組合,為了強迫自己使用 vim 並同時保有高效率開發,先來研究一下。

http://www.hamvocke.com/blog/a-quick-and-easy-guide-to-tmux/

更正,先學 vim 比較實際XD

tmux 比較適合長期連 ssh 或是開 rails server 之類

搭配 https://github.com/tmuxinator/tmuxinator 就可以一鍵開啟想要的東西,視窗都切割好

2017年10月14日 星期六

不錯的 project prioritise 公式 - RICE

RICE 是四個詞的縮寫

最後的公式是:( R * I * C ) / E = RICE


Reach
代表可以接觸到的 users 量,可以用季或是月當標準單位

Impact
對公司能造成的影響
3 for “massive impact”, 2 for “high”, 1 for “medium”, 0.5 for “low”, and finally 0.25 for “minimal

Confidence
對上述猜測的信心指數,低於 50% 的話根本就不要算了
100% is “high confidence”, 80% is “medium”, 50% is “low”. Anything below that is “total moonshot”


Effort
可以用:一個人要花一個月內的多少時間才能做完來當作指標,也可以用週或是日,但很難真的估得很仔細,所以假設用週當基準,那麼一週內能做完都算 0.5,一週算 1,超過一週再往上增加

Effort is estimated as a number of “person-months” – the work that one team member can do in a month. There are many unknowns here, so I keep my estimates rough by sticking to whole numbers (or 0.5 for anything well under a month). Unlike the other positive factors, more effort is a bad thing, so it divides the total impact.



https://blog.intercom.com/rice-simple-prioritization-for-product-managers/


2017年10月10日 星期二

onboarding 的模板

在開始前,用戶會問你什麼問題?



在第一次使用產品時,用戶忘記做什麼會讓使用者體驗搞砸
(最常客訴的點)



用戶最常做了什麼「正確的事」達到很好的體驗



用戶最常做了什麼「錯誤的事」結果收到很糟的體驗



東西賣出後你如何檢驗他們「做了正確的事」或「做了錯誤的事」?



他們如何聯絡你修正問題



你怎麼做事後補償的方案?



你希望他們如何事後幫你行銷?


reddit 上的 rails performance 總結

The Complete Guide to Rails Performance 這本書 https://www.railsspeed.com/ 的總結:

  • Measure. If you have a serious project a cost of NewRelic account is negligible but insights it provides are very valuable. Make sure you measure request queue time, when you have large variance in request processing time (some are slow, some are fast) you may want to switch from Nginx to Haproxy as a front-end.
  • Cache output. With large JSON/HTML responses you'll move from 300ms to sub-10ms. Use Russian doll caching
  • Use conditional GET
  • Use proper DB indexes. If they aren't enough, denormalize in RDBMS or use Shopify's identity_cache. There are gems that suggest what indexes you are missing. Remember that indexes are useful when searching using a prefix of indexed columns, so if you have an index on (name, created_at) it will be used when searching or sorting by name. Read "Use the index Luke" it contains pretty much everything you need to know about them.
  • If you are managing a database yourself and it's PostgreSQL, read the configuration chapter in the docs and change the settings accordingly. Defaults aren't optimized for performance.
  • DB optimization is a huge topic. If some query is unusually slow, make sure execution plan is correct. PostgreSQL optimizer sometimes messes up and uses hash join-table scan instead of nested loop. Increase stats granularity or force it to use nested loop. Read http://a.co/2GF5Sg8 if you want to know more.
  • Avoid N+1, make sure to include related records in queries. In rare cases it's better to use N+1 with Russian doll caching but generally avoiding N+1 is better. There are gems to detect N+1.
  • Play with number of processes and threads per process in your app server. Multi-threading helps with I/O bound tasks (querying a slow database, calling remote servers).
  • Enable out-of-bound GC in your app server, so that GC won't happen during requests. It has minimal impact but still.
  • Off-load long-running tasks (e.g. resizing images and calling external services) to background workers. Use Sidekiq, it's amazing.
  • Don't bother with EventMachine, it sucks.
  • Make a choice on what to do with JS files. Either use CDN to serve third-party libraries individually or bundle them in a separate file.
  • Serve static assets from CDN.


https://www.reddit.com/r/rails/comments/5x0wd2/has_anybody_purchased_the_complete_guide_to_rails/

比較 websocket 和其他技術,以及解釋action cable 的好文

大意

http
stateless

- polling
- long polling
- server send event

websocket
stateful

- 2 ways
- simultaneous communication
- hard to load balance

action cable

- 3-second heartbeat on all connections. If a client can’t be contacted, we automatically disconnect, calling the unsubscribe callback on our Channel class.


https://www.speedshop.co/2015/09/30/action-cable.html

2017年10月9日 星期一

管理 dotfile 的方法

https://developer.atlassian.com/blog/2016/02/best-way-to-store-dotfiles-git-bare-repo/

和 dotfile manager

https://github.com/TheLocehiliosan/yadm

2017年10月8日 星期日

[Side project 篇] 在 Shopify 上賣東西


之前聽到 Domon 說了一個「同事的朋友」(好不靠譜XD)用 Shopify 的 dropshiping 功能賣指尖陀螺在三個月賺八萬美金的故事,就在內心萌生也來玩玩看的念頭

昨天實際跑了一下流程,初始費用是:


Shopify29AUD/month
G suite5AUD/month
domain356NTD/yr


還滿便宜的,但還要算入一些編輯網頁和找素材等等的時間成本,弄了一個 https://travelercollection.com/ 來賣之前在網路上看到的刮刮樂地圖


Shopify 做得不錯的點:

1. Email onboarding 很厲害,都是對想開商店的人很有幫助的內容,捨不得取消訂閱,尤其是最後一封「隨時可以延長一週試用」太猛了啊...
2. 很多降低進入門檻的舉動,最厲害的是接 Godaddy API 自動綁域名,另外還有 GA, FB pixel 都整合得不錯,還有自動生成隱私政策等等的小東西


昨天基本上完成以下事項:

  • 買 Shopify Plan 下定決心
  • 整體網頁動向
  • 設定 GA, Facebook Pixel
  • 買 Domain
  • 掛 Domain 到 Shopify
  • 買 G suite
  • 掛 Domain 到 Gmail
  • 測試訂單
  • 發好友測試詢問意見
  • 多找幾個商品備案
  • 開始記流水帳



下一步是要買廣告來開始 Aquire users 近來衝動消費,需要:

  • 熟悉 FB 廣告後台
  • 熟悉 Instagram 廣告設定方式
  • 確定 TA
  • 「參考」其他賣同商品的人的廣告素材
  • 微調網頁介面和商品細節
  • 再來最後就是開始 Run 廣告!

其他還可以 Improve 的部分:


  • 研究美金 base 付款
  • 換個 Logo https://www.shopify.com/blog/17016964-5-easy-to-use-online-logo-makers-to-design-your-brand



實做 graphql api 的各種眉角

這篇文章提到了很多實做 graphql api 的各種眉角,都是很 practical 的,值得參考

https://blog.codeship.com/graphql-and-performance-in-rails/

2017年10月6日 星期五

k8s + docker + google cloud

### Docker

```
docker build -t wayne5540/poloniex-toy .

docker run -p 49160:3000 -d wayne5540/poloniex-toy
```

Go to `http://localhost:49160/`

Tutorails:

* https://nodejs.org/en/docs/guides/nodejs-docker-webapp/
* https://github.com/nodejs/docker-node/blob/master/README.md#how-to-use-this-image
* https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md

Commands:

* list images
  `docker images`
* list running containers
  `docker ps`
* stop container
  `docker stop <CONTAINER_ID>`
* remove container
  `docker rm <CONTAINER_ID>`
* remove imsage
  `docker rmi <IMAGE_ID>`

## Deployment

To google container engine (GKE )Using k8s, on Mac

https://www.sitepoint.com/kubernetes-deploy-node-js-docker-app/

```
brew install kubectl
```

```
docker build -t gcr.io/my-toy-projects/poloniex-toy:v1 .

gcloud docker -- push gcr.io/my-toy-projects/poloniex-toy:v1

kubectl create -f deployment.yml --save-config

kubectl get pods

kubectl expose deployment poloniex-toy-deployment --type="LoadBalancer"

kubectl get services
```

Clean
```
kubectl delete service/hello-world-deployment
kubectl delete deployment/poloniex-toy-deployment
```

docker

* 看 images

docker images

* remove images

docker rmi <IMAGE_ID>


* 建立 image
docker build -t <your username>/node-web-app .

* Run image

$ docker run -p 49160:8080 -d <your username>/node-web-app

In the example above, Docker mapped the 8080 port inside of the container to the port 49160 on your machine.


* node:
https://nodejs.org/en/docs/guides/nodejs-docker-webapp/

modern js cheatsheet

https://github.com/mbeaudru/modern-js-cheatsheet