Create App Icons for React Native Android App

First you need one png file as your launcher icon.
icon
Then you need to resize this icon file to needed resolutions.
There is a simple service to resize your app icon to all needed resolutions with rocket speed.
Then you can download all your needed icons.
icons
Then replace each ic_launcher.png via image with correct resolution.
webrowser/android$ find -name "ic_launcher.png"
./app/src/main/res/mipmap-hdpi/ic_launcher.png
./app/src/main/res/mipmap-mdpi/ic_launcher.png
./app/src/main/res/mipmap-xhdpi/ic_launcher.png
./app/src/main/res/mipmap-xxhdpi/ic_launcher.png

Or you can use Image Asset Studio to create App Icons.
1.open Android Studio poject in your react native application.
open-app
2.use Image Asset Studio
open-image-asset
In the Foreground Layer tab, select an Asset Type, and then specify the asset in the field underneath:
Select Image to specify the path for an image file.

If your app supports Android 8.0, create adaptive and legacy launcher icons.
ic_launcher
If your app supports versions no higher than Android 7.1, create a legacy launcher icon only.
ic_launcher-1

Check the result
react-native run-android

lc

Refer

https://developer.android.com/studio/write/image-asset-studio.html
https://www.npmjs.com/package/react-native-icon

Configure Proxy Settings for CMD.EXE, WinHttp

winhttp
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Users\lenger>netsh
netsh>winhttp
netsh winhttp>set proxy /?

Usage: set proxy [proxy-server=] [bypass-list=]

Parameters:

Tag Value
proxy-server - proxy server for use for http and/or https protocol
bypass-list - a list of sites that should be visited bypassing the
proxy (use "" to bypass all short name hosts)

Examples:

set proxy myproxy
set proxy myproxy:80 ";bar"
set proxy proxy-server="http=myproxy;https=sproxy:88" bypass-list="*.foo.com"

netsh winhttp>

set HTTP_PROXY=server:port
set HTTPS_PROXY=server:port

Refer

https://technet.microsoft.com/en-us/library/bb430772(v=exchg.141).aspx

install and build your first React Native app on windows

Installing Chocolatey with cmd.exe

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin" 

Installing Node, Python2 and JDK with Chocolatey

choco install -y nodejs.install python2 jdk8 

Install The React Native CLI

npm install -g react-native-cli 

Setup Android Studio

Create Virtual Device

Create New Application

react-native init AwesomeProject 

Run android

Launch your AVD before run-android

react-native run-android 

If every works well, below is your final result:
React-native-sample

Refer

https://facebook.github.io/react-native/docs/getting-started.html
https://chocolatey.org/install

Troubleshooting page

npm proxy set
run-android connection timeout
unable to load index.android.bundle

Unable to load script from assets index.android.bundle

Unable to load script from assets index.android.bundle

Solution

mkdir android/app/src/main/assets react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res 

Run

react-native run-android
Total time: 23.641 secs
'adb' is not recognized as an internal or external command,
operable program or batch file.
Starting the app (C:\Users\lenger\AppData\Local\Android\Sdk/platform-tools/adb shell am start -n com.webrowser/com.webrowser.MainActivity...
Starting: Intent { cmp=com.webrowser/.MainActivity }
React-native-sample

react-native run-android : Connection timed out

Error Log

Downloading https://services.gradle.org/distributions/gradle-2.14.1-all.zip

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
at org.gradle.wrapper.Download.download(Download.java:44)
at org.gradle.wrapper.Install$1.call(Install.java:59)
at org.gradle.wrapper.Install$1.call(Install.java:46)
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:46)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:126)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

Cause

The root cause was your computer need a proxy to download gradle-2.14.1-all.zip
And the file was not downloaded by react-native command or other shell command,
it was downloaded by java codes in your react-native application.
As android uses grandle for building project, We have to set proxy server in grandle property file.

Solution

Add the following lines in gradle.properties in the android folder
systemProp.http.proxyHost=xxx.xxx.xxx.xxx
systemProp.http.proxyPort=xxxx
systemProp.https.proxyHost=xxx.xxx.xxx.xxx
systemProp.https.proxyPort=xxxx

npm config http/https proxy

npm --proxy http://username:password@server:port install packagename
npm config set proxy http://username:password@server:port
npm config set https-proxy http://username:password@server:port
 
npm config set strict-ssl false
npm config set registry "http://registry.npmjs.org/"


npm config rm proxy
npm config rm https-proxy

show hospitality to strangers

你们务要常存弟兄相爱的心。 (希伯来书 13:1 和合本)
Keep on loving one another as brothers and sisters. (Hebrews 13:1 NIV)
不可忘记用爱心接待客旅;因为曾有接待客旅的,不知不觉就接待了天使。 (希伯来书 13:2 和合本)
Do not forget to show hospitality to strangers, for by so doing some people have shown hospitality to angels without knowing it. (Hebrews 13:2 NIV)
你们要记念被捆绑的人,好像与他们同受捆绑;也要记念遭苦害的人,想到自己也在肉身之内。 (希伯来书 13:3 和合本)
Continue to remember those in prison as if you were together with them in prison, and those who are mistreated as if you yourselves were suffering. (Hebrews 13:3 NIV)


Photo by Diego PH / Unsplash

Trust in the Lord

天怎样高过地,照样,我的道路高过你们的道路;我的意念高过你们的意念。 (以赛亚书 55:9 和合本)
"As the heavens are higher than the earth, so are my ways higher than your ways and my thoughts than your thoughts. (Isaiah 55:9 NIV)

你要专心仰赖耶和华,不可倚靠自己的聪明, (箴言 3:5 和合本)
Trust in the Lord with all your heart and lean not on your own understanding; (Proverbs 3:5 NIV)
在你一切所行的事上都要认定他,他必指引你的路。 (箴言 3:6 和合本)
in all your ways submit to him, and he will make your paths straight. (Proverbs 3:6 NIV)


Photo by Federico Respini / Unsplash

微信开放平台 创建移动应用 Android 应用签名

appsign

keystore file decide it.

In fact, it is MD5 value of the keystore file.
please refer https://errong.win/generate-keystore/ to generate the keystore file.
You can get the MD5 via
keytool -list -v -keystore webrowser.keystore
MD5: 4F:87:B6:11:A4:37:5A:29:E4:A2:F7:BD:2B:DC:CC:18
Remove all ":" and turn the string to lower case.
Application signature is :
4f87b611a4375a29e4a2f7bd2bdccc18

Generate keystore file to sign your android apk

Tool

keytool
You can get this tool after you installed jdk.

Command

C:\Program Files\Java\jdk1.8.0_121\bin>keytool.exe -genkey -alias "webrowser" -keyalg "RSA" -validity 10000 -keystore "webrowser.keystore"
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: Errong
What is the name of your organizational unit?
[Unknown]: Errong
What is the name of your organization?
[Unknown]: Errong
What is the name of your City or Locality?
[Unknown]: Nanjing
What is the name of your State or Province?
[Unknown]: JiangSu
What is the two-letter country code for this unit?
[Unknown]: CN
Is CN=Errong, OU=Errong, O=Errong, L=Nanjing, ST=JiangSu, C=CN correct?
[no]:
What is your first and last name?
[Errong]:
What is the name of your organizational unit?
[Errong]:
What is the name of your organization?
[Errong]:
What is the name of your City or Locality?
[Nanjing]:
What is the name of your State or Province?
[JiangSu]:
What is the two-letter country code for this unit?
[CN]:
Is CN=Errong, OU=Errong, O=Errong, L=Nanjing, ST=JiangSu, C=CN correct?
[no]: yes

Enter key password for
(RETURN if same as keystore password):

keystore file

C:\Program Files\Java\jdk1.8.0_121\bin>dir webrowser.keystore
Volume in drive C has no label.
Volume Serial Number is 40EA-8B0A

Directory of C:\Program Files\Java\jdk1.8.0_121\bin

12/27/2017 07:19 PM 2,230 webrowser.keystore
1 File(s) 2,230 bytes
0 Dir(s) 58,290,343,936 bytes free

list keystore file

C:\Program Files\Java\jdk1.8.0_121\bin>keytool -list -v -keystore webrowser.keystore
Enter keystore password:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: webrowser
Creation date: Dec 27, 2017
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Errong, OU=Errong, O=Errong, L=Nanjing, ST=JiangSu, C=CN
Issuer: CN=Errong, OU=Errong, O=Errong, L=Nanjing, ST=JiangSu, C=CN
Serial number: 4c63eb8d
Valid from: Wed Dec 27 19:19:32 CST 2017 until: Sun May 14 19:19:32 CST 2045
Certificate fingerprints:
MD5: 4F:87:B6:11:A4:37:5A:29:E4:A2:F7:BD:2B:DC:CC:18
SHA1: 21:F8:D8:7E:39:8E:49:C5:BE:A0:A1:8A:19:5E:3F:C0:4E:3F:05:66
SHA256: 77:31:F3:CB:D5:C1:1F:8D:1B:9E:A8:9D:5F:65:C8:64:56:48:8A:FB:32:BB:05:D2:5D:13:B0:8A:2C:92:D3:9F
Signature algorithm name: SHA256withRSA
Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 67 8A E4 45 0E 2D 10 87 44 E4 11 B2 C8 34 B1 A5 g..E.-..D....4..
0010: 62 4B FA BD bK..
]
]

We Browser

light web browser, heave social share

Godliness Training

"操练身体,益处还少;惟独敬虔,凡事都有益处,因有今生和来生的应许。" (提摩太前书 4:8 和合本)
For physical training is of some value, but godliness has value for all things, holding promise for both the present life and the life to come. (1 Timothy 4:8 NIV)


