Golang url 參數編碼與解碼

package main

import (
"fmt"
"net/url"
)

func main() {
urltest := "http://www.baidu.com/s?wd=自由度"
fmt.Println(urltest)
encodeurl:= url.QueryEscape(urltest)
fmt.Println(encodeurl)
decodeurl,err := url.QueryUnescape(encodeurl)
if err != nil {
fmt.Println(err)
}
fmt.Println(decodeurl)
}



輸出結果:
http://www.baidu.com/s?wd=自由度
http%3A%2F%2Fwww.baidu.com%2Fs%3Fwd%3D%E8%87%AA%E7%94%B1%E5%BA%A6
http://www.baidu.com/s?wd=自由度



常在處理網址的人應該會發現某些網址在從瀏覽器複製下來之後,就會變成一些百分比加上十六進位碼的奇怪網址,而貼回去瀏覽器又變正常了,就個就是網址 URL 百分比編碼的問題。

網址 URL 百分比編碼
在 RFC 3986 標準中規範一些 URI 的保留字元(reserved characters),若網址中出現這些保留字元時,就必須把這些保留字元轉為百分比編碼的表示方式,例如:!、#、: 與 & 等。

百分比編碼的規則就是把字元的 ASCII 碼以十六進位表示,前方再加上一個百分比符號,例如井字號 # 的 ASCII 碼是 0x23,所以經過百分比編碼轉換之後,就是 %23。

若是遇到非 ASCII 的字元(例如中文字),則會將資料以 UTF-8 的編碼方式表示成一連串的位元組序列,再將每個位元組以百分比編碼的方式進行編碼。

關於網址的百分比編碼介紹,可以參考維基百科的 Percent-encoding 說明。

平常最常會遇到的網址百分比編碼的地方就是瀏覽器的網址列,當我們在用 Google 搜尋後,若想要把網址複製起來,有時候就會遇到這種編碼問題:


雖然在瀏覽器的網址列中看到的中文字是正常顯示的,但是如果將這串文字複製起來,貼在一般的文字編輯器時,就會出現這樣經過編碼的 URL 網址:

https://www.google.com.tw/search?q=%E4%B8%AD%E6%96%87

原本網址的中文兩個字,在這裡變成了 %E4%B8%AD%E6%96%87,就這是因為瀏覽器在使用者複製網址時,自動把網址經過一道百分比編碼轉換了,事實上這才是標準的網址寫法。

HTML 的 form 表單在用 GET 或 POST 等管道送出資料時(content-type 為 application/x-www-form-urlencoded),其欄位名稱以及資料內容也會經過百分比編碼,不過在編碼規則上有一些小改變(請參考 W3C 網站),最常見的差異就是原本的空白字元會被編碼成 %20,而在這裡就會轉為加號 +。

這個差異在瀏覽器的網址列就可以時常看到,當我們在 Google 搜尋含有空白的關鍵字時,網址會變成這樣:


在 HTTP 的 GET 參數中的空白會被瀏覽器轉換為加號 +,所以 Google 搜尋 ubuntu linux 的網址會變成這樣:

https://www.google.com.tw/search?q=ubuntu+linux
簡單來說,在網址中問號 ? 左邊的空白會轉換成 %20,而右邊的空白則會轉換成 +。

Golang Web 编程的 Get 和 Post 請求發送與解析

通过一个简单的例子介绍Golang的Web编程主要用到的技术。

          文章结构包括:

Client-Get 请求
Client-Post 请求
Server 处理 Get 和 Post 数据
          在数据的封装中,我们部分采用了json,因而本文也涉及到Golang中json的编码和解码。



一、Client-Get

package main

import (
        "fmt"
        "net/url"
        "net/http"
        "io/ioutil"
        "log"
)

func main() {
        u, _ := url.Parse("http://localhost:9001/xiaoyue")
        q := u.Query()
        q.Set("username", "user")
        q.Set("password", "passwd")
        u.RawQuery = q.Encode()
        res, err := http.Get(u.String());
        if err != nil {
              log.Fatal(err) return
        }
        result, err := ioutil.ReadAll(res.Body)
        res.Body.Close()
        if err != nil {
              log.Fatal(err) return
        }
        fmt.Printf("%s", result)
}


二、Client-Post

package main

import (
        "fmt"
        "net/url"
        "net/http"
        "io/ioutil"
        "log"
        "bytes"
        "encoding/json"
)

type Server struct {
        ServerName string
        ServerIP   string
}

type Serverslice struct {
        Servers []Server
        ServersID  string
}


func main() {

        var s Serverslice

        var newServer Server;
        newServer.ServerName = "Guangzhou_VPN";
        newServer.ServerIP = "127.0.0.1"     
        s.Servers = append(s.Servers, newServer)

        s.Servers = append(s.Servers, Server{ServerName: "Shanghai_VPN", ServerIP: "127.0.0.2"})
        s.Servers = append(s.Servers, Server{ServerName: "Beijing_VPN", ServerIP: "127.0.0.3"})
       
        s.ServersID = "team1"

        b, err := json.Marshal(s)
        if err != nil {
                fmt.Println("json err:", err)
        }

        body := bytes.NewBuffer([]byte(b))
        res,err := http.Post("http://localhost:9001/xiaoyue", "application/json;charset=utf-8", body)
        if err != nil {
                log.Fatal(err)
                return
        }
        result, err := ioutil.ReadAll(res.Body)
        res.Body.Close()
        if err != nil {
                log.Fatal(err)
                return
        }
        fmt.Printf("%s", result)
}


三、Server

package main

import (
        "fmt"
        "net/http"
        "strings"
        "html"
        "io/ioutil"
        "encoding/json"
)

type Server struct {
        ServerName string
        ServerIP   string
}

type Serverslice struct {
        Servers []Server
        ServersID  string
}

