<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alan on Medium]]></title>
        <description><![CDATA[Stories by Alan on Medium]]></description>
        <link>https://medium.com/@alantseng?source=rss-72f231fee8cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IKiHbJLgghOJ_EXF.png</url>
            <title>Stories by Alan on Medium</title>
            <link>https://medium.com/@alantseng?source=rss-72f231fee8cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:00:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alantseng/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[使用 React 實作取得搜尋建議列表的功能]]></title>
            <link>https://medium.com/@alantseng/%E4%BD%BF%E7%94%A8-react-%E5%AF%A6%E4%BD%9C%E5%8F%96%E5%BE%97%E6%90%9C%E5%B0%8B%E5%BB%BA%E8%AD%B0%E5%88%97%E8%A1%A8%E7%9A%84%E5%8A%9F%E8%83%BD-4b2a7c87a676?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b2a7c87a676</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Sun, 06 Dec 2015 14:11:46 GMT</pubDate>
            <atom:updated>2015-12-06T14:11:46.165Z</atom:updated>
            <content:encoded><![CDATA[<p>這次要實作的是利用 React 與 google 的 suggestion 來實作一個可以自動取得 search suggestion 的 input 功能，結果展示如下：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Falantseng%2Fembed%2Fpreview%2FQyWoqe%3Fheight%3D600%26slug-hash%3DQyWoqe%26default-tab%3Dresult%26host%3Dhttp%253A%252F%252Fcodepen.io&amp;url=http%3A%2F%2Fcodepen.io%2Falantseng%2Fpen%2FQyWoqe&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F424900.QyWoqe.small.b6a29ced-443a-4dd9-b31d-d05b11ba1040.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/623b5915292f782fbdb41d5706bc0cf3/href">https://medium.com/media/623b5915292f782fbdb41d5706bc0cf3/href</a></iframe><p>這邊我們主要展示的取得列表的功能，所以使用 jQuery 幫我們完成一些方便的 DOM 操作功能。</p><p>首先，此 React 元件有4個屬性，分別是：searchWords, suggsKeywords, suggs 與 showSuggs，其中 searchWords 是用來儲存使用者輸入的文字， suggsKeywords 則是儲存對應到 suggs 的搜尋關鍵字，而 suggs 則是儲存 google 給的建議關鍵字們，最後 showSuggs 則是用來判斷是否該顯示搜尋建議關鍵字，在這邊只有當使用者輸入的文字(searchWords)和搜尋關鍵字對應的文字(suggsKeywords)是相同時 (代表我們目前儲存的關鍵字列表就是使用著輸入的文字)，以及 showSuggs是 true時，才會真正的顯示搜尋關鍵字列表，相關的判斷式如下：</p><pre>if (this.state.showSuggestions &amp;&amp; this.checkSuggsKeywords(this.state.searchWords)) {<br>  // show the suggestions list  <br>}</pre><p>另外在取得 google 的 suggestions 列表時，我們使用了 JSONP （<a href="http://security.stackexchange.com/questions/23438/security-risks-with-jsonp/23439#23439">這邊有一些安全性的討論可以看一下</a>） 來方便地做一些 <a href="https://developer.mozilla.org/zh-TW/docs/HTTP/Access_control_CORS">CROS</a> 的請求。</p><pre>$.ajax({<br>  ...<br>  dataType: ‘jsonp’,<br>  type: ‘GET’,<br>  success: function(data, textStatus, jqXHR) {<br>    ...<br>  }<br>}</pre><p>另外使用者也可以使用鍵盤上下鍵來選取建議的關鍵字，相關的程式碼如下：</p><pre>handleSelectSuggestions(event) {<br>  let li = $(‘.searcher-suggs-word.selected’);<br>  // 40 =&gt; down, 38 =&gt; up<br>  if (event.keyCode == 40 || event.keyCode == 38) {<br>    // move to the next or previous element in the suggestions list<br>  } else {<br>    // 13 =&gt; enter<br>    if (event.keyCode == 13) {<br>      // set the current selected element<br>    }<br>  }<br>}</pre><p>除此之外，當使用者沒有點選在建議列表或輸入的元件上時，應該把顯示的建議列表給隱藏起來，這邊我們註冊了一個 mousedown 的 event listener 來判斷這件事，判斷的部份如下：</p><pre>handleMouseDown(event) {<br>  let x = $(document).scrollLeft() + event.clientX; // event.offsetX<br>  let y = $(document).scrollTop() + event.clientY; // event.offsetY<br> <br>  // did not click on the search input or the suggestion list<br>  if (this.state.showSuggestions &amp;&amp; !this.checkXYInElement(x, y, ‘.searcher-suggs’) &amp;&amp; !this.checkXYInElement(x, y, ‘.searcher-input’)) {</pre><pre>   this.setState({showSuggestions: false});</pre><pre>  }</pre><pre>}</pre><p>最後因為這邊希望使用滑鼠或鍵盤選取是同一個事件，所以在滑鼠滑過建議列表時，我們也將目前滑過的建議關鍵字增加一個與鍵盤選取相同的 class name，相關的程式如下：</p><pre>handleHoverSearcherSuggestions(event) {<br>  $(‘.searcher-suggs-word.selected’).removeClass(‘selected’);<br>  $(‘.searcher-suggs-word:hover’).addClass(‘selected’);<br>}</pre><p>以上就可以實作一個簡單的顯示建議關鍵字列表的功能。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b2a7c87a676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xcode Debug 的兩個實用技巧]]></title>
            <link>https://medium.com/@alantseng/xcode-debug-%E7%9A%84%E5%85%A9%E5%80%8B%E5%AF%A6%E7%94%A8%E6%8A%80%E5%B7%A7-c617543ab31d?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c617543ab31d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[os-x]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Wed, 02 Dec 2015 15:42:03 GMT</pubDate>
            <atom:updated>2015-12-02T15:42:03.271Z</atom:updated>
            <content:encoded><![CDATA[<p>在幫同事 debug 時，有兩個很好用的 debug 技巧，原本以為應該都知道的卻不是的情況，這邊說明一下：</p><p>進公司後，把能共用的東西都模組化後，多了很多 library ，而在 debug 時，常常希望能夠把 breakpoint 下在某個 library 中；這時常看見的是一步一步地追進去 (step in) 後，到了要看的 library 中，才在想下的行數中新增 breakpoint ；但是其實 Xcode 有一個相當實用的功能，可以在想 debug 的 library 中直接在自己想 debug 的行數上新增breakpoint ：</p><p>首先在library 專案中，在想 debug 的地方新增 breakpoint ，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*9itILWhJ-z1-6PbbYJIJZQ.png" /></figure><p>接著在選取這些 breakpoint 後，點選滑鼠右鍵，之後選擇 User，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*sgIjPLMiu6vXyzdAbz4tYw.png" /></figure><p>之後只有有用到此 library 的程式，都可以在此 breakpoint 上 debug，<a href="https://developer.apple.com/library/ios/recipes/xcode_help-breakpoint_navigator/articles/specifying_the_scope_of_a_breakpoint.html">詳細的 Apple 文件在這</a>。</p><p>第二個就是使用 breakpoint 去忽略 Signals，因為有些 Signals 在 Debug 時並不在意，但這些 Signal 卻常常會造成 Xcode 停在某些地方，相當煩人：</p><p>首先切換到 breakpoint navigator，接著新增一個 Symbolic Breakpoint，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*qOqRh6VbkwQ8HXosTQXL5g.png" /></figure><p>在 Symbol 中填入城市的 entry point，這邊是 UIApplicationMain (iOS的程式，如果是OSX的程式應是 NSApplicationMain，一般 Console 應是 main)，然後再 Action 中選取 Debugger Command，之後輸入 process handle SIGPIPE — pass true — stop false — notify true，這邊我們是想忽略掉SIGPIPE，然後勾選 Automatically continue… (<a href="https://forums.developer.apple.com/thread/7425">詳細的 process handle 指令解釋在這</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*EEsqOKLx2tocv1v9nbbYHg.png" /></figure><p>之後再程式剛跑起來後，debug console 就會有如下的訊息：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*2LoTOh2554edCUQe0MuR6g.png" /></figure><p>希望這兩個實用的技巧能夠幫助 debug 流程更加順利。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c617543ab31d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[試試使用 try_lock 來獲取某些必須共用的物件]]></title>
            <link>https://medium.com/@alantseng/%E8%A9%A6%E8%A9%A6%E4%BD%BF%E7%94%A8-try-lock-%E4%BE%86%E7%8D%B2%E5%8F%96%E6%9F%90%E4%BA%9B%E5%BF%85%E9%A0%88%E5%85%B1%E7%94%A8%E7%9A%84%E7%89%A9%E4%BB%B6-a76d9b7cd2fb?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a76d9b7cd2fb</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Sun, 29 Nov 2015 17:23:46 GMT</pubDate>
            <atom:updated>2015-11-29T17:25:06.584Z</atom:updated>
            <content:encoded><![CDATA[<p>在多執行緒的環境中，理想的狀況是每個執行緒共用的東西越少越好，即便有資訊要交換，也只在交換完資訊後就互不相關了，但在接手過的專案中，常常遇到需要共用的物件，而每個執行緒在使用共用的物件卻都需要頗久的時間，而看到的都是使用一定要等到 lock 的機制，情況類似如下：</p><pre>Object shared_obj;</pre><pre>void request_run_task1()<br>{<br>  // lock for using shared_object<br>  shared_object.run_task1();<br>}</pre><pre>void request_run_task2()<br>{<br>  // lock for using shared_object<br>  shared_object.run_task2();<br>}</pre><pre>// thread 1<br>request_run_task1();</pre><pre>// thread 2<br>request_run_task2();</pre><p>要達到 thread-safe 一開始其實不難，但當架構越來越大，threads 越來越多，這種一定要等到物件使用權的方式往往很容易造成 dead lock，又或者是有某個 loading 較重的 task 時，後面往往會堆了一堆 thread 在等著，而當要此 share_object 立刻去做某些事時，常常也必須要等到這些排隊中的 thread 做完才能開始，而同時也造成後面要加入某些功能時，要考慮的事情越來越多，這時候也許就可以開試著考慮用 <a href="http://en.cppreference.com/w/cpp/thread/try_lock">try_lock</a> 的機制，而不是 <a href="http://en.cppreference.com/w/cpp/thread/lock">lock</a>。</p><p>接下來的 demo 中， task1 和 task2 都需要使用 obj_mutex，但使用的時間不一樣，在使用 try_lock 的機制中，會每隔一段時間去試著獲取 obj_mutex，當拿不到 obj_mutex，便會在下一次再來一次，而當拿到時，便開始執行原有的 task：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7022b59b3302810f1f792a28c4bc7e3f/href">https://medium.com/media/7022b59b3302810f1f792a28c4bc7e3f/href</a></iframe><p>這個好處是，可以更快的反應使用者想做的事，而不是等著原先等待的 task 完成；雖然在使用 try_lock 的機制中， task2 並沒有執行，而先執行使用者的 task (stop all tasks)，但如果一定要 task2 執行的話，可以加入一個 timer，一段時間就重試還沒做的 task (也可以加入優先權的考量)，在這樣的機制下，後面在處理新增這個 shared object 的功能時，考慮的事情可以簡單很多，也不太用考慮 task 互卡的問題，也減少很多在修改時造成 dead lock 的可能性。</p><p>雖然在多執行緒的環境中，要考慮的事情還有更多，但在過去的經驗中，再把 try_lock 的機制加入後，在後續修改或新增功能時，要考慮的事情會少很多而跟著也簡單許多。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a76d9b7cd2fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[處理在 react-rails 使用 bigint 的問題]]></title>
            <link>https://medium.com/@alantseng/%E8%99%95%E7%90%86%E5%9C%A8-react-rails-%E4%BD%BF%E7%94%A8-bigint-%E7%9A%84%E5%95%8F%E9%A1%8C-3966f7276e23?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3966f7276e23</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Thu, 26 Nov 2015 14:55:48 GMT</pubDate>
            <atom:updated>2015-11-26T14:55:48.264Z</atom:updated>
            <content:encoded><![CDATA[<p>當在 Ruby on Rails 上使用 <a href="https://github.com/reactjs/react-rails">react-rails</a> 時，如果在 data model 上有使用 bigint，當成參數傳給 React，而因為在 react-rails 中，傳進的去的 Object 會用 to_json 來轉成 React 內部處理的資料，相關在 <a href="https://github.com/reactjs/react-rails">react-rails</a> 的 <a href="https://github.com/reactjs/react-rails/blob/master/lib/react/rails/component_mount.rb">component_mount.rb</a> 中，如下：</p><pre>html_options[:data].tap do |data| </pre><pre>data[:react_class] = name </pre><pre>data[:react_props] = (props.is_a?(String) ? props : props.to_json) </pre><pre>end</pre><p>而因為 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER">javascript 的 number 最大數字</a>是 2⁵³-1，當 bigint 超過這個數字時，會發生在 Rails 中的數值與在 react 中的數值不一樣的情況，而在這邊我使用了將 bigint 轉成 string 再送到 javascript 處理，也就是透過 rails 的 to_s 轉換成 string。</p><p>為了要達成方便設定與使用的方式，我這邊寫了一個<a href="https://github.com/alantseng7/as_json_string_attributes">gem</a>，只要使用者設定要轉成 string 的 attributes 後，之後只要通過 as_json (to_json也是通過 as_json )，就會自動地將相關的 attributes 轉成 string (原本是根據 attributes 所屬的 class 的 as_json method，詳細的實作方式請查看 <a href="https://github.com/rails/rails">rails source code</a> 中的 <a href="https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/json.rb">json.rb</a>)，實作方式如下：</p><pre>def as_json(options = nil)<br>  hash = super.as_json(options)<br>  self.class.json_string_attributes.each do |attr|<br>    key = “#{attr}”<br>    if hash.key?(key)<br>      hash[key] = hash[key].nil? ? hash[key] : hash[key].to_s<br>    end<br>  end</pre><pre>  return hash<br>end</pre><p>首先是透過原有的 as_json 來轉成 hash，之後再 check hash中是否有使用者設定的 attributes，有的話就把原有的值透過 to_s 轉成 string，因為已打包成 gem 的形式，使用者可以在 Gemfile 加入來使用：</p><pre>gem &#39;as_json_string_attributes&#39;, :git =&gt; &#39;https://github.com/alantseng7/as_json_string_attributes.git&#39;</pre><p>而設定的方式只又再相對應的 class 中 include 後，接著設定要轉成 string 的 attributes 就可以了，範例如下：</p><pre>class Post &lt; ActiveRecord::Base<br>    include AsJsonStringAttributes<br><br>    set_json_string_attributes :id, :user_id<br>end</pre><p>這邊是把Post中的 id 與 user_id 轉成 string，之後只要是透過 as_json 的方式，id 與 user_id 都會是 string，範例測試結果如下：</p><pre>$ post<br>=&gt; #&lt;Post id: 1095709597894710274, user_id: 1095708658118956033, content: &quot;Testing!&quot;, created_at: &quot;2015-10-14 16:06:24&quot;, updated_at: &quot;2015-10-14 16:06:24&quot;&gt;</pre><pre>$ post.to_json<br>=&gt; &quot;{\&quot;id\&quot;:\&quot;1095709597894710274\&quot;,\&quot;user_id\&quot;:\&quot;1095708658118956033\&quot;,\&quot;content\&quot;:\&quot;Testing!\&quot;,\&quot;created_at\&quot;:\&quot;2015-10-14T16:06:24.431Z\&quot;,\&quot;updated_at\&quot;:\&quot;2015-10-14T16:06:24.431Z\&quot;}&quot;</pre><p>這邊 Post 的 id 與 user_id 都超過 javascript 能處理的數字，當透過 as_json / to_json 轉換時，id 與 user_id 都會是 string，便能在 javascript 中處理了。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3966f7276e23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用React實作一個Infinite Scrolling 的功能]]></title>
            <link>https://medium.com/@alantseng/%E4%BD%BF%E7%94%A8react%E5%AF%A6%E4%BD%9C%E4%B8%80%E5%80%8Binfinite-scrolling-%E7%9A%84%E5%8A%9F%E8%83%BD-1ecd25efc0b1?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ecd25efc0b1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Wed, 25 Nov 2015 14:31:30 GMT</pubDate>
            <atom:updated>2015-11-26T14:14:21.147Z</atom:updated>
            <content:encoded><![CDATA[<p>當使用者滑到頁面最底端時，頁面會自動讀取新的訊息後，自動地將新訊息連接到頁面最下端，讓使用者不必換頁就有看不完的訊息，今天要實作的就是這樣的功能，在訊息排版則是用了 flexbox，關於 flexbox 這篇文章有不錯的介紹 <a href="https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties">A Visual Guide to CSS3 Flexbox Properties</a> 。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Falantseng%2Fembed%2Fpreview%2FWQqePr%3Fheight%3D600%26slug-hash%3DWQqePr%26default-tab%3Dresult%26host%3Dhttp%253A%252F%252Fcodepen.io&amp;url=http%3A%2F%2Fcodepen.io%2Falantseng%2Fpen%2FWQqePr&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F424900.WQqePr.small.80ef2a35-a04e-4f3e-8a3b-0fa5a4f38c06.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/04c23987c848b87fb2ab483c79ac7165/href">https://medium.com/media/04c23987c848b87fb2ab483c79ac7165/href</a></iframe><p>首先我們要做的就是偵測使用者是否已經滑動到頁面的最下方，這邊則是使用了 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop">ScrollTop</a>， <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight">ScrollHeight</a> 與 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth">clientHeight</a> 屬性，當 ScrollTop 加上clientHeight 超過 ScrollHeight 時，就代表畫面已經滑到最下方了：</p><pre>var scrollTop = (document.documentElement &amp;&amp; document.documentElement.scrollTop) || document.body.scrollTop;</pre><pre> var scrollHeight = (document.documentElement &amp;&amp; document.documentElement.scrollHeight) || document.body.scrollHeight;</pre><pre> var clientHeight = document.documentElement.clientHeight || window.innerHeight;</pre><pre> var scrolledToBottom = Math.ceil(scrollTop + clientHeight) &gt;= scrollHeight;</pre><p>這時我們則用 AJAX 去取得最新的訊息，並將 requestSent 設定成 true，防止再上一個 request 結果還沒回來時，又再度傳送了取得新訊息的 request：</p><pre>if (this.state.requestSent) {<br>  return;<br>}</pre><pre>// enumerate a slow query<br>setTimeout(this.doQuery, 2000);</pre><pre>this.setState({requestSent: true});</pre><p>而當 requestSent 是 true 時，在頁面的最下方則回顯示一個loading的效果，下面是 react 的 render function 中的一小段：</p><pre>if (this.state.requestSent) {<br>  return(<br>    &lt;div className=”users-loading”&gt;<br>      &lt;i className=”fa fa-refresh fa-spin”&gt;&lt;/i&gt;<br>    &lt;/div&gt;<br>  );<br>} else {<br>  return(<br>    &lt;div className=”users-loading”&gt;&lt;/div&gt;<br>  );<br>}</pre><p>當我們取到新訊息後，將新的資料串接到舊的資料後面，之後再將 requestSent 屬性設成 false，讓使用者可以在傳送取得新訊息的 request，如此就能達到我們想要的功能了。</p><pre>var fakeData = this.createFakeData(this.state.data.length, 20);<br>var newData = this.state.data.concat(fakeData);<br>this.setState({data: newData, requestSent: false});</pre><p>在這邊我們使用了假的訊息來展示功能，在實作上可以和後端配合，傳送回 JSON 格式的資料，再使用 JSON.parse 來與舊的資料串接便可。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ecd25efc0b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用React實作一個簡單的Sign In Form]]></title>
            <link>https://medium.com/@alantseng/%E4%BD%BF%E7%94%A8react%E5%AF%A6%E4%BD%9C%E4%B8%80%E5%80%8B%E7%B0%A1%E5%96%AE%E7%9A%84sign-in-form-b5a49755414c?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5a49755414c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Tue, 24 Nov 2015 15:40:56 GMT</pubDate>
            <atom:updated>2015-12-21T10:21:43.068Z</atom:updated>
            <content:encoded><![CDATA[<p>前不久看到了一個感覺不錯的 input label 的呈現方式(已忘了在哪看到了)，今天想說用 React 實作同樣的 label 呈現方式，並把它放在一個簡單的 Sign In Form 中，以下是最後的結果：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Falantseng%2Fembed%2Fpreview%2FPPvEyB%3Fheight%3D600%26slug-hash%3DPPvEyB%26default-tab%3Dresult%26host%3Dhttp%253A%252F%252Fcodepen.io&amp;url=http%3A%2F%2Fcodepen.io%2Falantseng%2Fpen%2FPPvEyB&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F424900.PPvEyB.small.dae87c59-c8be-4660-84ef-b1185e44f4a5.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/5236dae94aca8eb8a52e0dc0e86c787d/href">https://medium.com/media/5236dae94aca8eb8a52e0dc0e86c787d/href</a></iframe><p>其中 Form 的認證使用了簡單的 AJAX 來取得結果，因為自己目前是使用Rails來當後端，當中的 CSRF token 則是 <a href="http://guides.rubyonrails.org/security.html">Rails的Security</a> 處理的一環，這邊改變 label 的 class 的事件，則是加在相對的 input 的 focus 與 blur 事件上。</p><p>其中處理input的focus與blur事件分別是判斷輸入值是否是空的，是的話就在label 的 class name 加上 ”active”，不是的話就把 ”active” 從 label 的 class name 移除，相關的程式如下：</p><pre><br>input.onfocus = function() {<br>  if (label.className.indexOf(‘active’) == -1) {<br>    label.className += “ active”;<br>  }<br>};</pre><pre>input.onblur = function() {<br>   if (input.value.length == 0 || !input.value.trim()) {<br>     label.className = label.className.replace(/(?:^|\s)active(?!\S)/, ‘’);<br>   }<br>}</pre><pre>label.onclick = function() {<br>  input.focus();<br>}</pre><p>而在對於 label 的 CSS 處理上，則是根據 label 的 class name 是否有 ”active” 來移動其位置，相關設定如下：</p><pre>label{<br>  ...<br>  top: 30px;<br> <br>  <a href="http://twitter.com/include">@include</a> transition(..., top .3s);<br> <br>  &amp;.active{<br>    top: 0px;<br>    ...<br>  }<br>}</pre><p>簡單，卻有著還不錯的效果。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5a49755414c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用 React 實作一個簡單的 Sliding Navigator]]></title>
            <link>https://medium.com/@alantseng/%E4%BD%BF%E7%94%A8-react-%E5%AF%A6%E4%BD%9C%E4%B8%80%E5%80%8B%E7%B0%A1%E5%96%AE%E7%9A%84-sliding-navigator-979fe0c32010?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/979fe0c32010</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Mon, 23 Nov 2015 17:29:16 GMT</pubDate>
            <atom:updated>2015-11-26T14:15:26.008Z</atom:updated>
            <content:encoded><![CDATA[<p>這邊使用<a href="https://facebook.github.io/react/">React</a>實作了一個<a href="http://codepen.io/alantseng/pen/LpoVrJ">簡單的Sliding Navigation Bar</a>：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Falantseng%2Fembed%2Fpreview%2FLpoVrJ%3Fheight%3D600%26slug-hash%3DLpoVrJ%26default-tab%3Dresult%26host%3Dhttp%253A%252F%252Fcodepen.io&amp;url=http%3A%2F%2Fcodepen.io%2Falantseng%2Fpen%2FLpoVrJ&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F424900.LpoVrJ.small.eca974f3-c64a-415f-a64a-d14390138f00.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/750a0edc4cfed8bbabb361da5cb7ca4e/href">https://medium.com/media/750a0edc4cfed8bbabb361da5cb7ca4e/href</a></iframe><p>首先是先創建了一個用來當sliding navibar的頁面(mynav-content)，並把它藏在整個頁面的最左側，當使用者按下了toggle 按鈕(mynav-toggle)時，再將此頁面移動到畫面上來，概念和實作方式都相當簡單；而這邊也放了一個mynav-overlay，在使用者點選在不是 mynav-content 頁面上時(因為只佔畫面寬度的90%)，也把 mynav-content 自動地移回畫面外。</p><p>而註冊每個元件的 event listener 的地方都是在 react 的 <a href="https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount">componentDidMount</a> 中，分別在 mynav-toggle 元件的 click 事件上加了顯示 mynav-content 頁面的功能，而在 mynav-content-close 與 mynav-overlay 元件的 click 事件加了隱藏 mynav-content 頁面的功能。</p><p>因爲顯示與隱藏 mynav-content 只是將其元件移動到畫面內與外( <a href="http://www.w3schools.com/cssref/pr_pos_left.asp">left property</a> )，所以僅使用 CSS 的 Transitions 功能；其中隱藏 mynav-content 與 mynav-overlay 的方式是將此兩個元件的 class 類別加上了”hidden”，而顯示則只是拿掉了此類別。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=979fe0c32010" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用std::map作為連續性資料所在範圍的查詢]]></title>
            <link>https://medium.com/@alantseng/%E4%BD%BF%E7%94%A8std-map%E4%BD%9C%E7%82%BA%E9%80%A3%E7%BA%8C%E6%80%A7%E8%B3%87%E6%96%99%E6%89%80%E5%9C%A8%E7%AF%84%E5%9C%8D%E7%9A%84%E6%9F%A5%E8%A9%A2-3172af4e0518?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3172af4e0518</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Sun, 22 Nov 2015 16:04:45 GMT</pubDate>
            <atom:updated>2015-11-26T14:16:23.034Z</atom:updated>
            <content:encoded><![CDATA[<p>很多人使用 std::map 來當作 key/value 的查詢，但在 std::map 中有兩個極為好用的 method (<a href="http://www.cplusplus.com/reference/map/map/lower_bound/">lower_bound</a>, <a href="http://www.cplusplus.com/reference/map/map/upper_bound/">upper_bound</a>)，可以拿來當作資料落點的查詢，而且速度相當快。</p><p>在之前寫遊戲專案時，大多遊戲性資料都是經由企劃設定，輸出成設定檔後，再由程式讀取後，根據這些設定來改變遊戲性；就好比說：企劃設定了一個系統，希望能根據使用者的得分，來給于使用者獎勵；也就是說當使用者分數是1~100時，給于獎勵100，而當分數是101~200時，給于獎勵200，以此類推，分數範圍和獎勵都是企劃所設定的，沒有一定規則，而原來寫的查詢獎勵值得方式大概是這樣：</p><pre>typedef struct Reward<br>{<br> int32_t start_score;<br> int32_t end_score;<br> int32_t reward_value;<br>} Reward;</pre><pre>using RewardsContainer = std::vector&lt;Reward&gt;;<br>RewardsContainer rewards;</pre><pre>int32_t find_reward_value(int32_t score)<br>{<br>  // find max reward<br>  int32_t reward_value = 0;<br>  for (RewardsContainer::iterator it = rewards.begin(); it != rewards.end(); ++it)<br>  {<br>    if (score &gt;= it-&gt;start_score &amp;&amp; score &lt; it-&gt;end_score)<br>    {<br>      reward_value = it-&gt;reward_value;<br>    }<br>    else if (score &gt;= it-&gt;end_score)<br>    {<br>      reward_value = it-&gt;reward_value;<br>    }<br>    else<br>    {</pre><pre>    }<br>  }</pre><pre>  return reward_value;<br>}</pre><p>這方法在設定變多時，所需花費的時間自然就跟著上去，當然有許多方法可以改善原有的效率，但其實 std::map 也可以拿來作為資料範圍落點的查詢，而且效率也相當不錯，類似的方法如下：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5cba54f93b03ed0797271a3006772b0/href">https://medium.com/media/a5cba54f93b03ed0797271a3006772b0/href</a></iframe><p>在這裡把原本的獎勵設定存到 std::map 後，std::map 內的資料類似下列：</p><pre>score (key) =&gt; reward (value)</pre><pre>0 =&gt; 0</pre><pre>100 =&gt; 100 (means 1~100 =&gt; 100)</pre><pre>200 =&gt; 200 (means 101~200 =&gt; 200)</pre><p>當輸入1~100時，會找到的是key為100的那個value，當輸入是101~200時，以此類推；因為這邊只有存reward的最大score值，所有有個假設是reward的最小score值則是剛好比排序中前一個的最大score值大（也就是score 200的前一個是score 100，所以就假定score 200是從101~200)。</p><p>這種方式不僅有效率，而且實作起來也很快很方便，很多地方都可以用到，很適合用在連續性資料的查詢；就好比之前做過在查詢 H264 中 P Frame 的前一個 I Frame 的資訊，就是將每個 I Frame的 timestamp 存在 std::map key 中，而 I Frame 的資訊存在相對的 value 中，當輸入 P Frame 的 timestamp，很快就可以找到前一個(或後一個) I Frame 的資訊。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3172af4e0518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[std::bind and std::function were good]]></title>
            <link>https://medium.com/@alantseng/std-bind-and-std-function-were-good-b29c0eedf2e5?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b29c0eedf2e5</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Thu, 19 Nov 2015 15:07:29 GMT</pubDate>
            <atom:updated>2015-11-26T14:16:44.907Z</atom:updated>
            <content:encoded><![CDATA[<p>今天要介紹的是使用 std::bind 和 std::function (或是用 boost::bind 和boost::function )，雖然在網路上常看到，自己也常在用，可是奇怪的是在接手過的專案中卻沒看過，而在把原有專案(或新專案)中的 callback 和可以當作 invoker 的流程替換成 std::fuction (或 boost::function )後，都使得程式碼更易於維護和修改，也使得程式碼讀起來更簡潔。</p><p>在原有的專案中，最常見的是使用 C Function Pointer 和 virtual function 來當作 callback 或 invoker 流程，如下列所示：</p><pre>typedef void(*callback)(const int32_t input);</pre><pre>class CallbackObject<br>{<br>public:<br> CallbackObject() = default;<br> ~CallbackObject() = default;</pre><pre>virtual void callback(const int32_t input) = 0;</pre><pre>};</pre><p>在專案小或流程簡單的專案當中，這些都沒什麼太大的問題；然而當專案越來越大，功能改動越來越頻繁，程式中物件越來越多樣，常常會造成在 C Function Pointer 內有一堆物件型別或該呼叫哪個物件 method 的判斷，很容易出錯也不易維護，對於日後修改與新增也變得較為複雜；而使用 CallbackObject 的方法中，也會出現很多只拿來當作 callback object 的class，然後再轉而呼叫真正要執行的 method。</p><p>在個人的經驗中，使用 bind 和 function 都使得流程更為清楚，再之後修改與維護也較容易，而使用的方法如下：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27e539e9066b92e8b9857411e90db8b0/href">https://medium.com/media/27e539e9066b92e8b9857411e90db8b0/href</a></iframe><p>希望大家有機會能夠在專案中嘗試看看，對專案和自己的思路都會有很大的幫助。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b29c0eedf2e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thread Pool with Boost]]></title>
            <link>https://medium.com/@alantseng/thread-pool-with-boost-e11a86606add?source=rss-72f231fee8cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e11a86606add</guid>
            <category><![CDATA[boost]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Alan]]></dc:creator>
            <pubDate>Wed, 18 Nov 2015 15:05:44 GMT</pubDate>
            <atom:updated>2015-11-18T15:05:44.987Z</atom:updated>
            <content:encoded><![CDATA[<p>今天要介紹的是使用boost來建立一個好用的thread pool，在過去接手過的專案中，都是只使用dedicated thread的處理方式，這並沒什麼不好；但在某些問題處理中，使用thread pool的概念反而在效能與task的分配上會處理得更好更方便。</p><p>在自己的經驗中，處理video/audio的decode問題，在decode單一 stream下使用 thread pool 和 dedicated thread 效能並沒有太大的差距，但在同時處理多個stream中，兩種處理方式均都造成CPU滿載，但在thread pool方式的處理中，只要將用在decode的thread上的數量對CPU做一下調整，效能上馬上跟使用dedicated thread的方式有著顯著的提升。但是要注意的是，並不是處理所有問題用thread pool的概念都是最好的方式。</p><p>在下列的demo當中，這邊使用了一個work來避免io service在沒有task時會停止的問題：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5af8ca4162088882e253929929725b6b/href">https://medium.com/media/5af8ca4162088882e253929929725b6b/href</a></iframe><p>程式碼相當短，因為處理multi-thread的問題，棘手的往往是tasks的切割與分配。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e11a86606add" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>