Photo by Ines Álvarez Fdez / Unsplash

wrong LC_NUMBERIC cause CSS unsupported value

warning: unsupported value
position: absolute; width: 12.9em; transform: translateX(16.27em);
^
and you know, some countries uses decimal point as comma - not point.
so scanf function cannot read "12.9em" if we set NUMERIC at that country.
Such as French.
 
// query LC_NUMERIC 
char* locale = setlocale(LC_NUMERIC, NULL); 
// set LC_NUMERIC 
char* locale = "en_US.utf8"; 
setlocale(LC_NUMERIC, locale); 
 
if LC_NUMERIC was set to "frCA.UTF-8",
12.9em can't be read as a Decimal.
The correct should be like "en_US.utf8"
Refer:
https://en.wikipedia.org/wiki/Decimal_mark
http://man7.org/linux/man-pages/man3/setlocale.3.html

故意犯罪 真是可怕的

If we deliberately keep on sinning after we have received the knowledge of the truth, no sacrifice for sins is left, (Hebrews 10:26 NIV)
惟有战惧等候审判和那烧灭众敌人的烈火。 (希伯来书 10:27 和合本)
but only a fearful expectation of judgment and of raging fire that will consume the enemies of God. (Hebrews 10:27 NIV)
人干犯摩西的律法,凭两三个见证人,尚且不得怜恤而死, (希伯来书 10:28 和合本)
Anyone who rejected the law of Moses died without mercy on the testimony of two or three witnesses. (Hebrews 10:28 NIV)
何况人践踏 神的儿子,将那使他成圣之约的血当作平常,又亵慢施恩的圣灵,你们想,他要受的刑罚该怎样加重呢! (希伯来书 10:29 和合本)
How much more severely do you think someone deserves to be punished who has trampled the Son of God underfoot, who has treated as an unholy thing the blood of the covenant that sanctified them, and who has insulted the Spirit of grace? (Hebrews 10:29 NIV)
因为我们知道谁说:"伸冤在我,我必报应";又说:"主要审判他的百姓。" (希伯来书 10:30 和合本)
For we know him who said, "It is mine to avenge; I will repay," and again, "The Lord will judge his people." (Hebrews 10:30 NIV)
落在永生 神的手里,真是可怕的! (希伯来书 10:31 和合本)
It is a dreadful thing to fall into the hands of the living God. (Hebrews 10:31 NIV)

Photo by Drew Jones / Unsplash

主啊!你在我生命的旨意是什么?

人一生虚度的日子,就如影儿经过,谁知道什么与他有益呢?谁能告诉他身后在日光之下有什么事呢? (传道书 6:12 和合本)
For who knows what is good for a person in life, during the few and meaningless days they pass through like a shadow? Who can tell them what will happen under the sun after they are gone? (Ecclesiastes 6:12 NIV)


Photo by Jonatan Pie / Unsplash

auto learn account


会计人员继续教育网上培训 只需要登录你的账号。
所有的课程将会自动开始学习 无需你再理会 只要开着浏览器即可。
自动勾选学习过程中弹出的问题,学习过程不会再被卡住。

https://www.youtube.com/watch?v=V9zXnnQQRUE&feature=youtu.be

FireFox Plugin:
https://addons.mozilla.org/en-US/firefox/addon/auto-learn-account/



HOW ARE YOUR EYES?

耶稣过去的时候,看见一个人生来是瞎眼的。 (约翰福音 9:1 和合本)
As he went along, he saw a man blind from birth. (John 9:1 NIV)
门徒问耶稣说:"拉比,这人生来是瞎眼的,是谁犯了罪?是这人呢?是他父母呢?" (约翰福音 9:2 和合本)
His disciples asked him, "Rabbi, who sinned, this man or his parents, that he was born blind?" (John 9:2 NIV)
耶稣回答说:"也不是这人犯了罪,也不是他父母犯了罪,是要在他身上显出 神的作为来。 (约翰福音 9:3 和合本)
"Neither this man nor his parents sinned,"said Jesus, "but this happened so that the works of God might be displayed in him. (John 9:3 NIV)
趁着白日,我们必须做那差我来者的工;黑夜将到,就没有人能做工了。 (约翰福音 9:4 和合本)
As long as it is day, we must do the works of him who sent me. Night is coming, when no one can work. (John 9:4 NIV)
我在世上的时候,是世上的光。" (约翰福音 9:5 和合本)
While I am in the world, I am the light of the world." (John 9:5 NIV)
耶稣说了这话,就吐唾沫在地上,用唾沫和泥抹在瞎子的眼睛上, (约翰福音 9:6 和合本)
After saying this, he spit on the ground, made some mud with the saliva, and put it on the man's eyes. (John 9:6 NIV)
对他说:"你往西罗亚池子里去洗。"(西罗亚翻出来就是"奉差遣"。)他去一洗,回头就看见了。 (约翰福音 9:7 和合本)
"Go,"he told him, "wash in the Pool of Siloam"(this word means "Sent"). So the man went and washed, and came home seeing. (John 9:7 NIV)
他的邻舍和那素常见他是讨饭的,就说:"这不是那从前坐着讨饭的人吗?" (约翰福音 9:8 和合本)
His neighbors and those who had formerly seen him begging asked, "Isn't this the same man who used to sit and beg?" (John 9:8 NIV)
有人说:"是他";又有人说:"不是,却是像他。"他自己说:"是我。" (约翰福音 9:9 和合本)
Some claimed that he was. Others said, "No, he only looks like him." But he himself insisted, "I am the man." (John 9:9 NIV)
他们对他说:"你的眼睛是怎么开的呢?" (约翰福音 9:10 和合本)
"How then were your eyes opened?" they asked. (John 9:10 NIV)
他回答说:"有一个人,名叫耶稣,他和泥抹我的眼睛,对我说:'你往西罗亚池子去洗。'我去一洗,就看见了。" (约翰福音 9:11 和合本)
He replied, "The man they call Jesus made some mud and put it on my eyes. He told me to go to Siloam and wash. So I went and washed, and then I could see." (John 9:11 NIV)


Photo by Monica Galentino / Unsplash

CHRIST’S INVITATION

节期的末日,就是最大之日,耶稣站着高声说:"人若渴了,可以到我这里来喝。 (约翰福音 7:37 和合本)
On the last and greatest day of the festival, Jesus stood and said in a loud voice, "Let anyone who is thirsty come to me and drink. (John 7:37 NIV)
信我的人就如经上所说:'从他腹中要流出活水的江河来。'" (约翰福音 7:38 和合本)
Whoever believes in me, as Scripture has said, rivers of living water will flow from within them." (John 7:38 NIV)


Photo by Michael Bomke / Unsplash

PETER’S CONFESSION

耶稣到了凯撒利亚·腓立比的境内,就问门徒说:"人说我(有古卷没有我字) —人子是谁?" (马太福音 16:13 和合本)
When Jesus came to the region of Caesarea Philippi, he asked his disciples, "Who do people say the Son of Man is?" (Matthew 16:13 NIV)
他们说:"有人说是施洗的约翰;有人说是以利亚;又有人说是耶利米或是先知里的一位。" (马太福音 16:14 和合本)
They replied, "Some say John the Baptist; others say Elijah; and still others, Jeremiah or one of the prophets." (Matthew 16:14 NIV)
耶稣说:"你们说我是谁?" (马太福音 16:15 和合本)
"But what about you?"he asked. "Who do you say I am?" (Matthew 16:15 NIV)
西门·彼得回答说:"你是基督,是永生 神的儿子。" (马太福音 16:16 和合本)
Simon Peter answered, "You are the Messiah, the Son of the living God." (Matthew 16:16 NIV)
耶稣对他说:"西门·巴·约拿,你是有福的!因为这不是属血肉的指示你的,乃是我在天上的父指示的。 (马太福音 16:17 和合本)
Jesus replied, "Blessed are you, Simon son of Jonah, for this was not revealed to you by flesh and blood, but by my Father in heaven. (Matthew 16:17 NIV)
我还告诉你,你是彼得,我要把我的教会建造在这磐石上;阴间的权柄(权柄:原文是门) 不能胜过他。 (马太福音 16:18 和合本)
And I tell you that you are Peter, and on this rock I will build my church, and the gates of Hades will not overcome it. (Matthew 16:18 NIV)
我要把天国的钥匙给你,凡你在地上所捆绑的,在天上也要捆绑;凡你在地上所释放的,在天上也要释放。" (马太福音 16:19 和合本)
I will give you the keys of the kingdom of heaven; whatever you bind on earth will be bound in heaven, and whatever you loose on earth will be loosed in heaven." (Matthew 16:19 NIV)
当下,耶稣嘱咐门徒,不可对人说他是基督。 (马太福音 16:20 和合本)
Then he ordered his disciples not to tell anyone that he was the Messiah. (Matthew 16:20 NIV)
从此,耶稣才指示门徒,他必须上耶路撒冷去,受长老、祭司长、文士许多的苦,并且被杀,第三日复活。 (马太福音 16:21 和合本)
From that time on Jesus began to explain to his disciples that he must go to Jerusalem and suffer many things at the hands of the elders, the chief priests and the teachers of the law, and that he must be killed and on the third day be raised to life. (Matthew 16:21 NIV)


Photo by Chris Barbalis / Unsplash

KVM folder share, networking, host and guest IP

Create Virtual Machine via KVM

nat

Host IP of KVM, run ifconfig on host

~$ ifconfig 
virbr0    Link encap:Ethernet  HWaddr fe:54:00:ad:73:64  
          inet addr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:588122 errors:0 dropped:0 overruns:0 frame:0
          TX packets:749737 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:31412184 (31.4 MB)  TX bytes:1267281456 (1.2 GB)