func main() {
        http.HandleFunc("/", handler)
        http.ListenAndServe(":9001", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
        r.ParseForm() //解析参数,默认是不会解析的
        fmt.Fprintf(w, "Hi, I love you %s", html.EscapeString(r.URL.Path[1:]))
        if r.Method == "GET" {
                fmt.Println("method:", r.Method) //获取请求的方法

                fmt.Println("username", r.Form["username"])
                fmt.Println("password", r.Form["password"])

                for k, v := range r.Form {
                        fmt.Print("key:", k, "; ")
                        fmt.Println("val:", strings.Join(v, ""))
                }
        } else if r.Method == "POST" {
                result, _:= ioutil.ReadAll(r.Body)
                r.Body.Close()
                fmt.Printf("%s\n", result)

                //未知类型的推荐处理方法

                var f interface{}
                json.Unmarshal(result, &f)
                m := f.(map[string]interface{})
                for k, v := range m {
                        switch vv := v.(type) {
                                case string:
                                        fmt.Println(k, "is string", vv)
                                case int:
                                        fmt.Println(k, "is int", vv)
                                case float64:
                                        fmt.Println(k,"is float64",vv)
                                case []interface{}:
                                        fmt.Println(k, "is an array:")
                                        for i, u := range vv {
                                                fmt.Println(i, u)
                                        }
                                default:
                                        fmt.Println(k, "is of a type I don't know how to handle")
                         }
                  }

                 //结构已知,解析到结构体

                 var s Serverslice;
                 json.Unmarshal([]byte(result), &s)

                 fmt.Println(s.ServersID);
 
                 for i:=0; i<len(s.Servers); i++ {
                         fmt.Println(s.Servers[i].ServerName)
                         fmt.Println(s.Servers[i].ServerIP)
                 }
        }
}

電池電量校正

所謂「斷崖式掉電」,另一個說法是「跳電」,
網路上有大量關於手機「斷崖式掉電」的發文,蘋果、小米,各種品牌的都有,
即是手機剩餘電量驟減,如前一秒電量還剩餘50%,後一秒電量就剩下不到20%,又過了幾秒鐘,手機顯示電量不足10%,隨後就自動關機,嘗試開機時顯示低電量無法開機。

那麼,到底是什麼導致了跳電?主要有兩種情況,接觸問題與使用環境溫度過低。

因接觸問題產生跳電,對於拆解過手機或更換過電池的用戶來說,因為這種原因產生的跳電大多伴隨著手機重新啟動。

若是由於使用環境溫度過低導致,當使用環境溫度上升後即可恢復正常使用。

若不是上述兩種情況,則試試看電池電量校正能否修復...


以 iPhone 來說:

1. 想辦法把 iPhone 的電池用盡,用到完全沒電直到 iPhone 自行關機。
2. 等完全沒電之後,接上充電器。
3. 由於之前是用到自行關機,所以電力需要先充到大約2%左右,iPhone 才會顯示畫面,這時候把 iPhone 關機 (長按休眠鍵,一直到出現『滑動來關機』提示出現,然後滑動關機)。
4. 接下來就讓 iPhone 持續充電,充到100% (一般三個多小時可以充飽),充到100%之後,先別拔掉充電線,繼續再多充個一到兩個小時。
5. 接著開機 (還是不要拔掉充電線)。
6. 等iPhone開完機以後,同時按下休眠鍵以及Home鍵,一直按著,直到白底黑蘋果Logo出現為止。
7. OK,電池校正好了。

註:iPhone 處在關機狀態時,一插電就會自動開機,這是一種固定不可改的機制,是用以預防 休眠鍵 故障時,因而導致無法開機的備用手段。

小米做手機、掃地機器人都大賣,攻占不同市場的關鍵是?

「我不需要你用黃金的價格把稻草賣出去,」小米創辦人雷軍說。他在 2010 年創立的這家企業,以「永遠維持 5% 毛利率」「創造高性價比產品」為宗旨,不斷打破各種產業規則,每推出一款商品,就可能造成該商業領域爆炸性的改變,例如當他們所做的行動電源、延長線、小米耳機,都在在改變了該產品領域的定價,以及消費者對於產品質量的要求程度。

從賣手機起家,眾人曾以為「又是一間山寨企業」的小米,在短短 8 年內一路轉型,竄入小家電、生活消費品、電腦與電視產品,在做電腦的同時,也一樣生產掃地機器人、牙刷、延長線。這些分散於不同領域的眾多商品,命運出奇的雷同:在小米生產商品時沒人在意、小米宣告進軍時被眾人訕笑,在小米確定拿下大量市場分額時,又博得眾人的注意和好奇。
小米究竟是怎麼辦到的?雷軍如何能不斷創造大量高性價比的爆品,構成專屬於小米的新商業模式?答案就在 ──「小米生態系」。

「小米生態鏈」是什麼?

時間得回到要 2013 年中,雷軍交辦小米科技聯合創始人暨副總裁劉德,「到市場上去搶一批創業團隊,用小米價值觀孵化一批企業。」

當年選定的第一項產品就是手機周邊商品 ── 行動電源,背後的生產製造公司是「紫米」。再來陸續出現做小米耳機的「萬魔聲學」(1 MORE)、做小米手環等智能可穿戴式裝置的「華米」、做淨水器的「雲米」及平衡車的「納恩博」等等,逐步攻占各個市場領域,形成小米生態圈。

這個生態圈以手機為圓心,向外慢慢發展成三大圈,頭兩層是小米的老本行、雷軍認為還大有可為的手機周邊商品及智慧硬體產品;最外層則是擁有巨大市場的生活耗材類產品。在小米的公開招股書中載明,截至 2018 年 3 月 31 日為止,小米透過投資和管理,建立了由超過 210 家公司組成的生態鏈,其中,有高達 90 多家專注於研發智慧硬體設備與生活消費用品。根據艾瑞諮詢根據 2017 年及 2018 年第一季的統計,行動電源、空氣清淨機與電動滑板車出貨量全球第一的企業,皆隸屬於小米生態鏈。

第一層手機: 智慧型手機
第二層手機周邊: 行動電源(紫米)、耳機(藍米、萬魔聲學)、自拍棒(悅米)
第三層智慧硬體: 空氣清淨機(智米)、智能手環(華米)、電視(峰米)、掃地機器人(石頭科技)、電飯鍋(純米)
第四層生活耗材: 牙刷(貝醫生)、毛巾(最生活)、背包與行李箱(90 分)

對雷軍與小米高層而言,小米生態系的主要定義是「這是一個基於企業生態的智慧硬體設備孵化器」。小米提出三大主張,包括小米只投資、不控股;小米完全輸出產品方法論與價值觀,主導設計、協助研發與尋找供應鏈,並且在自營通路上上架販售;生態鏈企業全數是獨立企業,可獨立研發與銷售自有商品。

也因此,小米與小米生態系旗下眾多企業不是單純的代工關係、也不是單純的投資,更不是母子企業的從屬關係,他們更像是在 IoT 生態下,一群圍繞著「小米精神」、擁有共同思維與企業文化,快速生產、製造與研發各種領域商品的戰略夥伴。

在小米生態系出現之前,這種商業模式前所未見,自然無人可以仿效。雷軍為什麼要這樣做?這對小米的市場地位有什麼樣的幫助?主要來自於他的兩個判斷:

1. 下一個市場在物聯網(IoT)

小米創立時是中國的互聯網元年,當時正巧趕上中國大陸從一般型手機,轉換至智慧型手機的換機潮,也因此才能在 3 年間飛速成長。雷軍認為,物聯網是下一個風口,小米不能錯過。


2. 速度、速度,還是速度

但要趕上這波熱潮,單靠小米之力絕對做不到。雷軍判斷,當年小米有 8000 名員工、其中 2000 名工程師專注於研發手機,卻仍舊趕不上市場速度。單是手機如此,遑論要往外擴展到手機周邊、生活消費硬體設備,人力、專業度、效率與成本,都不能單押在小米一家企業身上。因此,雷軍才有了「去投資一批企業」的想法,意即,

小米要以「投資加孵化」的方式找一堆公司組團打群架,一起布局市場。

雷軍想像,當小米生態鏈有 100 間企業,那就有可能會有 100 個產品進入不同的產業「抱團打拚」,這不只會改善市場,也會改善供應鏈結構,雷軍甚至認為,建構了這個複雜的生態鏈系統,有機會在新零售、AIoT(人工智慧結合物聯網)的環境下,出現一個能超越 BAT(中國三大品牌百度、阿里巴巴、騰訊)三座大山的彎道。

小米 2018 年第 3 季財報,或許證實了雷軍當初的想像。集團季營收將近 508.46 億人民幣,較去年同期增長 49.1%,其中手機商品銷量達 3 億 3300 萬支,約進帳 350 億元人民幣,較去年同期增長 36.1%,但更值得注意的是其 IoT 與生活消費產品營收為 108 億元人民幣,占總營收 21.3%,相較去年成長 89.8%,幅度驚人。

誰才能加入生態鏈,一起打群架?

那誰有資格加入?洪華說,早期小米的投資者都是一群工程師,這群人徹底了解小米的價值觀、對於產品的標準,也對企業極度忠誠,不會因為投資中間所產生的利潤而被誘惑。他們選擇投資標的,只看產品與技術,不看商業計畫與估值,主要原因是「沒必要」,產品太新還沒有市場,而且小米投資的本質是「孵化」,相中有未來發展性的產品更重要。

除了產品之外,他們更在意「被投資人」,雷軍喜歡找熟人,業界說他「衣不如新,人不如故」。智米的蘇峻,是劉德以前在大學教書時的老朋友;小貝醫生的章駿,則是洪華大學時期的學弟。洪華解釋,小米最在意的是被投資者的「價值觀」契合度,包括「不賺快錢」「矢志做最好的產品」「認為互聯網是有未來的」「願意為了改造傳統行業,致力提升效率」等等。

例如純米創辦人楊華,為了做好電子鍋,他們先「蒐集」了全球好用、評價好的產品,全數拿回來研究;再者,他們還到日本向擁有電子鍋多項專利的發明人內藤毅求教;雲米在開發淨水器時,發現市售淨水器都有漏水問題,他們沒打算放過,而是決意升級解決產品的「產業級痛點」,開發商品的過程中產生 400 多項專利、發明專利有 100 個、創新率達 90% 以上,這為淨水器產品立下了相當性的門檻,讓競爭對手難以模仿與超越。

當你加入小米生態鏈之後,小米會提供資源,幫助生態鏈的企業孵化出爆品、成為有能力自主經營的公司。這些資源可分為小米的核心粉絲(人)、小米做爆品的方法和邏輯(貨)、小米的通路和銷售場域(場)三大部分,從新零售的「人、貨、場」三大元素,分析小米商業模式的成功邏輯。


恭喜,貴公司得標了,然後勒?

終於標下大案子!除了慶祝、獎勵員工,還有一件事主管更該做

某公司為了爭取一個大客戶,專門成立了專案組,分工協作,努力半年,經歷各種挫折和辛苦,當然也有各種鼓勵和改進,終於得到了客戶的認可:「恭喜,貴公司得標了。」
這時候公司負責人應該幹什麼?

做兩件事:第一,帶著團隊去狂歡;第二,帶領大家走進會議室,認真地進行一次「復盤」。

哈佛大學的大衛.葛文(David A. Garvin)教授認為:學習型組織的診斷標準之一,就是「不犯曾經犯過的錯誤」。 從即將結束的項目中總結成功經驗,吸取失敗教訓,這就是「復盤」。

聯想公司根據實際經驗,把復盤歸納為 4 個步驟: 回顧目標、評估結果、分析原因和總結規律。

回到最初的案例。按照聯想的復盤流程,可以有如下做法:

一、回顧目標

回顧目標,就是要準確、客觀的回答兩個問題:我們的目標是什麼?我們的里程碑有哪些?

「我們的目標是不顧一切拿下這個項目。」這準確、客觀嗎?這個目標很含糊,什麼叫「不顧一切」?準確、客觀的描述是:「我們要在 10% 毛利率的底線內,拿下這個項目。」

那里程碑呢?「我們的里程碑,是三月底拿下項目,六月份測試上線,九月份收回全款。」

二、評估結果

這一步很關鍵。通過準確、客觀的描述結果,可以找到相對於目標的「好的差異」和「壞的差異」。

比如,結果是:「我們在二月底拿下了項目,但測算的毛利率只有 5%。」因此,好的差異是:我們推動客戶提前做出決定;壞的差異是:毛利率低於預期。

評估結果、描述差異時需要注意,不要忍不住分析原因,甚至提出解決方案,更不要忍不住指責、抱怨和撇清責任。

三、分析原因

評估完結果,就要分析原因:是什麼導致了「好的差異」和「壞的差異」?

大家討論後認為,推動客戶提前做出決定,讓競爭對手措手不及的原因是:

第一次使用了「作戰指揮室」的管理方式,團隊合作的效果和效率都大大提升,使項目方案極具說服力。

銷售嚴格執行「銷售漏斗」流程,發現客戶對上線日期的擔憂,從而說服客戶提前招標。

但是,毛利率為什麼低於預期呢?經過對事不對人的冷靜分析後,大家發現原因是:

項目方案內容變化太快,導致成本估算表更新速度跟不上。

最終一輪談判時,在談判技巧上,表現嚴重不足。

分析原因時要注意:成功主要看「客觀原因」,失敗主要看「主觀原因」。

註:
成功主要看「客觀原因」=>「成功者找方法,失敗者找藉口。」
失敗主要看「主觀原因」=>「做事失敗後,不找客觀原因,找自身原因。」

四、總結規律

公司負責人很高興大家能客觀地面對成敗,獲得的不僅是勝利,更是成長。但是,復盤還沒結束。還有最後一步,也是最重要的一步:總結規律。 這一步,是把「隱性知識顯性化」的關鍵一步。

根據對成敗原因的分析,總結出四條規律:

1. 作戰指揮室,是在重大項目中建立快速反應團隊的好方法。
2. 銷售漏斗培訓,對提高銷售能力值、提高項目成功率很有幫助。
3. 項目方案快速調整時,成本預算表是容易滯後的模塊。
4. 談判能力,在大項目的最後環節,作用明顯。

基於這四點,要開始做什麼、停止做什麼、繼續做什麼呢?

1. 「開始」做兩件事

行政部把一個會議室改成專門的作戰指揮室。

銷售部修改工作手冊,超過三百萬元的項目談判,配備談判專家。

2. 「停止」做一件事

項目內容大量變更時,方案中心不能獨自作戰,要申請財務部專員配合。

3. 「繼續」做一件事

每個新入職的銷售人員,都要參加銷售漏斗培訓。

最後,把復盤總結發給所有人;把總結的規律,寫進工作手冊;把要開始做、停止做的每件事,都啟動單獨的 PDCA 循環。

組織學習大師彼得.聖吉(Peter M. Senge)曾講過:

從本質上看,人類只能通過「試錯法」進行學習。復盤,就是從曾經試過的錯中學習,把經驗和教訓變成組織能力。


2019年1月的全球經濟情勢快照

每當聯準會 (Fed) 主席鮑爾說,他會持續做出過去二年 Fed 所做的事,即緩慢調高聯邦基金利率,並縮減資產負債表,市場投資人便悶悶不樂。

鮑爾的前任 Fed 主席葉倫與伯南克長期維持利率於極低水準,還三度大幅買進債券 (即量化寬鬆),使得股市持續上漲,經濟亦自大衰退中,緩慢復甦,同樣一群投資人却不知心存感激。

現在,他們懇切要求 Fed 別拿走這項利多。

每當鮑爾談話有點鷹派,即他相信經濟仍然強勁,當會繼續升息,股市便告下跌。每當他的措辭有點軟化,股市則又上漲。

目前並沒有證據顯示鮑爾的經濟基本面展望有所改變。他使用與葉倫同樣的措辭 -- 即呼籲緩慢升息,但他的行動較葉倫積極地多。自葉倫於 2015 年 12 月開始升息以來,Fed 已升息九次,却有近半數係發生在鮑爾任內,而到 2 月 5 日,他才上任滿一週年。

當然,對大企業與富人減稅,拉抬了經濟成長。預估 2018 年,美國 GDP 成長將達 3%,創 2015 年以來最高水準。去年就業成長達 260 萬人,高於 2017 年的 220 萬人。

同時,至 6 月,美國經濟復甦將達十年之久,而聯邦基金利率僅 2.25% 至 2.5%。在以往的經濟復甦中,葛林斯班與伯南克僅花了二年半時間,便將利率由 1% 調高到 5.25%。

鮑爾的心態難以捉摸,但他非常了解伯南克調降利率十次,降幅達五個百分點,以對抗金融危機與大衰退。Fed 還注入資產負債表逾 3.5 兆美元資金。除非鮑爾進一步升息,至少達到中性的 3%,否則他將沒有足夠的子彈,對抗下一波經濟衰退。如果不趁著經濟強勁時,縮減資產負債表,可能永遠也無法再做了。

2013 年,鮑爾曾敦促伯南克停止買進債券,展現他的鷹派立場。但現在,他必須保守,避免股市大跌,避免影響經濟。

但如果經濟依舊強勁,市場也穩定,預期他將持續縮減資產負債表,並調高聯邦基金利率,只是速度可能較預期慢一些。

補充:
當下大事件為中美貿易大戰,彭博資訊專欄作者 Fickling 指出,美國川普選擇開打貿易戰的日子選得真是好:中國正以歷史的縱深來打這場貿易戰。
費克林指出,川普在選擇升高貿易戰的時機上的確有一套。他在威脅數周之後,決定在9月18日再對2,000億美元中國產品開徵10%關稅,而「918」正是中國開始抵禦「日寇」侵略的重要日子,各機關、學校都有紀念活動,部分城市還會鳴響空襲警報,中共絕不會讓「918」深埋在歷史教科書中。
美國貿易談判官員一心想要以種種威脅,促使北京當局同意在經濟發展模式上做出重大改變。他們在決策的同時,應考慮到中南海的領導人絕不會僅執著於日常性的經濟鬥爭。
同時間,川普持續施壓要求聯準會主席鮑爾停止升息,並且希望各種手段促貶美元。
同時,川普還為了在墨西哥邊境築牆一事,不惜關閉政府來威脅民主黨就範。
















編程哲學:Python

用过 Python的人,基本上都知道在交互式解释器中输入 import this 就会显示 Tim Peters 的 The Zen of Python。

The Zen of Python, by Tim Peters


Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


Python之禅 by Tim Peters

优美胜于丑陋(Python 以编写优美的代码为目标)

明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)

