<?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 Akatsuki Taiwan Technology on Medium]]></title>
        <description><![CDATA[Stories by Akatsuki Taiwan Technology on Medium]]></description>
        <link>https://medium.com/@AktsukiTW.techBlog?source=rss-74b829bfdacd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Ca0-_xtq1-kKz-1QjQS6mA.png</url>
            <title>Stories by Akatsuki Taiwan Technology on Medium</title>
            <link>https://medium.com/@AktsukiTW.techBlog?source=rss-74b829bfdacd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:22:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AktsukiTW.techBlog/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[Using FZF to improve productivity]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/using-fzf-to-improve-productivity-84da1df28163?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/84da1df28163</guid>
            <category><![CDATA[utilities]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 17 May 2019 05:31:01 GMT</pubDate>
            <atom:updated>2019-07-31T04:48:48.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using FZF to Improve Productivity</h3><p>By Akash Khan</p><p>Consider the following problem.</p><p>Given an array of strings find all strings that match a given pattern. For example consider the input array to be [&#39;apple&#39;, &#39;ball&#39;, &#39;cat&#39;, &#39;doll&#39;] and the pattern to be al.<br>Looking at the array we can see that ball is the only string that matches the pattern exactly and it&#39;s not very difficult to implement an algorithm to detect this. However a much more interesting version of the problem is when we remove the restriction that the characters in the pattern should appear together. In the above example it would mean that our algorithm would need to output [&#39;apple&#39; , &#39;ball&#39;]. <br>This is known as fuzzy matching. It is part of a larger group of problems known as <a href="https://en.wikipedia.org/wiki/Approximate_string_matching">Approximate String Matching</a></p><p><a href="https://github.com/junegunn/fzf">FZF</a> is a commandline fuzzy finder which solves the above problem . It reads the list from STDIN and writes the result to STDOUT. What makes it special though is that it is extremely fast and extensible. Combined with Unix <a href="https://en.wikipedia.org/wiki/Pipeline_(Unix)">pipelines</a> we can create some very useful functions.</p><h3>Setting up and basic usage</h3><p>Check out the <a href="https://github.com/junegunn/fzf#installation">github page</a> for installation instructions. It’s available for every major platform and can be setup very easily. Once done you should have the fzf executable added.<br>Using fzf is very easy. All the commands I will be talking about follow the same structure .</p><ol><li>First you have the input command which generates the input list .</li><li>Second you pass this list to the fzf executable using | operator and fzf will generate the UI for pattern matching.</li><li>Once the user inputs the pattern fzf will pass the results to STDOUT and we can use the | operator again to use these results.</li></ol><p>In general</p><p>command 1 {options} | command 2 ... | fzf {options} | command n | command n+1 ...</p><p>For example</p><p><a href="https://asciinema.org/a/wMezjHVyC8dWves5lYUQcCYeQ">untitled</a></p><h3>Advanced Usage</h3><p>Since fzf is built to be extensible, it works very well with other unix commands and by composing different commands we can create powerful interfaces. I have listed a few which I’ve been using below:</p><ul><li>Navigating directories ( Replacing cd )</li></ul><p><a href="https://asciinema.org/a/WndJmuQN1ZUBypvebvrevdG9W">cd with fzf</a></p><pre>sh function fd() { <br>  local dir dir=$(find ${1:-.} -path ‘*/\.*’ -prune \ -o -type d -print 2&gt; /dev/null | fzf +m) &amp;&amp; cd “$dir” <br>}<br></pre><pre>function fdr() {<br>  local declare dirs=()<br>  ## Recursively fetch parent directories<br>  get_parent_dirs() {<br>    if [[ -d &quot;${1}&quot; ]]; then dirs+=(&quot;$1&quot;); else return; fi<br>    if [[ &quot;${1}&quot; == &#39;/&#39; ]]; then<br>      for _dir in &quot;${dirs[@]}&quot;; do echo $_dir; done<br>    else<br>      get_parent_dirs $(dirname &quot;$1&quot;)<br>    fi<br>  }<br>  local DIR=$(get_parent_dirs $(realpath &quot;$PWD&quot;) | fzf +m)<br>  cd &quot;$DIR&quot;<br>}</pre><ul><li>Killing processes</li></ul><p><a href="https://asciinema.org/a/1At3O6Xf4R9IqwbGEK9jU3GGx">Kill process with fzf</a></p><pre>fkill() {<br>  local pid<br>  pid=$(ps -ef | sed 1d | fzf -m | awk &#39;{print $2}&#39;)</pre><pre>  if [ &quot;x$pid&quot; != &quot;x&quot; ]<br>  then<br>    echo $pid | xargs kill -9<br>  fi<br>}</pre><ul><li>Searching git commits</li></ul><p><a href="https://asciinema.org/a/yVGCzMz4qYpAlfH4cQu7c0eaT">untitled</a></p><pre>function gitlog() {<br>  ## git log -&gt; fzf -&gt; extract commit SHA -&gt; git show<br>  git log --graph --color=always \<br>      --format=&quot;%C(auto)%h%d %s %C(black)%C(bold)%cr&quot; &quot;$@&quot; |<br>  fzf --ansi --no-sort --reverse --tiebreak=index --toggle-sort=\` \<br>      --bind &quot;ctrl-m:execute:<br>                echo &#39;{}&#39; | grep -o &#39;[a-f0-9]\{7\}&#39; | head -1 |<br>                xargs -I % sh -c &#39;git show --color=always % | less -R&#39;&quot;<br>}</pre><p>If you are a Vim/Neovim user like me, you would be glad to know that FZF also comes with a built-in integration for Vim which can be used to navigate through your code base!</p><p><a href="https://asciinema.org/a/dUAzJHPBYO5577qvLN4u5tMq6">untitled</a></p><h3>Conclusion</h3><p>The above scripts are just a small subset of the things we can do with fzf. By composing different commands, we can create very powerful interfaces which can help save time. The <a href="https://github.com/junegunn/fzf/wiki">FZF Wiki</a> page contains some very good documentation and examples for getting started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84da1df28163" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails 5 with Multi-Databases]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/rails-5-with-multi-databases-6453f0ed3662?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6453f0ed3662</guid>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[rails-5]]></category>
            <category><![CDATA[multiple-database]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 10 May 2019 05:31:02 GMT</pubDate>
            <atom:updated>2019-05-10T05:31:02.790Z</atom:updated>
            <content:encoded><![CDATA[<p>By Aaron Kuo</p><p>在開發 Application 的時候有時會需要同時對多個資料庫做處理，例如從既有系統要遷徒到新的系統，或開發新系統但與舊系統同時運行；又或者，像敝社開發開 game server app 的同時，需要另外開發 application 做為運維管理的輔助程式。</p><blockquote>Update 2019.02.22:<br>Rails 6 將會更完整地解決多資料庫的使用，詳見:<br><a href="https://confreaks.tv/videos/railsconf2018-keynote-the-future-of-rails-6-scalable-by-default">https://confreaks.tv/videos/railsconf2018-keynote-the-future-of-rails-6-scalable-by-default</a></blockquote><p>這些情況下，我們所開發的 Application，除了有自己的 database 來處理本身的業務邏輯，同時也需要讀取來自另一個 Application(Foo) 的資料庫裡的資料；而在開發階段，往往開發環境下就已經擁有 Foo App 的資料庫，所以只要設計讓特定的 model 改成連線至該資料庫的方法：</p><p>例如我們可以增加 initializer 先將連線設定讀取進來</p><pre># /config/initializers/foo.rb</pre><pre>FOO_CONNECTION_SPEC = YAML.load_file(File.join(Rails.root, &quot;config&quot;, &quot;foo_database.yml&quot;))[Rails.env.to_s]</pre><p>在另外設計一個 base model class 指定用連線至 Foo 的 DB Connection</p><pre>class Foo::Base &lt; ActiveRecord::Base<br>  establish_connection FOO_CONNECTION_SPEC<br>end</pre><pre>class Foo::User &lt; Foo::Base<br>end</pre><pre>class Foo::SomeTable &lt; Foo::Base<br>end</pre><p>如此就可以實現讓這些 model 連線到其他 database 的行為。</p><p>於是，我們接著就能在 App 中開發一些要對 Foo 的資料庫做操作的程式，例如查詢 Foo 的 user 紀錄、實作對 Foo 資料的統計運算…等。</p><h3>問題</h3><p>但是，當開始要對這些程式碼撰寫測試時，這時就沒有屬於測試用的 Foo 資料庫，無法對測項安排所需的假資料，當然也就無法讀取了！（或許你也可以選擇去 Mock 那些 model 的行為，但對假資料的生成和管理太不方便且沒效率了…）</p><p>所以我們需要對測試環境，也準備 Foo 的測試資料庫，並讓原本 App 的 Rspec 可以對它建立資料來運行測試</p><h3>解決方案</h3><p>這時，我們可以另外產生一組類似 db:create, db:schema:load 的 rake 指令，來幫助建立 Foo 的 test database</p><pre># lib/tasks/foo.rake</pre><pre>namespace :foo do<br>  namespace :db do |ns|<br>    task :drop do<br>      Rake::Task[&quot;db:drop&quot;].invoke<br>    end</pre><pre>    task :create do<br>      Rake::Task[&quot;db:create&quot;].invoke<br>    end</pre><pre>    namespace :schema do<br>      task :load do<br>        Rake::Task[&quot;db:schema:load&quot;].invoke<br>      end</pre><pre>      task :dump do<br>        Rake::Task[&quot;db:schema:dump&quot;].invoke<br>      end<br>    end</pre><pre>    ns.tasks.each do |task|<br>      task.enhance [&quot;foo:change_db_config&quot;] do<br>        Rake::Task[&quot;foo:revert_db_config&quot;]<br>      end<br>    end<br>  end</pre><pre>  task :change_db_config do<br>    @origin_config = {<br>      env_schema: ENV[&#39;SCHEMA&#39;],<br>      config: Rails.application.config.dup<br>    }</pre><pre>    ENV[&#39;SCHEMA&#39;] = &quot;db/foo/schema.rb&quot;<br>    Rails.application.config.paths[&#39;config/database&#39;] = [&quot;config/foo_database.yml&quot;]<br>  end</pre><pre>  task :revert_db_config do<br>    ENV[&#39;SCHEMA&#39;] = @original_config[:env_schema]<br>    Rails.application.config = @original_config[:config]<br>  end<br>end</pre><p>這時我們主要產生了這四個 rake 指令，可以幫我們操作另外一組 database</p><ul><li>foo:db:create</li><li>foo:db:drop</li><li>foo:db:schema:load</li><li>foo:db:schema:dump</li></ul><p>而每個指令其實也就直接延用了 ActiveRecord 既有的 rake 行為，我們所做的只是在原指令執行前，變更了 db 的 config 設定，並在執行後再還原回來</p><p>於是，只要：</p><ul><li>config/foo_database.yml 裡定義好測試資料庫的設定值</li><li>db/foo/schema.rb 裡準備好測試資料表的定義檔（可以用 foo:db:schema:dump 來產生）</li></ul><p>這樣就可以利用以下的指令，準備好測試環境要用的另一組 database 了</p><pre>RAILS_ENV=test rake foo:db:create foo:db:schema:load</pre><p>以上，就是在 Rails App 處理多資料庫&amp;測試的一點解決方法，若有問題還請多多指教，謝謝！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6453f0ed3662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cache Stores in Rails]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/cache-stores-in-rails-7a6499635f79?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a6499635f79</guid>
            <category><![CDATA[memcached]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 03 May 2019 05:31:01 GMT</pubDate>
            <atom:updated>2019-05-03T05:31:01.105Z</atom:updated>
            <content:encoded><![CDATA[<p>By Simon Liu</p><h3>Cache Stores in Rails</h3><p>Developers are in a love-hate relationship with caching. In one hand we can save a ton of resource using cache. In the other, cache related bugs are extra elusive. However benefits obviously outweighs the cost, otherwise no one would be using them.</p><pre>Rails.cache.fetch(cache_key) do<br>  # expensive method<br>end</pre><p>Recall the above method? Production servers have been reduced, lives have been saved, cost has been slashed all using the above method. Today we will take a look at few types of caching supported by Rails.</p><h3>File Store</h3><p>Used by default if no cache store is specified. Result of expensive method is stored in file. config.cache_store = :file_store, &quot;/path/to/cache/directory&quot;</p><h3>Use cases</h3><ul><li>Useful in development environment. One can test invalidations by removing cache files.</li><li>Useful in specific production scenario. When Cached object is very big.</li></ul><h3>Pitfalls</h3><ul><li>Slower than Memory and Memcache.</li><li>Cache store is not purged automatically.</li><li>Need to manually manage cache clean up using Rails.cache.cleanup.</li></ul><h3>Memory Store</h3><p>Cached content is stored in the main Ruby process. Memory store utilizes the (LRU) method to purge stale cache. Least Recently Used item is automatically purged to make room for new content. config.cache_store = :memory_store, { size: 16.megabytes }</p><h3>Use cases</h3><ul><li>Fastest cache store but can only be used in production if total cache size can be calculated.</li><li>Useful in development. Restarting any ruby process using cache will also purge it.</li></ul><h3>Pitfalls</h3><ul><li>Unregulated in memory cache can result in memory thrashing rendering any service unusable as host system begin to use disk for RAM.</li><li>Each process can have different cached content if not careful.</li></ul><h3>Memcache Store</h3><p>Cache is stored in a different service. Normally using a in memory storage, most popular services are memcached and Redis. Can be horizontally scaled by distributing cache keys amongst multiple cache services. This is the most commonly used caching strategy for production. config.cache_store = :mem_cache_store, &quot;memcached-1.example.com&quot;, &quot;memcached-1.example.com&quot;</p><h3>Use cases</h3><ul><li>Web page fragment cache, Russian doll cache.</li><li>Easy horizontal scaling.</li></ul><h3>Pitfalls</h3><ul><li>Expensive perhaps.</li></ul><h3>Null store</h3><p>Disables caching. Useful for debugging if an issue is related to cache.</p><pre>config.cache_store = :null_store</pre><h3>Conclusion</h3><p>So then you ask which one should I use? Unfortunately this is another one of those no silver bullet answer. It all depends on your use case. Below are some suggestions you may reference.</p><ol><li>Use memcache to cache small objects with high frequency of access.</li><li>Use file cache to cache large objects with moderate frequency of access. For high frequency, consider CDN.</li><li>Use memory cache to cache small to medium objects only if total cacheable size can be calculated.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a6499635f79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encrypt using SSH key pair]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/encrypt-using-ssh-key-pair-f7e99dfef164?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7e99dfef164</guid>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 26 Apr 2019 05:31:03 GMT</pubDate>
            <atom:updated>2019-06-06T07:23:57.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>Encrypt using SSH Key Pair</h3><p>By Zachary Huang</p><p>Under some circumstances you might want to send classified messages or files to other users. Openssl library provides us a fast and easy way to encrypt these documents. Before encrypting, a key pair is required. This article will be talking about how to produce encryptions using exist key pairs. For more knowledge, you can refer to previous article on this blog.</p><h3>Creating SSH Key Pair</h3><p>Before we start talking about encryption and decryption, we need something more fundamental. Ｗe need to create our own key pairs.</p><pre>ssh-keygen -t rsa</pre><p>Doing this gives you 2 files, id_rsa and id_rsa.pub, which are your private key and public key, respectively. They are your RSA key pair. Among two files, you must preserve your private key carefully, or this whole encryption thing will not be secured anymore, which loses its very own purpose. On the other side, you can now send your public key to others so they can encrypt messages for you.</p><p>Now, assume you received someone else’s public key. You want to send him/her a secret message, let’s say, a love letter, and of course you don’t want anyone else to read it, or you might die of embarrassment.</p><h3>Encryption</h3><p>To encrypt files, we can use openssl rsa library. By default, ssh-keygen generates key in OpenSSH format that is not very friendly to openssl. It needs some before processing. Transform the public key into PKCS8 format. There are 2 ways to do this</p><pre>1. OpenSSH -&gt; PKCS8<br>ssh-keygen -e -f ./id_rsa.pub -m PKCS8 &gt; ./id_rsa.pub.pkcs8</pre><p>or</p><pre>2. OpenSSH -&gt; PKCS1 -&gt; PKCS8<br>ssh-keygen -e -f ./id_rsa.pub -m pem &gt; id_rsa.pub.pem<br>openssl rsa -in id_rsa.pub.pem -RSAPublicKey_in -pubout &gt; id_rsa.pub.pkcs8</pre><p>Now using the PKCS8 file, we can encrypt by doing</p><pre>openssl rsautl -encrypt -pubin -inkey id_rsa.pub.pkcs8 -in LoveLetter.txt -out LoveLetter.txt.enc</pre><p>However, we usually don’t do this. Despite being well-secured, there are several disadvantages for RSA algorithm. Being an asymmetric cryptography, RSA is much slower on performance. Most importantly, RSA can only encrypt files of the same size as its key size. By default, ssh-keygen creates a 2048 bits key pair. This implies that our target file cannot be longer than 2048 bits. Which means that our love letter here cannot be longer than approximately 256 letters. That would be about 3 sentences. Not a very efficient way to express feelings.</p><p>We can do this in an alternative way. Openssl provides us other cryptography algorithm, one of which is AES. Though we will not talk about the details in this article, all we have to know is that as a symmetric cryptography, AES is a good choice when dealing with large files. Now we change our plan a little tiny bit. Instead of encrypting directly with RSA, we first encrypt our target with AES.</p><p>Generate a symmetric AES key</p><pre>openssl rand 32 -out secret_key // this will be a 32x8 = 256 bits key</pre><p>Encrypt using our new AES key</p><pre>openssl aes-256-cbc -in LoveLetter.txt -out LoveLetter.txt.enc -pass file:secret_key</pre><p>Note that the secret key generated should only be use this one time. Now, as we have done before, we encrypt with RSA. But this time, encrypt the key instead</p><pre>openssl rsautl -encrypt -pubin -inkey id_rsa.pub.pkcs8 -in secret_key -out secret_key.enc</pre><p>After everything is settled, send the encrypted LoveLetter along with the encrypted secret_key to your friend, and tell him/her to follow the instructions below to decrypt.</p><h3>Decryption</h3><p>STEP 1. Find their private key.</p><p>STEP 2. Decrypt the secret_key with private key</p><pre>openssl rsautl -decrypt -ssl -inkey id_rsa -in secret_key.enc -out secret_key</pre><p>STEP 3. Decrypt the message with the secret_key</p><pre>openssl aes-256-cbc -d -in LoveLetter.txt.enc -out LoveLetter.txt -pass file:secret_key</pre><p>STEP 4. Enjoy the message</p><p>In this article, I use RSA key pair as the key of AES key to solve the problem of key size limitation. Of course, this is just one of many possible solutions. I hope this help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7e99dfef164" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[淺談Cartoon Rendering系列－Cartoon Rendering using Texture Mapping]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/%E6%B7%BA%E8%AB%87cartoon-rendering%E7%B3%BB%E5%88%97-cartoon-rendering-using-texture-mapping-f8ce5ac3a2b2?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8ce5ac3a2b2</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[3d-computer-graphics]]></category>
            <category><![CDATA[texture]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 19 Apr 2019 05:31:00 GMT</pubDate>
            <atom:updated>2019-08-02T06:46:00.285Z</atom:updated>
            <content:encoded><![CDATA[<p>By Annie Chen</p><h3>Cartoon Rendering using Texture Mapping</h3><p>說到Cartoon Rendering得先提到非真實感渲染（Non-photorealistic rendering，NPR）。</p><p>NPR在CG電腦圖學中有別於一般追求真實的電腦繪圖，是一種模擬油畫,素描,卡通,動畫等藝術式的繪製風格。</p><p>而Cartoon Rendering卡通渲染則是NPR中一個典型的例子。</p><p>在模擬卡通渲染中，常會用一張漸層貼圖來表現渲染，稱為Texture Mapping，但Texture Mapping原理為何呢？</p><p>以下圖表示N代表法向量,L代表光的方向Lighting，當N與L平行，代表面對光，此時受到光影響是最大的，常以N dot L做計算，dot代表做向量內積。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*D7HDEBMj1bfFGTnDGPVXCg.jpeg" /></figure><p>而何謂向量內積呢？是否回憶起高中三角函數的餘弦定理了呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*e0FrLLNLiZrX6NtIKvdoPg.png" /></figure><p>兩個向量A ,B, A 與 B做內積代表算出A在B方向的投影量(純量，介於0~1之間)，當兩向量平行時，內積=1(重疊)，當兩向量垂直時內積=0(無相交)。</p><p>利用向量內積的特性，假設光與法向量平行，完全面光，此時就查找Texture Mapping中u＝0，比較淺的顏色。當N與L垂直時，代表照不到光，所以屬於暗面，此時查找u＝1，比較深的顏色，當這張貼圖與模型相對應時，就可以把顏色對應到渲染表現中，以模擬卡通渲染。</p><p>下圖則為Team fortress 2運用 Texture Mapping渲染到模型的效果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EiYw92iTKgg0GwVvpxv8w.jpeg" /></figure><p>美術可輸出各式不同的漸層圖，對應後看哪個效果是最喜歡的喔！</p><h3>Reference</h3><ul><li><a href="http://www.moddb.com/mods/team-fortress-2-shading-mini-mod/images/dr-youre-the-example">Team fortress 2</a></li><li><a href="https://en.wikipedia.org/wiki/Dot_product">Dot_product</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8ce5ac3a2b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Td-Idf of Texting Mining]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/td-idf-of-texting-mining-d4cbfaac41ef?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4cbfaac41ef</guid>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 12 Apr 2019 05:31:00 GMT</pubDate>
            <atom:updated>2019-04-12T05:31:00.766Z</atom:updated>
            <content:encoded><![CDATA[<p>By Rong Teng</p><p>去年畢業之後，進入Akatsuki開始了人生第一份工作～(菜味很重) 今天要分享的東西和目前工作的東西(好似)沒有什麼關聯，但是學生時期的兩份實習都與文字探勘相關，所以來做個小小小分享（其實是幫自己複習 XD ）</p><h3>TF — IDF</h3><p>TF-IDF 是 Term Frequency — Inverse Document Frequency 的縮寫，是一種常用於資訊檢索與文字挖掘的加權技術，用以評估一字詞對於一個檔案集或一個語料庫中的其中一份檔案的重要程度。 首先我們要先了解什麼是 Term Frequency和 Document Frequency。</p><h4>TF = Term Frequency 詞頻</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5j_SEdWSvjEx5uMO" /></figure><p>{:width=”75%”}</p><p>以上圖表格的例子為例：</p><p>假如一篇文章只包含這 5 個 terms，則此篇文章的總詞數 = 20 故 Akatsuki 出現 3 次，所以 TF 為 3/20</p><p>以此類推，將之整理為下表：</p><p>TermOccurrence times in documentTFAkatsuki33/20is55/20a55/20game66/20company11/20</p><p>沒有意義的詞彙就將其先刪除，例如 is 和 a ，剩餘詞彙中詞頻最高的兩個詞彙分別為 game 和 Akatsuki，那這樣代表 game 比 Akatsuki 更為重要嗎？</p><p>答案是: 不一定</p><p>由於有些詞彙在生活中出現的比例較高，所以必須另外考量 IDF 這個指標。</p><h4>IDF = Inverse Document Frequency 逆向文件頻率</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4r5_1brxyIx93aln" /></figure><p>{:width=”75%”}</p><p>以上圖表格的例子為例：</p><p>假如語料庫中的檔案總數共有 10000 篇，而包含 Akatsuki 的檔案總數共有 10 篇</p><p>則 Akatsuki 的 IDF 為 log(10000/10) = 3</p><p>以此類推，將之整理為下表：</p><p>TermNumber of documents occur this termIDFAkatsuki10log(10000/10) = 3game1000log(10000/1000) = 1</p><p>最後終於可以來計算 TF-IDF 了～(撒花)</p><h4>TF-IDF</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3GtqbP7s5PFg1g8F" /></figure><p>{:width=”75%”}</p><p>TermTFIDFTF-IDFAkatsuki3/2033/20*3 = 9/20game6/2016/20*1 = 6/20</p><p>從上表可以得知，Akatsuki 的 TF-IDF 是最高的，所以這篇文章中 Akatsuki 是最具有代表性的詞彙。</p><h4>總結</h4><p>一個詞彙具有 高詞頻 與 低文頻 則會有較高的 TF-IDF，表示其對這篇文章的重要程度越高，也越具有代表性，換句話說，就是這篇文章的 關鍵字 啦！！！</p><p>以上是對 TF-IDF 初淺的介紹，希望可以幫助到完全沒有學習或接觸過的人，因為我也很菜啊啊啊啊XD</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4cbfaac41ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用 Jenkins 實作 Pull Request 測試]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/%E4%BD%BF%E7%94%A8-jenkins-%E5%AF%A6%E4%BD%9C-pull-request-%E6%B8%AC%E8%A9%A6-4d0f4d38106?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d0f4d38106</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Thu, 04 Apr 2019 17:31:30 GMT</pubDate>
            <atom:updated>2019-04-04T17:31:30.998Z</atom:updated>
            <content:encoded><![CDATA[<p>By Hannah Lo</p><p>一般來說進行開發時我們會從目前的版本(develop)切出新的分支(feature-x)，在新的分支上製作新功能，開發完成後再將新分支 merge 回主要版本中。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*uor3slTF0oVAFXTb" /></figure><p>在 merge 回主要分支前我們必須確定修改的內容不會影響目前版本的運行。在多人共同開發的團隊中這是一件非常重要的事。因為主分支的錯誤可能影響他人開發和測試流程，進而造成整個時程的延宕，所以必須特別小心。</p><p>Jenkins CI 就能幫助我們在 merge 回主分之前進行簡易的驗證，如編譯並運行單元測試。在舊版的 Jenkins 需要安裝 plugin 才能在工作中接收 GitHub 狀態變更並回傳工作結果給 GitHub 的功能。但在 2.x 版本之後可以直接使用 Multibranch Pipeline，裡面已經整合了需要相關功能。只需要幾步驟的設定就能讓 Jenkins 幫我們做測試啦！</p><h3>先行條件</h3><p>如前面所提到的在這篇文章提供的方法需要有以下條件：</p><ol><li>用 GitHub 管理你的程式碼</li><li>有一個 Jenkins 平台</li><li>Jenkins 能夠自公開網路中存取 (GitHub 要能連的到)</li></ol><h3>GitHub Access Token</h3><p>為了讓 Jenkins 有權限能夠接收 GitHub 的 PullRequest 通知，需要產生一個 GitHub access token 給他使用。</p><p>登入一個有寫入權限的帳號 Settings -&gt; Developer settings -&gt; Personal access tokens -&gt; Generate new token，增加一個 Token 並且勾選以下權限：</p><ul><li>admin:repo_hook — for managing hooks (read, write and delete old ones)</li><li>repo — to see private repos</li><li>repo:status — to manipulate commit statuses</li></ul><h3>設定 GitHub Webhooks</h3><p>切到 GitHub 儲存庫的頁面</p><p>Setting -&gt; Webhooks -&gt; Add webhook</p><p>在 Payload URL 輸入 jenkins 的網址，如：</p><p>http://&lt;your-jenkins-url&gt;/github-webhook/</p><h3>在 Jenkins 設定 GitHub Servers</h3><p>之後在 Jenkins 的 Configuration 介面中的 GitHub -&gt; GitHub Servers 增加一筆設定。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jyElL187qr3iZO0_" /></figure><h3>建立任務</h3><p>Jenkins -&gt; New Item -&gt; 選 Multibranch Pipeline 並為它命名</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*PY-RKKEmQV0FJ287" /></figure><p>在 Configure -&gt; Branch Sources 指定儲存庫</p><p>Build Configuration 需要輸入使用的 Jenkinsfile 路徑</p><p>設定完成後 Jenkins 就會檢查所有分支，如果有找到 Jenkinsfile 就會依照檔案設定來工作，如編譯測試版本或運行單元測試等。 之後儲存庫 Pull Request 有變動時就會觸發 Jenkins，運行結果再回傳到 GitHub 顯示在 PR 的下方</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mOMxP_skD9zICBeQ" /></figure><h3>Jenkinsfile 範例</h3><pre>groovy node(‘server’) { <br>  stage(‘Checkout’) { <br>    checkout([<br>      $class: ‘GitSCM’, branches: [[name: env.BRANCH_NAME]],    <br>      doGenerateSubmoduleConfigurations: false, <br>      extensions: [<br>        [<br>          $class: ‘CloneOption’, noTags: false, <br>          reference: ‘’, shallow: true, timeout: 60<br>        ], <br>        [$class: ‘CheckoutOption’, timeout: 20], <br>        [<br>          $class: ‘SubmoduleOption’, <br>          disableSubmodules: false, parentCredentials: true, <br>          recursiveSubmodules: true, reference: ‘’, timeout: 20, <br>          trackingSubmodules: false<br>        ]<br>      ], <br>      submoduleCfg: [], <br>      userRemoteConfigs: [[<br>        credentialsId: ‘your github credentialsId’, <br>        url: ‘<a href="https://github.com/repo.git">https://github.com/repo.git</a>&#39;<br>      ]]<br>    ]) <br>  } <br>  stage(‘Do something’) { <br>    if ( env.BRANCH_NAME == ‘develop’ ) { <br>      echo ‘Do something with develop branch’ <br>    } else { <br>      echo ‘Do something with other branches’ <br>    } <br>  } <br>}</pre><h3>參考資料</h3><ul><li><a href="https://jenkins.io/doc/book/pipeline/multibranch/">Jenkins Document - Multibranch</a></li><li><a href="https://wiki.jenkins.io/display/JENKINS/Github+Plugin">Jenkins - Github Plugin</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d0f4d38106" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain Event Pattern]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/domain-event-pattern-6781e0eba49a?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6781e0eba49a</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[domain-events]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 29 Mar 2019 05:31:02 GMT</pubDate>
            <atom:updated>2019-03-29T05:31:02.943Z</atom:updated>
            <content:encoded><![CDATA[<p>By Shawn Hsiao</p><p>遊戲開發中經常會遇到這樣的需求，發生業務邏輯事件時，需要讓某些系統做相對應的處理。 例如購買道具，交易完成時可能要做以下幾件事情：</p><ul><li>顯示玩家金錢被扣除動畫</li><li>顯示購買道具成功訊息</li><li>道具背包增添一個道具</li><li>消費滿額禮服務檢查是否滿足送禮資格</li></ul><p>如此多且各自為政的系統，若想將以上行為放在交易成功之後執行。則交易服務需要想方設法的取得各系統的Reference，程式碼可能會長這樣：</p><pre>void PurchaseItem(Item item)<br>	{<br>        m_userDeposit.Decrease(item.price);<br>        m_itemStorage.AddItem(item);<br>        <br>        m_userInfoUI.PerformMoneyChange( - item.price);<br>		m_msgSystem.ShowMessage(&quot;Item &quot; + item.name + &quot; purchase successed.&quot;);<br>        m_userPackUI.AddItem(item);<br>        m_topupGiftService.Accumulate(item.price);<br>        if(m_topupGiftService.Qualify())<br>		{<br>        	m_itemStorage.AddItem(m_topupGiftService.Gift());<br>        }<br>    }</pre><p>看起來很直觀，但其實帶來了幾個問題。</p><ol><li>一個道具購買方法，裡面帶了五六種行為，違反了單一責任原則。</li><li>道具交易服務與許多系統耦合，要讓一個交易服務可以正常運行，得塞一堆系統的Refernece進去好讓交易成功時可以呼叫，而這使得產生一個Instance的困難度大幅增加。</li><li>只為了呼叫一個系統的某個行為，而與整個系統產生相依，讓交易服務擁有一堆不需要/不應該擁有的功能，增加了潛在風險，違反接口隔離原則。</li><li>限制了道具交易處理的擴充性，如果日後要再增修交易成功後的行為，除了要再想辦法將系統傳入，還得繼續修改PurchaseItem方法，即使交易本身並沒有改變任何規則。</li><li>呼叫道具購買服務的需求方(User), 連帶的也要擁有這些相依系統的Reference。</li></ol><p>從建構式就能看出這個服務非常難維護，像粽子一樣拎起就是一串。</p><pre>public ItemPurchaseService(UserInfoUI userInfoUI, MsgSystem msgSystem, UserPackUI packUI, ...)<br>{<br>}</pre><p>也許有同學說沒關係呀我IOC掉啊，不傳整個系統進去，只傳行為對應介面進去，這樣服務並沒有擁有整個系統，而是只擁有想執行的行為，這樣就解耦合了吧？</p><pre>public interface IMoneyUpdater<br>{<br>	void PerformMoneyChange(int variation);<br>}</pre><pre>ItemPurchaseService(IMoneyUpdater moneyUpdater, IMsgSender msgSender, ...)<br>{<br>}</pre><p>這並沒有解決次多少問題，頂多就是符合接口隔離原則，再來看看產生一個ItemPurchaseService需要做多少事</p><pre>var itemPurchaseService=  new ItemPurchaseService(GetUserInfoUI(), GetMsgSystem(),<br>   GetUserPackUI(), GetTopUpGiftService());</pre><p>通常購買道具的地方是道具商店(ItemShop)，那麼連帶的， ItemShop也要擁有或有辦法取得這些與他無關的系統。就因為道具購買成功需要做對應處理，而讓整個道具商店系統變的難以維護。</p><p>也許又有同學說，沒關係啊我用觀察者模式呀！玩家道具發生改變通知事件給聆聽者，各系統就做對應處理就行了吧？</p><pre>class ItemStorage:ISubject</pre><pre>public void Add(Item item)<br>{<br>	m_items.Add(item);<br>    Notify();<br>}</pre><pre>class UserPackUI:IItemObserver<br>{<br>	public UserPackUI()<br>	{<br>    	UserItem.AddObserver(this);<br>    }<br>	<br>    void OnItemStorageUpdate()<br>    {<br>    	RefreshItemList();<br>    }<br>}</pre><p>這時的ItemPurchaseService，已經不必再相依於無關系統。他專注在處理道具交易本身的行為-扣除金錢, 增加道具。而金錢與道具改變各會通知UI刷新, 顯示訊息, 似乎問題都已被解決。</p><pre>void PurchaseItem(Item item)<br>{<br>    m_userDeposit.Decrease(item.price);<br>    m_itemStorage.AddItem(item);        <br>}</pre><p>然而，我們再一次檢視需求會發現，消費滿額禮服務，他聆聽的不是道具增加，不是金錢變動，而是道具交易成功事件。這事件本身並非是資料驅動，它是一個行為驅動。 如果我們繼續沿用觀察者模式，讓滿額贈服務聆聽道具購買服務，則又會產生另個矛盾點- 道具購買服務並非是資料holder， 意即它應被允許在runtime中擁有多份instance，然而如果滿額贈服務依賴於道具購買服務， 則用戶必須只能用同一個instance進行道具購買，今天假如購買道具的地方不是只有商店系統，關卡中也想要即時買個道具爽一波。 該怎麼拿到那份道具服務？不就要把道具服務弄成靜態或Singleton或一路傳Reference傳到關卡中？</p><p>DomainEvent模式即是一個用來滿足想聆聽行為本身而非純資料異動事件的觀察需求。</p><ul><li>任何地方都可以Raise與Regisgter事件</li><li>可客製化事件挾帶的資訊</li></ul><p>你可以在任何業務行為發生時Raise一個事件。而聆聽者無需針對目標系統註冊事件，只需對DomainEvent註冊即可。 具體實現如下</p><pre>public static class DomainEvents<br>   {<br>       private static Dictionary&lt;Type, List&lt;Delegate&gt;&gt; m_actionsByType;</pre><pre>       public static void Register&lt;T&gt;(Action&lt;T&gt; callback) where T : IDomainEvent<br>       {<br>           var eventType = typeof(T);<br>           if (m_actionsByType == null)<br>           {<br>               m_actionsByType = new Dictionary&lt;Type, List&lt;Delegate&gt;&gt;();<br>           }</pre><pre>           if (!m_actionsByType.ContainsKey(eventType))<br>           {<br>               m_actionsByType.Add(eventType, new List&lt;Delegate&gt;());<br>           }<br>           var actions = m_actionsByType[eventType];<br>           if (!actions.Contains(callback))<br>               actions.Add(callback);<br>       }<br>       <br>       public static void Unregister&lt;T&gt;(Action&lt;T&gt; callback) where T : IDomainEvent<br>       {<br>           if (m_actionsByType == null)<br>           {<br>               return;<br>           }</pre><pre>           var eventType = typeof(T);<br>           if (m_actionsByType.ContainsKey(eventType))<br>           {<br>               var actions = m_actionsByType[eventType];<br>               actions.Remove(callback);<br>           }<br>       }</pre><pre>       public static void Clear()<br>       {<br>           if (m_actionsByType != null)<br>           {<br>               m_actionsByType.Clear();<br>               m_actionsByType = null;<br>           }<br>       }</pre><pre>       public static void Raise&lt;T&gt;(T args) where T : IDomainEvent<br>       {<br>           if (m_actionsByType != null)<br>           {<br>               if (m_actionsByType.ContainsKey(eventType))<br>               {<br>                   var actions = m_actionsByType[eventType];<br>                   foreach (var action in actions.Cast&lt;Action&lt;T&gt;&gt;().ToList())<br>                   {<br>                       action(args);<br>                   }<br>               }</pre><pre>           }<br>       }<br>   }</pre><p>可以看到，它其實就是一個管理IDomainEvent陣列的靜態類別。我們用泛型來支援客製化的Event型別(DTO)，用Type辨別事件類型，再用Action儲存聆聽者的callback。</p><p>那麼現在要使用這個架構來實現道具購買成功後的事件處理，我們檢視一下需求後發現各系統實際上想關心的是當交易購買成功時，道具的價格，名稱。</p><p>於是我們可自定義一個事件</p><pre>class OnItemPurchased:IDomainEvent<br>{<br>    public int Price;<br>    public string ItemName;<br>    <br>    public OnItemPurchased(Item item)<br>    {<br>    	Price = item.Price;<br>        ItemNaem =  item.Name;<br>    }<br>    <br>}</pre><p>現在ItemPurchaseService是事件發起者，交易成功時，他只需Raise道具購買事件，無需關心誰會對這事件感興趣。</p><pre>class ItemPurchaseService<br>{<br>    ItemPurchaseService()<br>    {}<br>    <br>    void PurchaseItem(Item item)<br>    {<br>        m_userDeposit.Decrease(item.price);<br>        m_itemStorage.AddItem(item); <br>        DomainEvent.Raise(new OnItemPurchased(item));<br>    }<br>}</pre><p>想聆聽者個事件的系統，各自針對這個事件下註冊，如稍早提到的滿額禮服務。</p><pre>class TopUpPurchaseService<br>{<br>    public TopUpPurchaseService()<br>    {<br>    	DomainEvent.Register&lt;OnItemPurchased&gt;(HandleItemPurchased);<br>    }<br> <br>     private void HandleItemPurchased(OnItemPurchased e)<br>     {<br>     	Accumulate(e.Price);<br>        <br>     	if(Qualify())<br>        {<br>        	m_itemStorage.AddItem(Gift());<br>        }<br>     }<br> }</pre><p>就像這樣，TopUpPurchaseService也不需要知道是誰在處理道具交易，他只關心交易成功後要處理的事。 於是各系統可以真正的與ItemPurchaseService解耦合。</p><p>我們檢視一下還有沒有一開始提到的問題。</p><ol><li>PurchaseItem()只專注在處理道具交易邏輯，符合單一責任。</li><li>ItemPurchaseService無需注入其他系統reference, 沒有依賴複雜問題。</li><li>ItemPurchaseService無需注入其他系統reference, 自然沒有違反接口隔離原則。</li><li>未來要擴充行為只需各自註冊處理，再也不需要變動ItemPurchaseService的任何code，降低業務邏輯風險。</li><li>使用道具購買服務的User, 可以隨時無壓力new一個出來執行購買，無需準備道具以外的資訊給服務。</li></ol><p>如此，問題全數解決。</p><p>然而使用上仍需要注意一些問題，由於是靜態類別，當User不需要聆聽該事件時，要記得解除註冊事件，避免記憶體洩漏，如果聆聽者被刪除時，也要記得在解構式中解除註冊。</p><pre>~TopUpPurchaseService()<br>{<br>   DomainEvent.Unregister&lt;OnItemPurchased&gt;(HandleItemPurchased);<br>}</pre><p>DomainEvent這麼好用，是不是用在任何地方？</p><h3>不建議用在業務邏輯以外的行為！</h3><p>如UI事件，要記得DomainEvent是Globalize的，一個按鈕事件應該只發給與這按鈕直接相關的系統，如購買按鈕與商品系統，如果交給了DomainEvent,則表示這ＵＩ事件開放給所有系統自由聆聽。 這可能會帶來負面影響，最有可能發生的問題是聆聽者聽到非預期的事件，試著想像如果一個通用的Dialog，它的按鈕事件同時被一堆系統聆聽，然而該Dialog可能只是一個特定系統的詢問確認視窗，如果觸發了，其他系統不可避免會收到事件通知，也許它們會自動地執行相對應的服務，造成非預期的執行結果。 這也是DomainEvent必須要遵守的一項原則，保持事件對象的單一性。</p><h3>事件處理應避免有順序之別</h3><p>兩個系統聆聽同一事件，如TopUpPurchaseService與UserPackUI都聆聽道具購買成功事件的話， 今天先被通知到的是UserPackUI，它更新了道具顯示欄，增加了購買了道具。接下來TopUpPurchaseService收到事件，如果這次滿足了滿額送的條件，玩家道具又增加了一個，於是道具欄UI就與道具資料不一致了。 解決方法不一定，可以是滿額送也要發它專屬的事件，也可以UserPackUI改聆聽道具增刪事件，總之使用時要特別檢視處理者依賴的資料來源是否會跨領域的被變動。</p><h3>避免重複註冊事件</h3><p>雖然DomainEvent本身有檢查重複性，但User仍可能在同類別用不同方法或註冊同一事件，應避免增加複雜度。</p><h3>注意Register與Raise時機點</h3><p>事件註冊應在系統初始化時，避免Raise時仍未被註冊到。</p><p>以上，只要使用得當，DomainEvent是一個相當方便的Pattern，它提升了程式碼可讀性，擴充性，降低依賴，好處非常多。</p><p>下一個章節介紹強化DomainEvent的用法，利用Handler提升靈活性。 下下個章節會介紹如何解決一對多的事件驅動-EventSourcing。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6781e0eba49a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity Custom Debug Logger]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/unity-custom-debug-logger-8c1c096ccd92?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c1c096ccd92</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 22 Mar 2019 05:31:02 GMT</pubDate>
            <atom:updated>2019-03-22T05:31:02.734Z</atom:updated>
            <content:encoded><![CDATA[<p>By Scissor</p><h3>Overview</h3><p>This article is focus on how to implement a custom debug logger that has following functions:</p><ol><li>Can full close/open Log</li><li>Can close/open Log alternative</li><li>Jump to the outermost of Log Stack</li><li>Quick usage of rich-text features</li></ol><h3>There two major problems about Debug.Log of Unity:</h3><ol><li>Bad performance</li><li>No good switch to open/close log</li></ol><pre>private bool m_isDebug = false;</pre><pre>private void DebugLog(string log)<br>{<br>    if (m_isDebug)<br>    {<br>        Debug.Log(log);<br>    }<br>}</pre><p>But this will make another bothering problem: Every time when you double click the log, will jump into this function. Then you need to track back by looking up stack. Below offers two solutions to solve this problem.</p><h4>Solution I：Scripting Define Symbol</h4><p>Create Debug Class fill with empty functions, and block with RELEASE Define.</p><pre>#if RELEASE<br> <br>using UnityEngine;<br> <br>public static class Debug<br>{<br>    public static void Log( object message )<br>    {<br>    }<br>    public static void Log( object message, UnityEngine.Object context )<br>    {<br>    }<br>    public static void LogError( object message )<br>    {<br>    }<br>    public static void LogError( object message, UnityEngine.Object context )<br>    {<br>    }<br>    public static void LogException( System.Exception exception )<br>    {<br>    }<br>    public static void LogException( System.Exception exception, UnityEngine.Object context )<br>    {<br>    }<br>    public static void LogWarning( object message )<br>    {<br>    }<br>    public static void LogWarning( object message, UnityEngine.Object context )<br>    {<br>    }<br>}<br>#endif</pre><p>Add RELEASE define into Scripting Define Symbol column in Build Settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*HDjdBL2iQUaylOkv" /></figure><h4>Solution II: Create another Debug Class and build into Dll</h4><p>The implement class is right here：</p><p><a href="https://goo.gl/4KXn8P">Debug.cs － Github</a></p><pre>UnityEngine.Debug.Log( &quot;UnityEngine.Debug.Log&quot; );<br>Debug.Log( &quot;Log&quot; );<br>Debug.LogError( &quot;LogError&quot; );<br>Debug.LogWarning( &quot;LogWarning&quot; );<br>Debug.LogBold( &quot;LogBold&quot; );<br>Debug.LogItalic( &quot;LogItalic&quot; );<br>Debug.LogColor( &quot;LogRed&quot;, &quot;red&quot; );<br>Debug.LogColor( &quot;LogYellow&quot;, &quot;yellow&quot; );<br>Debug.LogColor( &quot;LogGreen&quot;, &quot;green&quot; );<br> <br>Debug.FontSize = 14;<br>Debug.Log( &quot;FontSize: &quot; + Debug.FontSize );<br> <br>// Filter<br>Debug.Log( this, &quot;Before adding&quot; );<br>Debug.Add( this );<br> <br>Debug.Log( this, &quot;Filter Log&quot; );<br>Debug.LogWarning( this, &quot;Filter LogWarning&quot; );<br>Debug.LogError( this, &quot;Filter LogError&quot; );<br> <br>Debug.Remove( this );<br>Debug.Log( this, &quot;After removing&quot; );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*IJcMW9rGuuG7eLY8" /></figure><h3>More about Debug.Log</h3><ol><li>Every log contains “UnityEngine.Debug:Log(Object)”: Just add (“\n”) after the message</li><li>Font size: Add “size” tag</li><li>Bold: Add “b” tag</li><li>Italics: Add “i” tag</li><li>Color: Add “color” tag</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c1c096ccd92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A* PATHFINDING ALGORITHM IN 2D GRID]]></title>
            <link>https://medium.com/@AktsukiTW.techBlog/a-pathfinding-algorithm-in-2d-grid-11f5a5354cc2?source=rss-74b829bfdacd------2</link>
            <guid isPermaLink="false">https://medium.com/p/11f5a5354cc2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[pathfinder]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Akatsuki Taiwan Technology]]></dc:creator>
            <pubDate>Fri, 22 Mar 2019 05:31:02 GMT</pubDate>
            <atom:updated>2019-03-22T05:31:02.601Z</atom:updated>
            <content:encoded><![CDATA[<p>By Blake Lin</p><p>A* algorithm can be used to find the shortest path like Dijkstra’s algorithm, but A* algorithm uses the heuristic function to guide its way towards the goal more quickly.</p><h3>DIJKSTRA’S ALGORITHM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/0*Fn8YJDkq5SLhKLoM" /></figure><p>g(n): the cost of the path from the start point to any vertex n</p><h3>A* ALGORITHM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/0*CGX0H0z7hN-zVCTj" /></figure><p>g(n): the cost of the path from the start point to any vertex n<br>h(n): the heuristic estimated cost from vertex n to the goal</p><p>When h(n) = 0 , it’s just like Dijkstra</p><h3>FOR EXAMPLE</h3><p>Dijkstra’s algorithm will expand outward from start point and scan all neighborhood vertex n cost until it finds the goal so it will waste much time in the unnecessary vertex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*5Px-_xPk_tj4qmOhFFaTAg.png" /></figure><p>A* algorithm additionally uses the heuristic function to guide its way towards the goal so it tends to focus on the paths which lead to the goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*NswNFbfn2M4NDds5zJRLLQ.png" /></figure><h3>How to Get The Heuristic Cost</h3><p>Heuristic costformula</p><p>Euclidean Distance: Use real distance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/0*dIkUZaIyurnqCsA0" /></figure><p>Manhattan Distance: Can only move 4 directions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/83/0*ZWXXAq6ceQfjsqDp" /></figure><p>Chebyshev Distance: Can move 8 directions, diagonal cost is same as horizontal and vertical</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/0*hgYoXxeI-_DfMMWG" /></figure><p>Diagonal Distance: Can move 8 directions, 14 is mean diagonal cost, use 14 is more effective than sqrt(2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*Pt2rs6mtBckIGyUn" /></figure><h3>Implement A* Path Finding Algorithm</h3><pre>// openSet is the nodes that have calculated cost<br>// closedSet is the nodes that haven&#39;t calculated cost yet<br>Path findPath(startNode, endNode) {<br>  openSet.add(startNode)<br>  while (openSet.any?) {<br>    openSet.sort();<br>    currentNode = openSet.pop_front();<br>    closedSet.add(currentNode)<br><br>    // finally find the goal, trace path with parent<br>    if (currentNode == endNode) {<br>      while (currentNode != startNode) {<br>        path.Add(currentNode);<br>        currentNode = currentNode.parent;<br>      }<br>      return path<br>    }<br><br>    for (neighbourNode : currentNode.neighbours) {<br>        if (!neighbourNode.walkable ||<br>            closedSet.contains(neighbourNode)) {<br>          continue;<br>        }<br><br>        int cost = currentNode.gCost + heuristic_cost_estimate(currentNode, neighbourNode);<br>        if (cost &lt; neighbour.gCost || !openSet.contains(neighbour)) {<br>          neighbour.gCost = cost;<br>          neighbour.hCost = heuristic_cost_estimate(neighbour, targetNode);<br>          neighbour.parent = currentNode;<br><br>          if (!openSet.contains(neighbour))<br>            openSet.Add(neighbour);<br>        }<br>      }<br>    }<br><br>  }<br>  // if not found<br>  return null;<br>}<br><br>int heuristic_cost_estimate(nodeA, nodeB) {<br>  deltaX = abs(nodeA.x - nodeB.x);<br>  deltaY = abs(nodeA.y - nodeB.y);<br><br>  if (deltaX &gt; deltaY)<br>    return 14 * deltaY + 10 * (deltaX - deltaY);<br>  return 14 * deltaX + 10 * (deltaY - deltaX);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11f5a5354cc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>