Guest IP, run ifconfig on created virtual machine.

~$ ifconfig 
eth0      Link encap:Ethernet  HWaddr 52:54:00:ad:73:64  
          inet addr:192.168.122.112  Bcast:192.168.122.255  Mask:255.255.255.0
          inet6 addr: fe80::5054:ff:fead:7364/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:415799 errors:0 dropped:3 overruns:0 frame:0
          TX packets:252791 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:714784870 (714.7 MB)  TX bytes:17348958 (17.3 MB)

KVM IPs

192.168.122.112 is your virtual machine IP.
192.168.122.1 is your host IP.
We can easy share folder on host to your virtual machine via networking mount.
mount 192.168.122.1:/home /mnt 
 
scp, ssh also can be used too.

Install KVM and Create Virtual Machines on Ubuntu

Refer to:
https://www.howtogeek.com/117635/how-to-install-kvm-and-create-virtual-machines-on-ubuntu/
Summary:

Determine whether your CPU support hardware virtualization

egrep -c '(svm|vmx)' /proc/cpuinfo 
A 0 indicates that your CPU doesn't support hardware virtualization, while a 1 or more indicates that it does. You still have to enable hardware virtualization support in your computer's BIOS, even if this command returns a 1 or more.
Otherwise you will get a warning later on:
KVM is not available. This may mean the KVM package is not installed, 
or the KVM kernel modules are not loaded. 
Your virtual machines may perform poorly. 

Install KVM

sudo apt-get install qemu-kvm libvirt-bin bridge-utils virt-manager 

Add user to libvirtd group

sudo adduser name libvirtd 

Create Virtual Machines via virt-manager

virt-manager 
kvm
Click the Create New Virtual Machine button on the toolbar and the Virtual Machine Manager will walk you through selecting an installation method, configuring your virtual machine's virtual hardware, and installing your guest operating system of choice.

By the way:
You can creae raw image via qemu-img.
qemu-img create -f raw ubuntu_desktop_14.04.5.img 100G
$ ls *.img -all
-rw-r--r-- 1 libvirt-qemu kvm 107374182400  4 18:06 
ubuntu_desktop_14.04.5.img

The Lord has done great things

当耶和华将那些被掳的带回锡安的时候,我们好像做梦的人。 (诗篇 126:1 和合本)
When the Lord restored the fortunes of Zion, we were like those who dreamed. (Psalms 126:1 NIV)
我们满口喜笑、满舌欢呼的时候,外邦中就有人说:耶和华为他们行了大事! (诗篇 126:2 和合本)
Our mouths were filled with laughter, our tongues with songs of joy. Then it was said among the nations, "The Lord has done great things for them." (Psalms 126:2 NIV)
耶和华果然为我们行了大事,我们就欢喜。 (诗篇 126:3 和合本)
The Lord has done great things for us, and we are filled with joy. (Psalms 126:3 NIV)
耶和华啊,求你使我们被掳的人归回,好像南地的河水复流。 (诗篇 126:4 和合本)
Restore our fortunes, Lord , like streams in the Negev. (Psalms 126:4 NIV)
流泪撒种的,必欢呼收割! (诗篇 126:5 和合本)
Those who sow with tears will reap with songs of joy. (Psalms 126:5 NIV)
那带种流泪出去的,必要欢欢乐乐地带禾捆回来! (诗篇 126:6 和合本)
Those who go out weeping, carrying seed to sow, will return with songs of joy, carrying sheaves with them. (Psalms 126:6 NIV)

Where are you?

于是女人见那棵树的果子好作食物,也悦人的眼目,且是可喜爱的,能使人有智慧,就摘下果子来吃了,又给她丈夫,她丈夫也吃了。 (创世记 3:6 和合本)
When the woman saw that the fruit of the tree was good for food and pleasing to the eye, and also desirable for gaining wisdom, she took some and ate it. She also gave some to her husband, who was with her, and he ate it. (Genesis 3:6 NIV)
他们二人的眼睛就明亮了,才知道自己是赤身露体,便拿无花果树的叶子为自己编做裙子。 (创世记 3:7 和合本)
Then the eyes of both of them were opened, and they realized they were naked; so they sewed fig leaves together and made coverings for themselves. (Genesis 3:7 NIV)
天起了凉风,耶和华 神在园中行走。那人和他妻子听见 神的声音,就藏在园里的树木中,躲避耶和华 神的面。 (创世记 3:8 和合本)
Then the man and his wife heard the sound of the Lord God as he was walking in the garden in the cool of the day, and they hid from the Lord God among the trees of the garden. (Genesis 3:8 NIV)
耶和华 神呼唤那人,对他说:"你在哪里?" (创世记 3:9 和合本)
But the Lord God called to the man, "Where are you?" (Genesis 3:9 NIV)


Photo by chuttersnap / Unsplash

Can pthread_mutex_lock still work after pthread mutex_destroy ?

Refer:
https://linux.die.net/man/3/pthread_mutex_init
The pthread_mutex_destroy() function shall destroy the mutex object referenced by mutex; the mutex object becomes, in effect, uninitialized. An implementation may cause pthread_mutex_destroy() to set the object referenced by mutex to an invalid value. A destroyed mutex object can be reinitialized using pthread_mutex_init(); the results of otherwise referencing the object after it has been destroyed are undefined.
What is the undefined behavior ?
Let's us wirte sample codes to verify it.
#include <pthread.h>
#include <iostream>
#include <unistd.h>

using namespace std;

static pthread_mutex_t foo_mutex;

static void *
thread1(void *arg)
{
   while(1) {
       pthread_mutex_lock(&foo_mutex);
       cout << "thread 1 running" << endl;
       sleep(2);
   }
}

static void *
thread2(void *arg)
{
   while(1) {
       pthread_mutex_lock(&foo_mutex);
       cout << "thread 2 running" << endl;
       sleep(2);
   }
}

int main()
{
    pthread_mutex_init(&foo_mutex, NULL);
    pthread_mutex_destroy(&foo_mutex);
    pthread_t p1;
    pthread_t p2;
    pthread_create(&p1, 0, thread1, 0);
    pthread_create(&p2, 0, thread2, 0);

    pthread_join(p1, 0);
    pthread_join(p2, 0);

    return 0;
}
~$ g++ -o pmt pmt.cpp -lpthread
~$ ./pmt
thread 1 runningthread 2 running
thread 2 running
thread 1 running
thread 2 running
thread 1 running
thread 2 running
thread 1 running
......
The result is NOT WORK ANY MORE.

A Sabbath-rest for the people of God

我们既蒙留下,有进入他安息的应许,就当畏惧,免得我们(原文是你们) 中间或有人似乎是赶不上了。 (希伯来书 4:1 和合本)
Therefore, since the promise of entering his rest still stands, let us be careful that none of you be found to have fallen short of it. (Hebrews 4:1 NIV)
因为有福音传给我们,像传给他们一样;只是所听见的道与他们无益,因为他们没有信心与所听见的道调和。 (希伯来书 4:2 和合本)
For we also have had the good news proclaimed to us, just as they did; but the message they heard was of no value to them, because they did not share the faith of those who obeyed. (Hebrews 4:2 NIV)
但我们已经相信的人得以进入那安息,正如 神所说:"我在怒中起誓说:'他们断不可进入我的安息!'"其实造物之工,从创世以来已经成全了。 (希伯来书 4:3 和合本)
Now we who have believed enter that rest, just as God has said, "So I declared on oath in my anger, 'They shall never enter my rest.' " And yet his works have been finished since the creation of the world. (Hebrews 4:3 NIV)
论到第七日,有一处说:"到第七日, 神就歇了他一切的工。" (希伯来书 4:4 和合本)
For somewhere he has spoken about the seventh day in these words: "On the seventh day God rested from all his works." (Hebrews 4:4 NIV)
又有一处说:"他们断不可进入我的安息!" (希伯来书 4:5 和合本)
And again in the passage above he says, "They shall never enter my rest." (Hebrews 4:5 NIV)
既有必进安息的人,那先前听见福音的,因为不信从,不得进去。 (希伯来书 4:6 和合本)
Therefore since it still remains for some to enter that rest, and since those who formerly had the good news proclaimed to them did not go in because of their disobedience, (Hebrews 4:6 NIV)
所以过了多年,就在大卫的书上,又限定一日,如以上所引的说:"你们今日若听他的话,就不可硬着心。" (希伯来书 4:7 和合本)
God again set a certain day, calling it "Today." This he did when a long time later he spoke through David, as in the passage already quoted: "Today, if you hear his voice, do not harden your hearts." (Hebrews 4:7 NIV)
若是约书亚已叫他们享了安息,后来 神就不再提别的日子了。 (希伯来书 4:8 和合本)
For if Joshua had given them rest, God would not have spoken later about another day. (Hebrews 4:8 NIV)
这样看来,必另有一安息日的安息为 神的子民存留。 (希伯来书 4:9 和合本)
There remains, then, a Sabbath-rest for the people of God; (Hebrews 4:9 NIV)


Photo by Natalie Toombs / Unsplash

bring good news

那报佳音,传平安,报好信,传救恩的,对锡安说:你的 神作王了!这人的脚登山何等佳美! (以赛亚书 52:7 和合本)
How beautiful on the mountains are the feet of those who bring good news, who proclaim peace, who bring good tidings, who proclaim salvation, who say to Zion, "Your God reigns!" (Isaiah 52:7 NIV)


Photo by Flo Dahm / Unsplash

Correct usage of tzset(), TZ env

https://knowledgebase.progress.com/articles/Article/000044163
TZ variable can be set on on for a session, user profile or use it in the Database start-up script to start the database for the specific timezone or country or city.