简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)

复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁)

扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)

间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)

可读性很重要(优美的代码是可读的)

即便假借特例的实用性之名,也不可违背这些规则(这些规则至高无上)

不要包容所有错误,除非你确定需要这样做(精准地捕获异常,不写 except:pass 风格的代码)

当存在多种可能,不要尝试去猜测

而是尽量找一种,最好是唯一一种明显的解决方案(如果不确定,就用穷举法)

虽然这并不容易,因为你不是 Python 之父(这里的 Dutch 是指 Guido )

做也许好过不做,但不假思索就动手还不如不做(动手之前要细思量)

如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然(方案测评标准)

命名空间是一种绝妙的理念,我们应当多加利用(倡导与号召)

編程哲學:Golang

世界是并行的----先不说宇宙,就整个地球来说,世界万物都是并行发生的;天生对并发支持良好的go语言更容易描述并行的世界;

世界是由物质组合构成的---微观世界:由小的粒子组合成大的粒子;宏观世界:由小的物体组合成大的物体;
继承只能描述现实世界的一小部分,使用继承是不全面的;go的设计选择的是组合,这个和现实世界比较吻合的设计,表现力更强;

世界是标准化的---随着生产力的发展,社会分工越来与详细,越来越多行业有了国际标准,任何一个国家的、任何一个公司只要按照这个标准生产器件,就能装配到一台机器上;IBM/PC就是硬件模块化和接口化一个最成功的例证;
软件也可如此,go的接口是duck模型,面向接口编程,而不需要显示的声明,将语言能做的事情交给语言做;

