2019年12月19日 星期四

JAVA處理Race Condition


JAVA處理Race Condition
在JAVA中,如果我們建了一個物件給Multiple Threads用,很容易在該物件內發生Race Condition,這時我們需要用JAVA提供的Synchronized機制。
如果是物件的方法的話,可以將Synchronized加在如下的位置:
public synchronized int putAndGetData(int index) { //program }

如果是要針對某個Variable作Synchronized的話,加入如下的程式:
//Class variable area private final Object lock = new Object(); public void myMethod(void){ //..... synchronized (lock) { //put or get variable } //..... }

上述方法就能避免Race Condition,其它還有別的方式,用到在寫囉~

Messenger Webview回傳資料


本篇介紹如何用Webview給使用者填表單,並回傳資料到Server。 Facebook messenger的主訊息區塊功能是有限的,當你想呈現複雜的功能,就必需借助Webview,開啟自訂網頁來當介面用,同時Facebook提供你SDK,讓你可以更好的控制Webview這個模組。

加入白名單

1. 若要在Webview開啟的網頁,使用一些Facebook提供的進階功能(例 程式關Webview),要先將你的DOMAIN加入白名單。以下範例用windows版的CURL傳JSON指令給Facebook。
D:\curl\bin\curl -H "Content-Type: application/json" -d "{ \"whitelisted_domains\":[ \"https://\" ]}" https://graph.facebook.com/v2.6/me/messenger_profile?access_token=


URL button

2. 傳送訊息給使用者,產生URL按鈕,準備開啟Webview。
{ "recipient":{ "id":"" }, "message":{ "attachment":{ "type":"template", "payload":{ "template_type":"button", "text":"Try the URL button!", "buttons":[ { "type":"web_url", "url":"https:///option.html", "title":"URL Button", "messenger_extensions": "true", "webview_height_ratio": "compact" } ] } } } }



option.html

3. Webview會開啟的網頁,已加入Facebook的專用Javascript程式碼,最前面白名單若沒加入,這些功能就不會啟動。這個網頁會讓使用者填表單。
<html> <head> <meta http-equiv="Cache-Control" content="no-cache, no-store, max-age=0, must-revalidate"> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="expires" content="0" /> <title>Choose your preferences4</title> </head> <body> <script> (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/messenger.Extensions.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'Messenger')); window.extAsyncInit = () => { MessengerExtensions.getContext('', function success(thread_context) { // success document.getElementById("psid").value = thread_context.psid; document.getElementById("showmsg").value = "success"; }, function error(err) { // error document.getElementById("showmsg").value = "error"; } ); document.getElementById('submitButton').addEventListener('click', () => { MessengerExtensions.requestCloseBrowser(function success() { console.log("Webview closing"); }, function error(err) { console.log(err); }); }); }; </script> <form action="optionspostback.php" method="get"> <input type="hidden" name="psid" id="psid"> <input type="text" name="showmsg" id="showmsg"> <h3>Pillows</h3> <input type="radio" name="pillows" value="soft" checked>Soft<br> <input type="radio" name="pillows" value="hard">Hard<br> <h3>Bed</h3> <input type="radio" name="bed" value="single" checked>Single<br> <input type="radio" name="bed" value="double">Double<br> <input type="radio" name="bed" value="twin">Twin<br> <h3>View</h3> <input type="radio" name="view" value="sea" checked>Sea<br> <input type="radio" name="view" value="street">Street<br> <input type="submit" value="Submit" id="submitButton"> </form> <script </body>



optionspostback.php

4. 填完表單,Webview會根據FB SDK指令自動關閉,然後回傳資料,接收資料的網頁有如下的PHP程式接收,同時回傳如圖的確認訊息給使用者。

....//之前自己寫的傳送訊息函數 sendText($_GET['psid'],"Great, I will book you a $_GET[bed] bed, with $_GET[pillows] pillows and a $_GET[view] view."); ....





webhooks程式碼



ini_set('display_errors', 'On'); if( $_REQUEST['hub_challenge']){ echo $_REQUEST['hub_challenge']; } $raw = file_get_contents('php://input'); rewrite('webhooks.txt', "\n\n\n".$raw ."\n\n"); $data = json_decode($raw, true); if( $data['object'] == 'page'){ foreach($data['entry'] as $entry) { foreach($entry['standby'] as $messaging) { rewrite('webhooks.txt', '[sender][id] ='.$messaging['sender']['id']."\n"); rewrite('webhooks.txt', '[message][text] ='.$messaging['message']['text']."\n"); if(!empty($messaging['message']['text'])){ sendText($messaging['sender']['id'], $messaging['message']['text']); } } } } function sendText($sender,$text){ $token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; $url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$token; $data['messaging_type'] = "RESPONSE"; $data['recipient'] = array('id' => $sender); $data['message'] = array('text' => 'Text received, echo: '.$text); echo json_encode($data)."\n"; $options = array( 'http' => array( 'header' => "Content-type: application/json\r\n", 'method' => 'POST', 'content' => json_encode($data) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return $result; } function rewrite($filename, $data) { $filenum=fopen($filename,'a'); //flock($filenum,LOCK_EX); fwrite($filenum,$data); //flock($filenum,LOCK_UN); fclose($filenum); //chmod($filename,0666); } ?>

時間的自然語言理解


本篇設計一個Regular Expression的式子及Python程式,來理解使用者輸入的時間(不含日期),轉成標準的timestamp後,輸出給其它程式使用。
像這種時間、日期、數字等,有規則的字詞,用Regular Expression比利用機器學習還容易多,用機器學習還比較容易失敗。
下面的程式所用的Regular Expression式子有可能會接受錯誤的時間表示方式,畢竟想把所有可能的表示法塞在同一個式子,本來就不太可能,故若要改善,需要拆成多個式子來處理。
程式最下面的MAIN區塊,queryString是輸入的時間有關字句,getTime() 會把標準時間傳回來。
import re import urllib import pandas as pd # constants for chinese_to_arabic CN_NUM = { '〇' : 0, '一' : 1, '二' : 2, '三' : 3, '四' : 4, '五' : 5, '六' : 6, '七' : 7, '八' : 8, '九' : 9, '零' : 0, '壹' : 1, '贰' : 2, '叁' : 3, '肆' : 4, '伍' : 5, '陆' : 6, '柒' : 7, '捌' : 8, '玖' : 9, '貮' : 2, '两' : 2, '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9 } CN_UNIT = { '十' : 10, '拾' : 10, '百' : 100, '佰' : 100, '千' : 1000, '仟' : 1000, '万' : 10000, '萬' : 10000, '亿' : 100000000, '億' : 100000000, '兆' : 1000000000000, } def chinese_to_arabic(cn): unit = 0 # current ldig = [] # digest for cndig in reversed(cn): if cndig in CN_UNIT: unit = CN_UNIT.get(cndig) if unit == 10000 or unit == 100000000: ldig.append(unit) unit = 1 else: dig = CN_NUM.get(cndig) if unit: dig *= unit unit = 0 ldig.append(dig) if unit == 10: ldig.append(10) val, tmp = 0, 0 for x in reversed(ldig): if x == 10000 or x == 100000000: val += tmp * x tmp = 0 else: tmp += x val += tmp return val def word2timestamp(test_str): regex = r"(上午|下午|凌晨|中午|今夜|傍晚|午夜|半夜|夜間|大清早|早上|早晨|晚|晚上)?([零一二兩三四五六七八九十0123456789]+)[點|時|:]([零一二兩三四五六七八九十0123456789]*)[分|:]?([零一二兩三四五六七八九十0123456789]*)秒?\s?(am|pm|a.m|p.m|AM|PM|A.M|P.M)?" match = re.search(regex, test_str, re.MULTILINE) l = [] l.append(chinese_to_arabic(match.group(2))) if (len(match.groups()) > 2): l.append(chinese_to_arabic(match.group(3))) if (len(match.groups()) > 3): l.append(chinese_to_arabic(match.group(4))) match.group(4) if ((match.group(1) == "下午") & (l[0] <= 11) & (l[0] >= 1)): l[0] += 12 if ((match.group(1) == "半夜") & (l[0] in [8, 9, 10, 11, 12])): l[0] += 12 if ((match.group(1) == "今夜") & (l[0] in [5, 6, 7, 8, 9, 10, 11, 12])): l[0] += 12 if ((match.group(1) == "傍晚") & (l[0] in [5, 6, 7, 8, 9, 10, 11, 12])): l[0] += 12 if ((match.group(1) == "午夜") & (l[0] in [5, 6, 7, 8, 9, 10, 11, 12])): l[0] += 12 if ((match.group(1) == "中午") & (l[0] in [1, 2, 3, 4, 5, 6])): l[0] += 12 if ((match.group(1) == "夜間") & (l[0] in [6, 7, 8, 9, 10, 11, 12])): l[0] += 12 if ((match.group(1) == "晚") & (l[0] in [6, 7, 8, 9, 10, 11, 12])): l[0] += 12 if ((match.group(1) == "晚上") & (l[0] in [6, 7, 8, 9, 10, 11, 12])): l[0] += 12 if l[0] == 24: l[0] = 0 string = l[0] for i in range(1, len(l)): string = "%s:%d" % (string, l[i]) return string def getTime(queryString): url = 'http://morpheus.itri-nlp.tw:9801/v2/nlu/predict?' + urllib.parse.urlencode({'q': queryString}) f = urllib.request.urlopen(url) timeInfo = pd.read_json(f.read()) return word2timestamp(timeInfo['response']['labels']['時間'][0]['rawEntity']) if __name__ == '__main__': queryString = '晚7點四十五分十二秒出發' print(getTime(queryString)) # OUTPUT "19:45:12"


















IKEA吊櫃廚櫃

 好不容易裝好IKEA買來的吊櫃,花了三天。 從組裝,鑽牆,上牆調水平,累死我了。