Following are some examples can be tested in a terminal session of UNIX.

For China is UTC+8:00 or GMT+8:00

TZ needs to set it with opposite sign as follows:

TZ=UTC-8:00; export TZ
or,
TZ=GMT-8:00; export TZ
or,
TZ=Asia/Shanghai;export TZ

setenv("TZ", "GMT-8:00", 1) tzset(); 

For US EST (GMT-5:00, New York):

TZ=UTC+5:00; export TZ
Or,
TZ=GMT+5:00; export TZ
Or,
TZ=America/New_York;export TZ

setenv("TZ", "UTC+5:00", 1) tzset(); 

Trapping Rain Water

Question:

http://www.lintcode.com/en/problem/trapping-rain-water/
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

Example

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

Answer

RunTime : 1272ms
class Solution {
public:
 /*
 * @param heights: a list of integers
 * @return: a integer
 */
 int trapRainWater(vector<int> &heights) {
  // write your code here
  if (heights.size() < 3)
   return 0;
  int result = 0;
  size_t l, r;
  l = 0;
  r = heights.size() - 1;
  while (l < r) {
   while (l < r && heights[l] == 0) l++;
   while (l < r && heights[r] == 0) r--;
   int min = heights[l] < heights[r] ? 
                                  heights[l] : heights[r];
   for (size_t i = l; i <= r; i++) {
    if (heights[i] >= min)
     heights[i] -= min;
    else {
     result += min - heights[i];
     heights[i] = 0;
    }
   }
  }
  return result;
 }
};

Earn Money from YunFile

RIGHT ACTIONS FROM WRONG MOTIVES

"你们祷告的时候,不可像那假冒为善的人,爱站在会堂里和十字路口上祷告,故意叫人看见。我实在告诉你们,他们已经得了他们的赏赐。 (马太福音 6:5 和合本)
"And when you pray, do not be like the hypocrites, for they love to pray standing in the synagogues and on the street corners to be seen by others. Truly I tell you, they have received their reward in full. (Matthew 6:5 NIV)
你祷告的时候,要进你的内屋,关上门,祷告你在暗中的父;你父在暗中察看,必然报答你。 (马太福音 6:6 和合本)
But when you pray, go into your room, close the door and pray to your Father, who is unseen. Then your Father, who sees what is done in secret, will reward you. (Matthew 6:6 NIV)
你们祷告,不可像外邦人,用许多重复话,他们以为话多了必蒙垂听。 (马太福音 6:7 和合本)
And when you pray, do not keep on babbling like pagans, for they think they will be heard because of their many words. (Matthew 6:7 NIV)
你们不可效法他们;因为你们没有祈求以先,你们所需用的,你们的父早已知道了。 (马太福音 6:8 和合本)
Do not be like them, for your Father knows what you need before you ask him. (Matthew 6:8 NIV)
所以,你们祷告要这样说:我们在天上的父:愿人都尊你的名为圣。 (马太福音 6:9 和合本)
"This, then, is how you should pray: " 'Our Father in heaven, hallowed be your name, (Matthew 6:9 NIV)
愿你的国降临;愿你的旨意行在地上,如同行在天上。 (马太福音 6:10 和合本)
your kingdom come, your will be done, on earth as it is in heaven. (Matthew 6:10 NIV)
我们日用的饮食,今日赐给我们。 (马太福音 6:11 和合本)
Give us today our daily bread. (Matthew 6:11 NIV)
免我们的债,如同我们免了人的债。 (马太福音 6:12 和合本)
And forgive us our debts, as we also have forgiven our debtors. (Matthew 6:12 NIV)
不叫我们遇见试探;救我们脱离凶恶(或译:脱离恶者) 。因为国度、权柄、荣耀,全是你的,直到永远。阿们(有古卷没有因为…阿们等字) ! (马太福音 6:13 和合本)
And lead us not into temptation, but deliver us from the evil one. ' (Matthew 6:13 NIV)

Clouds in the sky during sunset.
Photo by Tom Barrett / Unsplash

Welcome to use Magoosh coupon code: CNAMBLER

I am Ambassador of Magoosh.
http://magoosh.com/

Welcome to use my Magoosh coupon code:

CNAMBLER

You can get more discount and save your money.

GMAT

GRE

TOEFL

AT THE BETHESDA POOL IN JERUSALEM

这事以后,到了犹太人的一个节期,耶稣就上耶路撒冷去。 (约翰福音 5:1 和合本)
Some time later, Jesus went up to Jerusalem for one of the Jewish festivals. (John 5:1 NIV)
在耶路撒冷,靠近羊门有一个池子,希伯来话叫作毕士大,旁边有五个廊子; (约翰福音 5:2 和合本)
Now there is in Jerusalem near the Sheep Gate a pool, which in Aramaic is called Bethesda and which is surrounded by five covered colonnades. (John 5:2 NIV)
里面躺着瞎眼的、瘸腿的、血气枯干的许多病人。(有古卷加:等候水动;4因为有天使按时下池子搅动那水,水动之后,谁先下去,无论害什么病就痊愈了。) (约翰福音 5:3 和合本)
Here a great number of disabled people used to lie—the blind, the lame, the paralyzed.
(John 5:3 NIV)
(John 5:4 NIV)
在那里有一个人,病了三十八年。 (约翰福音 5:5 和合本)
One who was there had been an invalid for thirty-eight years. (John 5:5 NIV)
耶稣看见他躺着,知道他病了许久,就问他说:"你要痊愈吗?" (约翰福音 5:6 和合本)
When Jesus saw him lying there and learned that he had been in this condition for a long time, he asked him, "Do you want to get well?" (John 5:6 NIV)
病人回答说:"先生,水动的时候,没有人把我放在池子里;我正去的时候,就有别人比我先下去。" (约翰福音 5:7 和合本)
"Sir," the invalid replied, "I have no one to help me into the pool when the water is stirred. While I am trying to get in, someone else goes down ahead of me." (John 5:7 NIV)
耶稣对他说:"起来,拿你的褥子走吧!" (约翰福音 5:8 和合本)
Then Jesus said to him, "Get up! Pick up your mat and walk." (John 5:8 NIV)
那人立刻痊愈,就拿起褥子来走了。 (约翰福音 5:9 和合本)
At once the man was cured; he picked up his mat and walked. The day on which this took place was a Sabbath, (John 5:9 NIV)
那天是安息日,所以犹太人对那医好的人说:"今天是安息日,你拿褥子是不可的。" (约翰福音 5:10 和合本)
and so the Jewish leaders said to the man who had been healed, "It is the Sabbath; the law forbids you to carry your mat." (John 5:10 NIV)
他却回答说:"那使我痊愈的,对我说:'拿你的褥子走吧。'" (约翰福音 5:11 和合本)
But he replied, "The man who made me well said to me, 'Pick up your mat and walk.'" (John 5:11 NIV)
他们问他说:"对你说'拿褥子走'的是什么人?" (约翰福音 5:12 和合本)
So they asked him, "Who is this fellow who told you to pick it up and walk?" (John 5:12 NIV)
那医好的人不知道是谁;因为那里的人多,耶稣已经躲开了。 (约翰福音 5:13 和合本)
The man who was healed had no idea who it was, for Jesus had slipped away into the crowd that was there. (John 5:13 NIV)
后来耶稣在殿里遇见他,对他说:"你已经痊愈了,不要再犯罪,恐怕你遭遇的更加利害。" (约翰福音 5:14 和合本)
Later Jesus found him at the temple and said to him, "See, you are well again. Stop sinning or something worse may happen to you." (John 5:14 NIV)


Photo by James Donovan / Unsplash

Word Break III

Question

http://www.lintcode.com/en/problem/word-break-iii/
Give a dictionary of words and a sentence with all whitespace removed, return the number of sentences you can form by inserting whitespaces to the sentence so that each word can be found in the dictionary.

Example

Given a String CatMat
Given a dictionary ["Cat", "Mat", "Ca", "tM", "at", "C", "Dog", "og", "Do"]
return 3
we can form 3 sentences, as follows:
CatMat = Cat Mat
CatMat = Ca tM at
CatMat = C at Mat

Answer

RunTime : 288ms
class Solution {
public:
 /*
 * @param s: A string
 * @param dict: A dictionary of words dict
 * @return: A boolean
 */
 int wordBreak3(string &s, unordered_set<string> &dict) {
  // write your code here
  if (s.length() <= 0)
   return 0;
  bool found = true;
  for (auto c : s) {
   bool in = false;
   for (auto d : dict) {
    if (in)
     break;
    for (auto e : d) {
     if (e == c) {
      in = true;
      break;
     }
    }
   }
   if (!in) {
    found = false;
    break;
   }
  }
  if (!found)
   return 0;
  Trie trie;
  for (auto d : dict)
   trie.insert(d);
  result = 0;
  wordBreakHelp(s, trie, 0);
  return result;
 }
private:
 int result;
 struct TrieNode {
  TrieNode() {
   for (int i = 0; i < 256; i++) {
    next[i] = 0;
   }
   s = 0;
  }
  int s;
  TrieNode* next[256];
 };
 class Trie {
 public:
  Trie() {
   root = new TrieNode();
  }
  inline void deleteHelper(TrieNode* root) {
   if (root) {
    for (int i = 0; i < 256; i++) {
     deleteHelper(root->next[i]);
    }
    delete root;
   }
  }
  ~Trie() {
   deleteHelper(root);
   root = 0;
  }
  void insert(string& s) {
   TrieNode* iter = root;
   for (auto c : s) {
    if (iter->next[c] == 0)
     iter->next[c] = new TrieNode();
    iter = iter->next[c];
   }
   iter->s = s.length();
  }
  unordered_set<int> search(string& s, int pos) {
   TrieNode* iter = root;
   unordered_set<int> words;
   for (size_t i = pos; i < s.length(); i++) {
    char c = s[i];
    if (iter->next[c] == 0)
     break;
    if (iter->s > 0) {
     words.insert(iter->s);
    }
    iter = iter->next[c];
   }
   if (iter->s > 0) {
    words.insert(iter->s);
   }
   return words;
  }
 private:
  TrieNode* root;
 };
 inline void wordBreakHelp(string& s, Trie& trie, int pos) {
  unordered_set<int> words = trie.search(s, pos);
  if (words.size() > 0) {
   for (auto word : words) {
    if ((pos + word) == s.length()) {
     result++;
    }
    else {
     wordBreakHelp(s, trie, pos + word);
    }
   }
  }
 }
};