正交性--几何上的正交指的是两个向量垂直关系,一个向量在另一个向量方向的投影是一个点;
现实中的正交是指多个因素,一个发生变化,不会影响其他的因素;在不减少表现力的情况下,正交是保持事物稳定性和简单性的最好设计;
go很好的遵循了这个规律,go的多个特性之间都是正交的:goroutine,接口,组合,类型系统等;
举一个典型的正交设计例子:比如客户嫌雨伞太小,单纯的加长伞杆是不行的,这会增加雨伞的长度;最后计出折叠式的雨伞;这种设计能保证雨伞大小和雨伞长度满足正交关系,当然这会增加雨伞生产的复杂性)

把复杂性留给厂家,把便利性留给客户;对于编程语言:尽量把复杂性留给语言实现者和编译器,把简单性留给语言使用者,这才是一种好的语言;


少即是多---没有万能的语言,换句话说一门语言不可能包含所有的特性;想囊括所有特性的语言一定是非常的复杂(C++);
保持简单性的方法就是:每种特性仅提供一种方法,减少重复、冗余,试想一下,如果汽车有多个刹车板,你会感觉更安全,更便利吗?

只提供一种方法做事情,把事情做到极致,这就是go的原则,解放程序员,不要给他提供很多雷同的功能和语句,这不会使问题简单,只会加重程序员的心智负担



二八定律---在编程语言中描述就:百分之八十的代码仅仅使用到百分之二十的语言特性,增加语言特性,并不能保证开发效率的提升,原因是它会增加复杂性,导致更容易犯错;
有些复杂的编程问题其实可以通过库的形式来辅助支持;大部分


异常与错误---所谓异常就是没有预料到的非期望的事情发生了,所谓错误就是预料到的非期望的事情发生了;go语言把两种情况终于给分清楚了;什么是防御性编程,怎么保持程序的健壮性;

每次调用都检查error确实让代码挺不美观的,个人认为为了健壮性,进行防御性的编程也是可以接收的;通过一定的技巧是可以避免错误代码冗余性;


论述完普世定律后,我来总结一下GO语言的哲学:

1.面向接口编程

2.使用组合的编程

3.正交性:语言设计的正交性,保证语言的稳定性和简单性

4.少即是多:有且仅有一种方法把事情做好做对

5.并发语言层面支持:并发更好利用多核,有更强的表现力来模拟真实世界

6.开放性:开源,语言的实现对程序员不是个黑盒子,任何想了解语言实现的人都可以参与进来


go 没有像JAVA一样,宗教式的完全面向对象设计;完全面向对象设计就是一刀切的宗教式的设计,但其并不能很好的表述这个世界,这就导致其表现力不足,最后通过设计模式和面向切面等设计技巧来弥补语言方面的缺陷;go是面向工程的实用主义者,其糅合了面向对象的设计,函数式设计和过程式设计的优点;原来通过各种设计模式的设计通过函数、接口、组合等简单方式就搞定了;go有更多胶水的东西比如:全局变量、常量,函数,闭包等等,可以轻松的的把模块衔接和驱动起来; JAVA就好比:手里握着是锤子,看什么都是钉子,什么都是类的对象,这个和现实世界不符,类表示单个事物还可以,一旦表示多个事物及其交互,其表现力也就会遇到各种挑战。

      是时候该转变观念了,不要动不动就提面向对象设计,动不动就提设计模式(特指某些招聘伪专家);编程的世界是多样的,编程思想和范式是丰富多彩的,不要再沿着错误的路线继续前进了,拥抱go吧。

美國的公司透過破產等手法來惡意規避養老金支付