Word Break II

Question

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.

Example

Gieve s = lintcode,
dict = ["de", "ding", "co", "code", "lint"].
A solution is ["lint code", "lint co de"].

Answer

RunTime : 902ms
class Solution {
public:
 /*
 * @param s: A string
 * @param dict: A dictionary of words dict
 * @return: A boolean
 */
 vector<string> wordBreak(string &s, unordered_set<string> &dict) {
  // write your code here
  result.clear();
  if (s.length() <= 0)
   return result;
  bool found = true;
  for (auto c : s) {
   bool in = false;
   for (auto d : dict) {
    if (in)
     break;
    for (auto e : d) {
     if (e == c) {
      in = true;
      break;
     }
    }
   }
   if (!in) {
    found = false;
    break;
   }
  }
  if (!found)
   return result;
  Trie trie;
  for (auto d : dict)
   trie.insert(d);
  string bw;
  wordBreakHelp(s, trie, 0, bw);
  return result;
 }
private:
 vector<string> result;
 struct TrieNode {
  TrieNode() {
   for (int i = 0; i < 26; i++) {
    next[i] = 0;
   }
   s = 0;
  }
  int s;
  TrieNode* next[26];
 };
 class Trie {
 public:
  Trie() {
   root = new TrieNode();
  }
  inline void deleteHelper(TrieNode* root) {
   if (root) {
    for (int i = 0; i < 26; i++) {
     deleteHelper(root->next[i]);
    }
    delete root;
   }
  }
  ~Trie() {
   deleteHelper(root);
   root = 0;
  }
  void insert(string& s) {
   TrieNode* iter = root;
   for (auto c : s) {
    if (iter->next[c - 'a'] == 0)
     iter->next[c - 'a'] = new TrieNode();
    iter = iter->next[c - 'a'];
   }
   iter->s = s.length();
  }
  unordered_set<int> search(string& s, int pos) {
   TrieNode* iter = root;
   unordered_set<int> words;
   for (size_t i = pos; i < s.length(); i++) {
    char c = s[i];
    if (iter->next[c - 'a'] == 0)
     break;
    if (iter->s > 0) {
     words.insert(iter->s);
    }
    iter = iter->next[c - 'a'];
   }
   if (iter->s > 0) {
    words.insert(iter->s);
   }
   return words;
  }
 private:
  TrieNode* root;
 };
 inline void wordBreakHelp(string& s, Trie& trie, int pos, string& bw) {
  unordered_set<int> words = trie.search(s, pos);
  if (words.size() > 0) {
   for (auto word : words) {
    string bwd = bw;
    if (bwd.empty())
     bwd = s.substr(pos, word);
    else {
     bwd.append(" ");
     bwd.append(s.substr(pos, word));
    }
    if ((pos + word) == s.length()) {
     result.push_back(bwd);
    }
    else {
     wordBreakHelp(s, trie, pos + word, bwd);
    }
   }
  }
 }
};

Word Break

Question

http://www.lintcode.com/en/problem/word-break/
Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.

Example

Given s = "lintcode", dict = ["lint", "code"].
Return true because "lintcode" can be break as "lint code".

Answer

Run Time : 582ms 
class Solution {
public:
 /*
 * @param s: A string
 * @param dict: A dictionary of words dict
 * @return: A boolean
 */

 bool wordBreak(string &s, unordered_set<string> &dict) {
  // write your code here
  if (dict.size() <= 0) {
   if (s.length() <= 0)
    return true;
   return false;
  }
  Trie trie;
  for (auto d : dict)
   trie.insert(d);
  return wordBreakHelp(s, trie, 0);
 }
private:
 struct TrieNode {
  TrieNode() {
   for (int i = 0; i < 26; i++) {
    next[i] = 0;    
   }
   s = 0;
  }
  int s;
  TrieNode* next[26];
 };
 class Trie {
 public:
  Trie() {
   root = new TrieNode();
  }
  inline void deleteHelper(TrieNode* root) {
   if (root) {
    for (int i = 0; i < 26; i++) {
     deleteHelper(root->next[i]);
    }
    delete root;
   }
  }
  ~Trie() {
   deleteHelper(root);
   root = 0;
  }
  void insert(string& s) {
   TrieNode* iter = root;
   for (auto c : s) {
    if (iter->next[c - 'a'] == 0)
     iter->next[c - 'a'] = new TrieNode();
    iter = iter->next[c - 'a'];
   }
   iter->s = s.length();
  }
  unordered_set<int> search(string& s, int pos) {
   TrieNode* iter = root;
   unordered_set<int> words;
   for (int i = pos; i < s.length(); i++) {
    char c = s[i];
    if (iter->next[c - 'a'] == 0)
     break;
    if (iter->s > 0) {
     words.insert(iter->s);
    }
    iter = iter->next[c - 'a'];
   }
   if (iter->s > 0) {
    words.insert(iter->s);
   }
   return words;
  }
 private:
  TrieNode* root;
 };
 inline bool wordBreakHelp(string& s, Trie& trie, int pos) {
  unordered_set<int> words = trie.search(s, pos);
  if (s.length() > 0 && words.size() > 0) {
   for (auto word : words) {
    if ((pos + word) == s.length())
     return true;    
    if (wordBreakHelp(s, trie, pos+word))
     return true;
   }
  }
  return false;
 }
}; 

Lord's will

其实明天如何,你们还不知道。你们的生命是什么呢?你们原来是一片云雾,出现少时就不见了。 (雅各书 4:14 和合本)
Why, you do not even know what will happen tomorrow. What is your life? You are a mist that appears for a little while and then vanishes. (James 4:14 NIV)
你们只当说:"主若愿意,我们就可以活着,也可以做这事,或做那事。" (雅各书 4:15 和合本)
Instead, you ought to say, "If it is the Lord's will, we will live and do this or that." (James 4:15 NIV)


Photo by James Chou / Unsplash

Unique Paths III

Question

http://www.lintcode.com/en/problem/unique-paths-iii/
Follow up for "Unique Paths II": https://acm.errong.win/uniquepathsii/
Now each grid contains a value, so each path also has a value. Find the sum of all the unique values paths.

Example

For example,
[
[1,1,2],
[1,2,3],
[3,2,4]
]
There are 2 unique value path:
[1,1,2,3,4] = 11
[1,1,2,2,4] = 10
return 21

Answer

class Solution {
public:
 /*
 * @param : an array of arrays
 * @return: the sum of all unique weighted paths
 */
 int uniqueWeightedPaths(vector<vector<int>> &obstacleGrid) {
  int m = obstacleGrid.size();
  if (m <= 0)
   return 0;
  int n = obstacleGrid[0].size();
  if (n <= 0)
   return 0;
  struct Up {
   int step;
   int sum;
   Up(int st, int su) : step(st), sum(su) {}
  };
  map<int, vector<Up>> sum_paths;
  sum_paths[0] = vector<Up>();
  sum_paths[0].push_back(Up(0, obstacleGrid[0][0]));
  for (int i = 1; i < m + n - 1; i++) {
   map<int, vector<Up>> new_sum_paths;
   for (auto sp : sum_paths) {
    int pos = sp.first;
    int x = pos / n;
    int y = pos % n;
    int nx = x + 1;
    int ny = y;    
    if (nx < m) {
     int npos = nx * n + ny;
     for (auto up : sp.second) {
      if (up.step < i) {
       Up nup = up;
       nup.sum += obstacleGrid[nx][ny];
       nup.step += 1;
       bool found = false;
       if (!new_sum_paths.count(npos)) {
        new_sum_paths[npos] = vector<Up>();
       }
       for (auto eup : new_sum_paths[npos]) {
        if (eup.sum == nup.sum) {
         found = true;
         break;
        }
       }
       if (!found)
        new_sum_paths[npos].push_back(nup);
      }
     }
    }
    nx = x;
    ny = y + 1;
    if (ny < n) {
     int npos = nx * n + ny;
     for (auto up : sp.second) {
      if (up.step < i) {
       Up nup = up;
       nup.sum += obstacleGrid[nx][ny];
       nup.step += 1;
       bool found = false;
       if (!new_sum_paths.count(npos)) {
        new_sum_paths[npos] = vector<Up>();
       }
       for (auto eup : new_sum_paths[npos]) {
        if (eup.sum == nup.sum) {
         found = true;
         break;
        }
       }
       if (!found)
        new_sum_paths[npos].push_back(nup);
      }
     }
    }
   }
   sum_paths = new_sum_paths;
  }
   int sum = 0;
  int pos = m*n - 1;
  for (auto sp : sum_paths[pos]) {
   sum += sp.sum;
  }
  return sum;
 }
};

JESUS THE SOUL WINNER