https://www.washingtonpost.com/business/economy/as-a-grocery-chain-is-dismantled-investors-recover-their-money-worker-pensions-are-short-millions/2018/12/28/ea22e398-0a0e-11e9-85b6-41c0fe0c5b8f_story.html

As a grocery chain is dismantled, investors recover their money. Worker pensions are short millions.

MUNCIE, Ind. — Once the Marsh Supermarkets chain began to falter a few years ago, its owner, a private-equity firm, began selling off the vast retail empire, piece by piece. The company sold more than 100 convenience stores. It sold the pharmacies. It closed some of the 115 grocery stores, having previously auctioned off their real estate. Then, in May 2017, the company announced the closure of the remaining 44 stores.

Marsh Supermarkets, founded in 1931, had at last filed for bankruptcy.

“It was a long, slow decline,” said Amy Gerken, formerly an assistant office manager at one of the stores. Sun Capital Partners, the private-equity firm that owned Marsh, “didn’t really know how grocery stores work. We’d joke about them being on a yacht without even knowing what a UPC code is. But they didn’t treat employees right, and since the bankruptcy, everyone is out for their blood.”

The anger arises because although the sell-off allowed Sun Capital and its investors to recover their money and then some, the company entered bankruptcy leaving unpaid more than $80 million in debts to workers’ severance and pensions.

For Sun Capital, this process of buying companies, seeking profits and leaving pensions unpaid is a familiar one. Over the past 10 years, it has taken five companies into bankruptcy while leaving behind debts of about $280 million owed to employee pensions.

The unpaid pension debts mean that some retirees will get smaller checks. Much of the tab will be picked up by the government’s pension insurer, a federal agency facing its own budget shortfalls.

“They did everyone dirty,” said Kilby Baker, 70, a retired warehouse worker whose pension check was cut by about 25 percent after Marsh Supermarkets withdrew from the pension. “We all gave up wage increases so we could have a better pension. Then they just took it away from us.”

Founded by two onetime colleagues at Lehman Brothers, Marc Leder and Rodger R. Krouse, Sun Capital manages billions in private-equity investments, buying and selling companies for profit. The public face of the firm is Leder, a co-owner of the Philadelphia 76ers basketball team and the New Jersey Devils hockey team. Noted for his extravagant parties and yachting expeditions, he has been dubbed by tabloids as “the Hugh Hefner of the Hamptons.”


Politically, he may be best known for hosting the Boca Raton, Fla., dinner where presidential candidate Mitt Romney made what became infamous comments about the “47 percent of the people . . . who are dependent upon government, who believe that they are victims.”

In a statement for this report, Sun Capital said: “Marsh was a struggling business that we worked hard to save. Our investment kept the company alive and provided jobs for its employees for 11 years.”

Over that period, the company invested $150 million in improving some stores and building others, Sun said, and contributed $30 million to pensions for Marsh workers.

“Despite these efforts, and in the face of declining revenues and massive spending by national competitors, Marsh was unfortunately forced to declare bankruptcy and we lost money on our investment,” the statement said.


Regarding the unpaid pensions at the other companies, Leder said in a statement: “You can’t reach a meaningful conclusion by examining such a small percentage of our investments. We’ve done 365 deals in our history and the vast majority have grown and been successful.”

When a company fails, it is sometimes impossible to pay everyone who is owed money. The trouble, according to some critics, is that financial firms often extract money from losing bets to reward themselves and then, through bankruptcy, leave obligations to workers unpaid. Companies owned by private-equity firms have used bankruptcy to leave behind hundreds of millions of dollars in pension debts, according to a government estimate.

“These private-equity firms buy a company, plunder it of any assets, and then send it into bankruptcy without paying employees,” said Eileen Appelbaum, an economist at the Center for Economic and Policy Research who studies private-equity transactions. “To anyone but a bankruptcy court, this looks like a swindle.”


In recent years, some in Congress have sought to change the bankruptcy laws to prevent companies from ditching pension debts through bankruptcy. Last year, Rep. Tim Ryan (D-Ohio) introduced a bill that would give pensions higher priority in bankruptcy payouts. He said that in 2016 alone, 146,000 pensioners overall had seen cuts to their benefits. It did not win passage.

“There’s this idea that pensions are a giveaway,” said Ryan, who expects to reintroduce the legislation in 2019. But “it’s their money. Through negotiations, workers have deferred wages for a pension down the line. For them not to get that money is theft — in a lot of ways. The workers are a pawn in the game.”

Promises made, not kept

Since the 1960s, the United States has grappled with how to prevent companies from reneging on the payment of employee pensions.


“You should keep the promises you make to your workers,” President George W. Bush said in signing the last major U.S. effort in pension reform, the Pension Protection Act, in 2006. “If you offer a private pension plan to your employees, you have a duty to set aside enough money now so your workers will get what they’ve been promised when they retire.”

But the threats to pensions continue. At the heart of federal efforts to protect workers is a low-profile government agency known as the Pension Benefit Guaranty Corp., or the PBGC. The agency collects insurance premiums from companies that offer pensions. When a pension fund runs out of money, the federal agency provides a portion of the lost benefit payments to the affected retirees. In all, it covers the benefits for about 44 million people.

The program has come under mounting financial pressure as more companies have shed their pension debts through bankruptcy.


For example, the part of the government’s pension insurer that backs up benefits for many unionized workers is projected to run out of money by 2025, leaving it unable to protect pensioners, many of whom are facing a wave of trouble: The private-sector pension funds covering more than 1 million unionized workers are expected to run out of money within the next 20 years, according to government estimates.

In the view of Joshua Gotbaum, the former director of the PBGC and a former partner in a private-equity firm, much of the blame lies with the financial firms that buy and sell companies for profit.

“What we’ve seen is that financial firms essentially take the money and run, leaving their employees and the PBGC holding the bag,” said Gotbaum, who was appointed to head the agency by President Barack Obama in 2010.


According to a 2013 tally by Gotbaum, companies controlled by private-equity firms have used bankruptcy to shed more than $650 million of pension obligations. That leaves the government’s pension insurer or employees to pick up the tab.