在那里有雅各井;耶稣因走路困乏,就坐在井旁。那时约有午正。 (约翰福音 4:6 和合本)
Jacob's well was there, and Jesus, tired as he was from the journey, sat down by the well. It was about noon. (John 4:6 NIV)
有一个撒玛利亚的妇人来打水。耶稣对她说:"请你给我水喝。"( (约翰福音 4:7 和合本)
When a Samaritan woman came to draw water, Jesus said to her, "Will you give me a drink?" (John 4:7 NIV)
那时门徒进城买食物去了。) (约翰福音 4:8 和合本)
(His disciples had gone into the town to buy food.) (John 4:8 NIV)
撒玛利亚的妇人对他说:"你既是犹太人,怎么向我一个撒玛利亚妇人要水喝呢?"原来犹太人和撒玛利亚人没有来往。 (约翰福音 4:9 和合本)
The Samaritan woman said to him, "You are a Jew and I am a Samaritan woman. How can you ask me for a drink?" (For Jews do not associate with Samaritans. ) (John 4:9 NIV)
耶稣回答说:"你若知道 神的恩赐,和对你说'给我水喝'的是谁,你必早求他,他也必早给了你活水。" (约翰福音 4:10 和合本)
Jesus answered her, "If you knew the gift of God and who it is that asks you for a drink, you would have asked him and he would have given you living water." (John 4:10 NIV)


Photo by Gerrie van der Walt / Unsplash

Unique Paths II

Question

http://www.lintcode.com/en/problem/unique-paths-ii/
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.

Example

For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.

Answer

class Solution {
public:
    /*
     * @param obstacleGrid: A list of lists of integers
     * @return: An integer
     */
    int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
        int m = obstacleGrid.size();
        if (m <= 0)
            return 0;
        int n = obstacleGrid[0].size();
        if (obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)
            return 0;
        vector<vector<int>> res(m, vector<int>(n, 0));
        res[0][0] = 1;
        for (int j = 1; j < n; j++) {
             if (obstacleGrid[0][j] == 1) {
                 for (int i = j; i < n; i++)
                      res[0][i] = 0;
                 break;
             } else
                 res[0][j] = 1;
        }
        for (int j = 1; j < m; j++) {
             if (obstacleGrid[j][0] == 1) {
                 for (int i = j; i < m; i++)
                      res[i][0] = 0;
                 break;
             } else {
                 res[j][0] = 1;
             }
        }
        for (int i = 1; i < m; i++) {
             for (int j = 1; j < n; j++) {
                 if (obstacleGrid[i][j] == 1)
                     res[i][j] = 0;
                 else
                     res[i][j] = res[i-1][j] + res[i][j-1];
             }
        }
        return res[m-1][n-1];
    }
};

Unique Paths

Question

http://www.lintcode.com/en/problem/unique-paths/
A robot is located at the top-left corner of a m x n grid.
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?

Example

Given m = 3 and n = 3, return 6.
Given m = 4 and n = 5, return 35.
Given m = 6 end = 63, return 9657648

Answer

// brute force solution, Time Limit Exceeded
// help us get dp formula pattern
// res[i][j] = res[i-1][j] + res[i][j-1];
public int uniquePaths(int m, int n) {
    return helper(1, 1, m, n);
}
private int helper(int row, int col, int m, int n)
{
    if(row == m && col == n)
        return 1;  
    if( row > m || col > n)
        return 0;
    return helper(row+1, col, m, n) + helper(row, col+1, m, n);
}

// dp solution
class Solution {
public:
    /*
     * @param m: positive integer (1 <= m <= 100)
     * @param n: positive integer (1 <= n <= 100)
     * @return: An integer
     */
    int uniquePaths(int m, int n) {
        // write your code here
        if (m <= 0 || n <= 0)
            return 0;
        vector<int> res(n);
        res[0] = 1;
        for (int i = 0; i < m; i++) {
             for (int j = 1; j < n; j++) {
                  res[j] += res[j-1];
             }
        }
        return res[n-1];
    }
};

Next Sparse Number

Question

http://www.lintcode.com/en/problem/next-sparse-number/
A number is Sparse if there are no two adjacent 1s in its binary representation. Given a number n, find the smallest Sparse number which greater than or equal to n.
eg. 5 (binary representation: 101) is sparse, but 6 (binary representation: 110) is not sparse.

Example

Given n = 6, return 8
Next Sparse Number is 8

Given n = 4, return 4
Next Sparse Number is 4

Given n = 38, return 40
Next Sparse Number is 40

Given n = 44, return 64
Next Sparse Number is 64

Given n = 341381939, return 343932928
Next Sparse Number is 343932928

Answer

class Solution {
public:
    /*
     * @param : a number
     * @return: return the next sparse number behind x
     */
    int nextSparseNum(int x) {
        // write your code here
        if (x == 0 || x == 1) return x;
        string binary;
        int n = x;
        while (n) {
            if (n&1)
                binary.append("1");
            else
                binary.append("0");
            n >>= 1;
        }
        for (int i = 1; i < binary.length(); i++) {
            if (binary[i] == '1' && binary[i-1] == '1') {
                // plus 1 from i-1
                int c = 1;
                int j = i-1;
                while (c == 1 && j < binary.length()) {
                    int t = binary[j] - '0' + c;
                    if (t < 2) {
                        c = 0;
                        binary[j] = t + '0';
                    } else {
                        c = 1;
                        binary[j] = '0';
                    }
                    j++;
                }
                if (c == 1)
                    binary.append("1");
            }
        }
        int result = 0;
        for (int i = 0; i < binary.length() - 1; i++) {
            if (binary[i] == '1') {
                string nb = binary;
                nb[i] = '0';
                int nx = bintoint(nb);
                if (nx >= x) {
                    binary[i] = '0';
                    if (result == 0)
                        result = nx;
                    else if (result > nx)
                        result = nx;
                }
            }
        }
        if (result == 0)
            result = bintoint(binary);
        return result;
    }
    inline int bintoint(string& binary) {
       int result = 0;
       for (int i = binary.length(); i > 0; i--)
            result += (binary[i-1] - '0') << (i-1);
       return result;
    }
};

How to verify your ownership of the web server powered by Ghost via Search Console

Since I want to do Verify my ownership of http://www.errong.win/ via Search Console.

Search Console Verify Ownership

I tried to upload the file google9aedadfa5be8a815.html under my site's working directory where I installed via ghost instal command.
but only get 404 error while visiting http://www.errong.win/google9aedadfa5be8a815.html

Solution

Thanks to Nistor Cristian, kevin, vikas.potluri, they replied my thread quickly in ghost.slack.org and I got the issue fixed.

Nistor Cristian
simply include it in your theme and should work
kevin
@Errong add the file to the root of your theme
vikas.potluri
If you're not sure which theme to use, go to the ghost admin panel, download the current theme, drop in your google verification and upload it back to the admin interface

For my case:
I use the default casper theme, its path is :
blog/content/themes/casper/
I moved google9aedadfa5be8a815.html there and then it works.
You do not even need to restart your ghost(ghost restart).

You can use below command to check it.
curl https://www.errong.win/google9aedadfa5be8a815.html
google-site-verification: google9aedadfa5be8a815.html

CHRIST’S DEATH MEANS OUR LIFE

有一个法利赛人,名叫尼哥底母,是犹太人的官。 (约翰福音 3:1 和合本)
Now there was a Pharisee, a man named Nicodemus who was a member of the Jewish ruling council. (John 3:1 NIV)
这人夜里来见耶稣,说:"拉比,我们知道你是由 神那里来作师傅的;因为你所行的神迹,若没有 神同在,无人能行。" (约翰福音 3:2 和合本)
He came to Jesus at night and said, "Rabbi, we know that you are a teacher who has come from God. For no one could perform the signs you are doing if God were not with him." (John 3:2 NIV)
耶稣回答说:"我实实在在地告诉你,人若不重生,就不能见 神的国。" (约翰福音 3:3 和合本)
Jesus replied, "Very truly I tell you, no one can see the kingdom of God unless they are born again. " (John 3:3 NIV)
尼哥底母说:"人已经老了,如何能重生呢?岂能再进母腹生出来吗?" (约翰福音 3:4 和合本)
"How can someone be born when they are old?" Nicodemus asked. "Surely they cannot enter a second time into their mother's womb to be born!" (John 3:4 NIV)
耶稣说:"我实实在在地告诉你,人若不是从水和圣灵生的,就不能进 神的国。 (约翰福音 3:5 和合本)
Jesus answered, "Very truly I tell you, no one can enter the kingdom of God unless they are born of water and the Spirit. (John 3:5 NIV)
从肉身生的就是肉身;从灵生的就是灵。 (约翰福音 3:6 和合本)
Flesh gives birth to flesh, but the Spirit gives birth to spirit. (John 3:6 NIV)
我说:'你们必须重生',你不要以为希奇。 (约翰福音 3:7 和合本)
You should not be surprised at my saying, 'You must be born again.' (John 3:7 NIV)
风随着意思吹,你听见风的响声,却不晓得从哪里来,往哪里去;凡从圣灵生的,也是如此。" (约翰福音 3:8 和合本)
The wind blows wherever it pleases. You hear its sound, but you cannot tell where it comes from or where it is going. So it is with everyone born of the Spirit." (John 3:8 NIV)
尼哥底母问他说:"怎能有这事呢?" (约翰福音 3:9 和合本)
"How can this be?" Nicodemus asked. (John 3:9 NIV)
耶稣回答说:"你是以色列人的先生,还不明白这事吗? (约翰福音 3:10 和合本)
"You are Israel's teacher,"said Jesus, "and do you not understand these things? (John 3:10 NIV)
我实实在在地告诉你,我们所说的是我们知道的;我们所见证的是我们见过的;你们却不领受我们的见证。 (约翰福音 3:11 和合本)
Very truly I tell you, we speak of what we know, and we testify to what we have seen, but still you people do not accept our testimony. (John 3:11 NIV)
我对你们说地上的事,你们尚且不信,若说天上的事,如何能信呢? (约翰福音 3:12 和合本)
I have spoken to you of earthly things and you do not believe; how then will you believe if I speak of heavenly things? (John 3:12 NIV)
除了从天降下、仍旧在天的人子,没有人升过天。 (约翰福音 3:13 和合本)
No one has ever gone into heaven except the one who came from heaven—the Son of Man. (John 3:13 NIV)
摩西在旷野怎样举蛇,人子也必照样被举起来, (约翰福音 3:14 和合本)
Just as Moses lifted up the snake in the wilderness, so the Son of Man must be lifted up, (John 3:14 NIV)
叫一切信他的都得永生(或译:叫一切信的人在他里面得永生) 。 (约翰福音 3:15 和合本)
that everyone who believes may have eternal life in him." (John 3:15 NIV)
" 神爱世人,甚至将他的独生子赐给他们,叫一切信他的,不至灭亡,反得永生。 (约翰福音 3:16 和合本)
For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life. (John 3:16 NIV)


Photo by diego / Unsplash

Maximum Subarray VI

Question

Given an array of integers. find the maximum XOR subarray value in given array.
What's the XOR: https://en.wikipedia.org/wiki/Exclusive_or

Notice

Expected time complexity O(n).

Answer

https://threads-iiith.quora.com/Tutorial-on-Trie-and-example-problems
Let's say F(L,R) is XOR of subarray from L to R.
Here we use the property that F(L,R)=F(1,R) XOR F(1,L-1). How?
Let's say our subarray with maximum XOR ended at position i. Now, we need to maximise F(L,i) ie. F(1,i) XOR F(1,L-1) where L<=i. Suppose, we inserted F(1,L-1) in our trie for all L<=i, then it's just problem1.

class Solution {
public:
    /*
     * @param : the array
     * @return: the max xor sum of the subarray in a given array
     */    
    int maxXorSubarray(vector<int> &nums) {
        // write code here
        int ans = INT_MIN;
        int pre = 0;
        Trie trie;
        for (auto n : nums) {
            pre = pre ^ n;
            trie.insert(pre);
            ans = max(ans, trie.query(pre));
        }
        return ans;
    }
private:    
    class Trie {
    public:
        Trie() {
            root = new TrieNode(0);
            INTBITS = sizeof(int) * 8;
        }
        void insert(int x) {
            TrieNode* iter = root;
            for (int i = INTBITS - 1; i >= 0; i--) {
                bool v = x & (1 << i);
                if (iter->arr[v] == 0)
                    iter->arr[v] = new TrieNode(0);
                iter = iter->arr[v];
            }
            iter->val = x;
        }
        int query(int x) {
            TrieNode* iter = root;
            for (int i = INTBITS - 1; i >= 0; i--) {
                bool v = x & (1 << i);
                if (iter->arr[1-v] != 0)
                    iter = iter->arr[1-v];
                else if (iter->arr[v] != 0)
                    iter = iter->arr[v];
            }
            return x ^ iter->val;
        }
    private:
        class TrieNode {
        public:
            int val;
            TrieNode *arr[2];
            TrieNode(int v)
                : val(v) {
                arr[0] = arr[1] = 0;
            }
        };
        TrieNode* root;
        int INTBITS;
    };    
};

Maximum Subarray III

Question:

http://www.lintcode.com/en/problem/maximum-subarray-iii/
Given an array of integers and a number k, find k non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.

Answer

localMax[i][j], means the maximum sum we can get while select j subarrays 
from first i elements, including element i 
globalMax[i][j], means the maximum sum we can get while select j subarrays 
from first i elements, may not including element i 
// state transfer 
localMax[i][j] = max(localMax[i - 1][j] + nums[i - 1], globalMax[i - 1][j - 1] + nums[i - 1]) 
globalMax[i][j] = max(globalMax[i - 1][j], localMax[i][j]) 
 
 
class Solution {
public:
    /*
     * @param nums: A list of integers
     * @param k: An integer denote to find k non-overlapping subarrays
     * @return: An integer denote the sum of max k non-overlapping subarrays
     */
    int maxSubArray(vector<int> &nums, int k) {
        // write your code here
        int n = nums.size();
        if (n == 0 || k > n)
            return 0;
        // Use INT_MIN might cause numeric overflow 
        vector<vector<int>> localMax(n+1, vector<int>(k+1, INT_MIN/2));
        vector<vector<int>> globalMax(n+1, vector<int>(k+1, INT_MIN/2));

        localMax[0][0] = globalMax[0][0] = 0;

        for (int i = 1; i <= n; i++) {
             localMax[i][0] = 0;
             globalMax[i][0] = 0;
             for (int j = 1; j <= k; j++) {
                  localMax[i][j] = max(localMax[i-1][j] + nums[i-1], 
                                       globalMax[i-1][j-1] + nums[i-1]);
                  globalMax[i][j] = max(globalMax[i-1][j], localMax[i][j]);
             }
        }
        return globalMax[n][k];
    }
};

Maximum Subarray II

Question

Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.

Notice

The subarray should contain at least one number

Answer

class Solution {
public:
    /*
     * @param nums: A list of integers
     * @return: An integer denotes the sum of max two non-overlapping subarrays
     */
    int maxTwoSubArrays(vector<int> &nums) {
        // write your code here
        int len = nums.size();
        vector<int> suml(len);
        int cur_max = nums[0];
        int max = cur_max;
        suml[0] = max;
        for (int i = 1; i < len; i++) {
            if (cur_max <= 0) {
                cur_max = nums[i];
            } else {
                cur_max += nums[i];
            }
            if (max < cur_max)
                max = cur_max;
            suml[i] = max;
        }
        vector<int> sumr(len);
        cur_max = nums[len-1];
        max = cur_max;
        sumr[len-1] = max;
        for (int i = len - 2; i >= 0; i--) {
             if (cur_max <= 0) {
                 cur_max = nums[i];
             } else {
                 cur_max += nums[i];
             }
             if (max < cur_max)
                 max = cur_max;
             sumr[i] = max;
        }
        int result = suml[0] + sumr[1];
        for (int i = 1; i < len - 1; i++) {
             int temp = suml[i] + sumr[i+1];
             if (result < temp)
                 result = temp;
        }
        return result;
    }
};

Look at the new growth in the valley

那向外观看、如晨光发现、美丽如月亮、皎洁如日头、威武如展开旌旗军队的是谁呢? (雅歌 6:10 和合本)
Who is this that appears like the dawn, fair as the moon, bright as the sun, majestic as the stars in procession? He (Song of Songs 6:10 NIV)
我下入核桃园,要看谷中青绿的植物,要看葡萄发芽没有,石榴开花没有。 (雅歌 6:11 和合本)
I went down to the grove of nut trees to look at the new growth in the valley, to see if the vines had budded or the pomegranates were in bloom. (Song of Songs 6:11 NIV)
不知不觉,我的心将我安置在我尊长的车中。〔耶路撒冷的众女子〕 (雅歌 6:12 和合本)
Before I realized it, my desire set me among the royal chariots of my people. Friends (Song of Songs 6:12 NIV)

Green Plants
Photo by 贝莉儿 NG / Unsplash

Candy

Question:

http://www.lintcode.com/en/problem/candy/
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:

Each child must have at least one candy. 
Children with a higher rating get more candies than their neighbors. 
 
What is the minimum candies you must give?

Answer:

class Solution {
public:
    /*
     * @param ratings: Children's ratings
     * @return: the minimum candies you must give
     */
    int candy(vector<int> &ratings) {
        // write your code here
        vector<int> candys(ratings.size(), 1);
        for (int i = 0; i < ratings.size() - 1; i++) {
            if (ratings[i+1] > ratings[i])
                candys[i+1] = candys[i] + 1;
        }
        for (int i = ratings.size() - 1; i > 0; i--) {
            if (ratings[i-1] > ratings[i])
                candys[i-1] = max(candys[i] + 1, candys[i-1]);
        }
        int count = 0;
        for (auto i : candys)
            count += i;
        return count;
    }
};

Course Schedule III

Question:

http://www.lintcode.com/en/problem/course-schedule-iii/
There are ·n· different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.
Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.

Notice

The integer 1 <= d, t, n <= 10,000. You can't take two courses simultaneously. 

Example

Given [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
return 3
There're totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day.
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day.
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.

Answer:

class Solution {
public:
    /*
     * @param : duration and close day of each course
     * @return: the maximal number of courses that can be taken
     */
    int scheduleCourse(vector<vector<int>> &courses) {
        // write your code here
        int curTime = 0;
        priority_queue<int> q;
        sort(courses.begin(), courses.end(), [](vector<int>& a, vector<int>& b) {return a[1] < b[1];});
        for (auto course : courses) {
            curTime += course[0];
            q.push(course[0]);
            if (curTime > course[1]) {
                curTime -= q.top(); q.pop();
            }
        }
        return q.size();
    }
};

Course Schedule II

Question:

http://www.lintcode.com/en/problem/course-schedule-ii/
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example

Given n = 2, prerequisites = [[1,0]]
Return [0,1]
Given n = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Return [0,1,2,3] or [0,2,1,3]

Answer:

class Solution {
public:
    /*
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: the course order
     */
    vector<int> findOrder(int numCourses, vector<pair<int, int>> &prerequisites) {
        // write your code here
        vector<vector<int>> adj(numCourses);
        vector<int> indegree(numCourses);
        for (int i = 0; i < numCourses; i++)
             indegree[i] = 0;
        for (auto pq : prerequisites) {
            adj[pq.second].push_back(pq.first);
            indegree[pq.first]++;
        }
        stack<int> st;
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] == 0)
                st.push(i);
        }
        int count = 0;
        vector<int> result;
        while (!st.empty()) {
            int v1 = st.top();
            st.pop();
            count++;
            result.push_back(v1);
            for (auto v2 : adj[v1]) {
                indegree[v2]--;
                if (indegree[v2] == 0)
                    st.push(v2);
            }
        }
        if (count != numCourses) {
            return vector<int>();
        }
        return result;
    }
};