Since bankruptcy law changed in 1978, Gotbaum said, “the business community has been inventing new uses of the bankruptcy courts. The private-equity community realized they could use Chapter 11 to do pension laundering.”

Shedding debts, buying again

As a public relations matter, companies that default on their pension obligations often blame business conditions. Executives say the companies simply lack the money to replenish the pension fund. But it is often the case that companies neglect the pension even when they have the money: The owners would rather use the cash for other purposes, including taking it as dividends for themselves.


Consider four Sun Capital companies — besides Marsh — that were sent into bankruptcy court.

At two of them, Sun Capital took millions of dollars out of the companies while leaving pensions underfunded.

At Powermate, a manufacturer of electric generators with a factory in Nebraska, Sun Capital took $20 million from the company as a dividend in 2006, according to court documents. Two years later, it sent the company into bankruptcy court, leaving the government insurer to pay for the underfunded pension covering 600 workers.

At Indalex, an Illinois-based aluminum parts maker, Sun extracted a dividend of $70 million in 2007, according to court documents. Two years later it sent the company into bankruptcy, leaving the government insurer to pay more than 3,000 pensioners.

At the other two companies, Friendly’s in 2011 and Fluid Routing Solutions in 2009, Sun Capital used the bankruptcy court to shed the pension obligations — and then kept operating. First, Sun put each company into bankruptcy, essentially relinquishing control. In bankruptcy court, the companies were absolved of their pension debts of $115 million and $30 million, respectively. Then, once the companies were pension-free, Sun Capital bought the same companies out of the ensuing bankruptcy auction.

“They used bankruptcy to get rid of pension obligations they didn’t want — all while retaining ownership,” Gotbaum said.

In response to questions about whether Sun had treated the pensions fairly, the private-equity firm noted that the pension debts at those companies had accrued before Sun became involved: Each of those five companies — Marsh, Powermate, Indalex, Friendly’s and Fluid Routing Solutions — had “significant” pension debts when it acquired them. Indeed, when Sun bought those companies, they were about $90 million behind on pension payments. By the time those Sun companies filed for bankruptcy and the government insurer picked up their pension obligations, however, their pension debts were estimated at $280 million. In part, the pension bills went up because the recession caused pension fund losses. Most of that $280 million debt, however, was shed through the bankruptcy courts.

Sun also noted that these five companies represent only a small sample of its investment portfolio. During the period when these five companies filed for bankruptcy with underfunded pensions, Sun had investments in more than 80 companies.

Origins of Marsh deal
The inspiration for Sun Capital, according to Leder, arose from a visit to Romney’s private-equity firm, Bain Capital.

In April 1995, Leder and Krouse, then both at Lehman Brothers, had a meeting at Bain Capital in Boston and heard executives complaining about an investment in which they’d doubled their money.

“We’re looking at each other saying, ‘This is an industry where double your money is not that good of a deal?’ ” Leder recalled in an interview with the New York Times.

The two founded Sun Capital the same year. They began raising money from investors, then buying and selling companies for profit.

It was in 2006 that Sun Capital would make a play for Marsh Supermarkets. The chain had been launched by Ermal Marsh in the early years of the Great Depression and since then had expanded rapidly, operating under various names across Indiana, Illinois and Ohio: 69 Marsh supermarkets, 38 LoBill Foods stores, eight O’Malia Food Markets and 154 Village Pantry convenience stores. It also had a catering service, pharmacies and a florist business.

But Marsh was also facing fierce competition, particularly from Walmart, and it had begun racking up debt, losing money and suffering from corporate bloat. Don Marsh, Ermal’s son, had taken over the company and, among other extravagances noted by his detractors, he traveled using a corporate jet, a 1997 Citation Ultra.

Yet Sun Capital executives were attracted.

In their view, the supermarket chain was underperforming. It was basically a good business — and if they revamped the company, they thought, there was money to be made, according to former executives who spoke on the condition of anonymity.

Moreover, if they failed at resurrecting the company, they could still turn a profit, former executives said.

The land and buildings owned by Marsh were appraised at about $360 million, according to company financial statements. That meant even if a buyer failed to revive the business, it could make money selling off the stores.

Sun Capital acquired Marsh Supermarkets for $325 million, paying $88 million for the business and assuming $237 million in the company’s debt.

“We see tremendous potential in this 75-year franchise and intend to build upon Marsh’s significant market share in the communities in which it serves,” a Sun Capital executive said in a news release at the time.

The deal goes awry

By most accounts, Sun’s reign at Marsh Supermarkets got off to a good start. Under Sun’s management, corporate overhead was trimmed. The staff at headquarters, which had about 500 people, was pared about 30 percent. Sun executives dropped the company’s pricey corporate sponsorship for the Indiana Pacers NBA team. The company’s jet had been scrapped.

The cost savings, in turn, provided cash to help remodel older stores.

“We were rocking and rolling again,” said a former Marsh executive who spoke on the condition of anonymity. “We saw a sales bump with the store renovations.”

The profits didn’t last. Former Marsh executives cited a variety of reasons for Marsh’s subsequent demise: the recession, which continued to depress consumer spending; executive turnover at Marsh; and finally, competition from other larger chains, particularly Kroger and Meijer, which cut into margins.

Marsh Supermarkets was on a long, slow road to bankruptcy, but Sun Capital and its investors nonetheless would manage to recover their investment, mainly by selling the company off in pieces.

One of the first moves they made at Marsh was a “sale-leaseback,” and it was critical. Marsh sold off its real estate portfolio for about $260 million, according to Marsh documents, and then leased the stores back from the new owners.

There were more sales to come. In 2013, Marsh sold some of its convenience stores for $48 million, according to a lawsuit filed by the buyer. And in 2015, Marsh collected an additional $40 million with the sale of the rest of the convenience stores, according to the same lawsuit. Some of the money from these sales stayed with Marsh; some went back to Sun Capital.

When considering whether anyone made money with the Marsh investment, there are two parties to consider.

First are the investors who turned over money to Sun Capital to invest in buying and selling companies such as Marsh Supermarkets. These investors got back almost all of the money they sank into Marsh, according to a cash-flow statement obtained by The Washington Post. They recovered all but $500,000 of the $51 million invested in buying and renovating the chain. When Sun Capital says the investment lost money, this is what they are referring to.

But then there is Sun Capital Partners itself. It did better than merely recover its investment. As an investor in its own fund, it may have shared a small portion of the $500,000 loss. But private-equity firms also collect fees on the portfolio of companies they manage, and these would have more than made up for that slight loss. Sun Capital collected a $1 million annual management fee from Marsh, according to former executives. Sun Capital also has collected large commissions for selling off assets, as it did with Marsh, but it is not known how much Sun Capital took in such commissions in this case. Sun Capital declined to share the fees in the Marsh deal.

Even with the eventual bankruptcy, “there’s no way Sun lost money on that deal,” said Douglas W. Dougherty, chief financial officer at Marsh Supermarkets until a few months after Sun Capital acquired the company. “The value of the real estate in the company, which they sold, was just too much.”

Although Sun Capital investors were basically repaid, the Marsh pension debts were not. The company was notified in May 2012 — just a few days after the Romney dinner — that it owed $62 million to the pension for warehouse workers. At the same time, it was behind millions of dollars to the pension covering store employees. Those debts remained largely unpaid at the time of bankruptcy.

“Sun thus stripped [Marsh Supermarkets and its affiliates] of more than $100 million that should have been used to resolve the pension obligation,” alleges a lawsuit filed by GPM Investments, the company that bought the convenience stores and is disputing whether it is liable for any of the pension debt.

Through its attorneys, GPM Investments declined to comment.

Marsh pensions unpaid

When Sun bought Marsh Supermarkets, the company had three retirement plans. One for the top five Marsh executives, one for the store employees, and one for the warehouse workers.

Only the executives’ plan, however, was fully funded under the sales agreement: With the completion of Sun’s purchase, Marsh’s top five executives were to be awarded $14 million in retirement payments, according to company financial documents. Among them: CEO Don Marsh at $7 million and corporate counsel P. Lawrence Butt at $2.2 million.

Meanwhile, the other two retirement plans — the worker pensions — were short millions of dollars.

The pension for store employees — deli clerks, cashiers, store managers — was underfunded by $32 million at the time of the bankruptcy. Most of that burden will be placed on the government insurer, the Pension Benefit Guaranty Corp., which will restore virtually all of what the 4,000 store employees entitled to pensions were owed in retirement.

The pension covering the company’s warehouse workers fared worst.

At the time of the bankruptcy, Marsh Supermarkets was behind in its obligations to that pension by $55 million, and because of the way that pension is organized, the shortfall is likely to help cause significant cuts to pension checks for retirees and accelerate financial woes of the government’s pension insurer.

The pension fund for Marsh’s warehouse workers is part of a Teamsters-affiliated fund known as Central States, which covers about 400,000 people. Even before the Marsh bankruptcy, Central States was running out of money, partly because so many trucking companies have filed for bankruptcy. More than $1.5 billion of the Central States pension shortfall can be traced to bankruptcy by companies owned by private-equity firms, according to the pension fund. It is expected to be insolvent within seven years.

Barring a government intervention, pensioners who worked at Marsh’s warehouses, making about $17 an hour, may get very little of the pensions they were expecting.

For years, the warehouse workers had given up wage increases to get a better pension, they said.

Yet some retirees already have seen cuts to the amounts they had been promised. The highest pension checks run about $2,600 a month, cut from more than $3,000, according to retirees. When Sun pulled Marsh Supermarkets out of the Central States pension plan in 2012, pension benefits dropped about 25 percent, pension officials said.

But the projected insolvency of the Central States pension would be far worse — stranding not only the Marsh warehouse workers but thousands of other pensioners who rely on it.

“They’re jacking with people’s lives,” said Darren Cooper, 48, who worked at the warehouse for 26 years until the bankruptcy. “When Sun took over, we were kind of all taken aback. You didn’t mind working for a place that started up right around here. But then all of a sudden with Sun, we’re working for some rich guy from somewhere else who doesn’t care about you. They don’t even know who you are — they’re just counting their money.”

Among those who have seen their benefit drop is Phil Rainey, 70, who worked in the Marsh warehouse for decades. He began at Marsh’s ice cream factory in 1967, a year after graduating from high school. His mother had worked at the Marsh bakery. He was drafted a couple years later and, after an Army tour in Vietnam, Rainey worked the next 42 years at the Marsh warehouse. Over that time, he got married, bought a house, and raised two daughters.

Like others in his union, Rainey was willing to give up wage increases to get a better pension, and as he thought about retirement, he figured his finances would hold, thanks to the monthly benefit. And just to get his “ducks in a row,” he also arranged to pay off his home mortgage. Like many planning retirement, he didn’t want to have to worry.

Already, though, his monthly benefit payment has been cut about 25 percent, and the promised certainty of a stable monthly pension check has been elusive.

“I’ve been fighting since I retired to keep the pension,” Rainey said. “And I think about it a lot. We don’t know what’s going to happen.”

He has received notices saying that the Central States pension is projected to run out of money in 2025. And that the government insurance program that normally would have insured those pension benefits is expected to go bust about the same time.

“Seems kind of funny that those two would run out of money at the same time,” Rainey said skeptically.

“But then, it’s not funny at all. If I lose my pension, what am I going to do? Who’s going to hire a 75-year-old man?”

程式語言編年史

程式語言編年史原文 下面這張圖片描繪了整個程式語言的歷史。包括各種程式語言的發明人、程式語言的特點和適用領域、被什麼網站或公司使用等 (檢視 完整高清圖 )。 之所以會有那麼多不同的程式語言是因為設計程式語言的初衷不同、對語言學習曲線的追求不同、不同程式之間的執行成本差異...