Topological Sorting

Question:

http://www.lintcode.com/en/problem/topological-sorting/
Given an directed graph, a topological order of the graph nodes is defined as follow:
For each directed edge A -> B in graph, A must before B in the order list.
The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph.

Answer:
class Solution {
public:
    /*
     * @param ratings: Children's ratings
     * @return: the minimum candies you must give
     */
    int candy(vector<int> &ratings) {
        // write your code here
        vector<int> candys(ratings.size(), 1);
        for (int i = 0; i < ratings.size() - 1; i++) {
            if (ratings[i+1] > ratings[i])
                candys[i+1] = candys[i] + 1;
        }
        for (int i = ratings.size() - 1; i > 0; i--) {
            if (ratings[i-1] > ratings[i])
                candys[i-1] = max(candys[i] + 1, candys[i-1]);
        }
        int count = 0;
        for (auto i : candys)
            count += i;
        return count;
    }
};

Course Schedule

Question:

http://www.lintcode.com/en/problem/course-schedule/
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Answer:

class Solution {
public:
    /*
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: true if can finish all courses or false
     */
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        // Write your code here
        vector<vector<int>> adj(numCourses);
        vector<int> indegree(numCourses);
        for (int i = 0; i < numCourses; i++)
             indegree[i] = 0;
        for (auto pq : prerequisites) {
            adj[pq.first].push_back(pq.second);
            indegree[pq.second]++;
        }
        stack<int> st;
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] == 0)
                st.push(i);
        }
        int count = 0;
        while (!st.empty()) {
            int v1 = st.top();
            st.pop();
            count++;
            for (auto v2 : adj[v1]) {
                indegree[v2]--;
                if (indegree[v2] == 0)
                    st.push(v2);
            }
        }
        return count == numCourses;
    }
}

How to be Jesus's disciples

我是葡萄树,你们是枝子。常在我里面的,我也常在他里面,这人就多结果子;因为离了我,你们就不能作什么。 (约翰福音 15:5 和合本)
"I am the vine; you are the branches. If you remain in me and I in you, you will bear much fruit; apart from me you can do nothing. (John 15:5 NIV)
人若不常在我里面,就像枝子丢在外面枯干,人拾起来,扔在火里烧了。 (约翰福音 15:6 和合本)
If you do not remain in me, you are like a branch that is thrown away and withers; such branches are picked up, thrown into the fire and burned. (John 15:6 NIV)
你们若常在我里面,我的话也常在你们里面,凡你们所愿意的,祈求,就给你们成就。 (约翰福音 15:7 和合本)
If you remain in me and my words remain in you, ask whatever you wish, and it will be done for you. (John 15:7 NIV)
你们多结果子,我父就因此得荣耀,你们也就是我的门徒了。 (约翰福音 15:8 和合本)
This is to my Father's glory, that you bear much fruit, showing yourselves to be my disciples. (John 15:8 NIV)

A close-up of bunches of purple grapes on the vine
Photo by Bill Williams / Unsplash

Wildcard Matching

Question:
http://www.lintcode.com/en/problem/wildcard-matching/
Implement wildcard pattern matching with support for '?' and '*'.

    '?' Matches any single character. 
    '*' Matches any sequence of characters (including the empty sequence). 
 
The matching should cover the entire input string (not partial).


Answer:
 
class Solution {
public:
    /*
     * @param s: A string 
     * @param p: A string includes "?" and "*"
     * @return: is Match?
     */
    bool isMatch(string &s, string &p) {
        if (p.empty())
            return false;
        int n = s.length();
        int m = p.length();
        bool f[n + 1][m + 1];
        memset(f, false, sizeof(f));
        f[0][0] = true;
        for (int i = 1; i <= n; i++)
            f[i][0] = false;
        for (int i = 1; i <= m; i++)
            f[0][i] = f[0][i - 1] && p[i - 1] == '*';
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (p[j - 1] == '*') {
                    f[i][j] = f[i - 1][j] || f[i][j - 1];
                } else if (p[j - 1] == '?') {
                    f[i][j] = f[i - 1][j - 1];
                } else {
                    f[i][j] = f[i - 1][j - 1] && (s[i - 1] == p[j - 1]);
                }
            }
        } 
        return f[n][m];
    }
}; 

Maximum Gap

Question:
http://www.lintcode.com/en/problem/maximum-gap/
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Sort is easy but will cost O(nlogn) time. Try to solve it in linear time and space.
Answer:
class Solution {  
public:  
    int maximumGap(vector<int> &num) {  
       if (num.size() < 2) return 0;  
        int maxNum = num[0];  
        int minNum = num[0];  
        for (int x : num) {  
            maxNum = max(maxNum, x);  
            minNum = min(minNum, x);  
        }  
        int len = (maxNum - minNum) / num.size() + 1;  
        vector<vector<int>> buckets((maxNum - minNum) / len + 1);  
        for (int x : num) {  
            int i = (x - minNum) / len;  
            if (buckets[i].empty()) {  
                buckets[i].reserve(2);  
                buckets[i].push_back(x);  
                buckets[i].push_back(x);  
            } else {  
                if (x < buckets[i][0]) buckets[i][0] = x;  
                if (x > buckets[i][1]) buckets[i][1] = x;  
            }  
        }  
        int gap = 0;  
        int prev = 0;  
        for (int i = 1; i < buckets.size(); i++) {  
            if (buckets[i].empty()) continue;  
            gap = max(gap, buckets[i][0] - buckets[prev][1]);  
            prev = i;  
        }  
        return gap;  
    }  
};

HOW CHRIST MET A REAL NEED

第三日,在加利利的迦拿有娶亲的筵席,耶稣的母亲在那里。 (约翰福音 2:1 和合本)
On the third day a wedding took place at Cana in Galilee. Jesus' mother was there, (John 2:1 NIV)
耶稣和他的门徒也被请去赴席。 (约翰福音 2:2 和合本)
and Jesus and his disciples had also been invited to the wedding. (John 2:2 NIV)
酒用尽了,耶稣的母亲对他说:"他们没有酒了。" (约翰福音 2:3 和合本)
When the wine was gone, Jesus' mother said to him, "They have no more wine." (John 2:3 NIV)
耶稣说:"母亲(原文是妇人) ,我与你有什么相干?我的时候还没有到。" (约翰福音 2:4 和合本)
"Woman, why do you involve me?"Jesus replied. "My hour has not yet come." (John 2:4 NIV)
他母亲对用人说:"他告诉你们什么,你们就做什么。" (约翰福音 2:5 和合本)
His mother said to the servants, "Do whatever he tells you." (John 2:5 NIV)
照犹太人洁净的规矩,有六口石缸摆在那里,每口可以盛两三桶水。 (约翰福音 2:6 和合本)
Nearby stood six stone water jars, the kind used by the Jews for ceremonial washing, each holding from twenty to thirty gallons. (John 2:6 NIV)
耶稣对用人说:"把缸倒满了水。"他们就倒满了,直到缸口。 (约翰福音 2:7 和合本)
Jesus said to the servants, "Fill the jars with water"; so they filled them to the brim. (John 2:7 NIV)
耶稣又说:"现在可以舀出来,送给管筵席的。"他们就送了去。 (约翰福音 2:8 和合本)
Then he told them, "Now draw some out and take it to the master of the banquet."They did so, (John 2:8 NIV)
管筵席的尝了那水变的酒,并不知道是哪里来的,只有舀水的用人知道。管筵席的便叫新郎来, (约翰福音 2:9 和合本)
and the master of the banquet tasted the water that had been turned into wine. He did not realize where it had come from, though the servants who had drawn the water knew. Then he called the bridegroom aside (John 2:9 NIV)
对他说:"人都是先摆上好酒,等客喝足了,才摆上次的,你倒把好酒留到如今!" (约翰福音 2:10 和合本)
and said, "Everyone brings out the choice wine first and then the cheaper wine after the guests have had too much to drink; but you have saved the best till now." (John 2:10 NIV)
这是耶稣所行的头一件神迹,是在加利利的迦拿行的,显出他的荣耀来;他的门徒就信他了。 (约翰福音 2:11 和合本)
What Jesus did here in Cana of Galilee was the first of the signs through which he revealed his glory; and his disciples believed in him. (John 2:11 NIV)

Macro view of a wine glass containing alcoholic wine with a bunch of grapes
Photo by Roberta Sorge / Unsplash

The LORD is great

愿一切寻求你的,因你高兴欢喜;愿那些喜爱你救恩的,常说:当尊 神为大! (诗篇 70:4 和合本)
But may all who seek you rejoice and be glad in you; may those who long for your saving help always say, "The Lord is great!" (Psalms 70:4 NIV)
但我是困苦穷乏的; 神啊,求你速速到我这里来!你是帮助我的,搭救我的。耶和华啊,求你不要耽延! (诗篇 70:5 和合本)
But as for me, I am poor and needy; come quickly to me, O God. You are my help and my deliverer; Lord , do not delay. (Psalms 70:5 NIV)


Photo by Justin Kauffman / Unsplash

Recommend text editor : Sublime Text

A sophisticated text editor for code, markup and prose