<?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 Archer Zhang on Medium]]></title>
        <description><![CDATA[Stories by Archer Zhang on Medium]]></description>
        <link>https://medium.com/@archer.xn?source=rss-d91cbbf7ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rmNwtkiIOOvlPZzOGRAPEA.jpeg</url>
            <title>Stories by Archer Zhang on Medium</title>
            <link>https://medium.com/@archer.xn?source=rss-d91cbbf7ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:51:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@archer.xn/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[Viv Isn’t Vim]]></title>
            <link>https://medium.com/@archer.xn/viv-isnt-vim-60317bf7043b?source=rss-d91cbbf7ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/60317bf7043b</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Archer Zhang]]></dc:creator>
            <pubDate>Mon, 25 Dec 2017 05:15:05 GMT</pubDate>
            <atom:updated>2017-12-25T05:15:05.637Z</atom:updated>
            <content:encoded><![CDATA[<p>Viv is a lightweight C++ implementation of vim. Viv implements most of vim’s core feature including most of the navigation commands and editing commands, command multipliers, undo/redo, macros, syntax highlight for C++, bracket matching, and file I/O.</p><p>Here is the <a href="https://github.com/Azhng/viv">link</a> to the github repo. However, do note that due to university policy, the source code of this project is not publically available. Hence that repo only contains pre-built binaries for Linux and macOS. But feel free to shoot me an email and I will be more than happy to send you a copy of the source code, provided that you are not going to submit it as your own project of course.</p><h4>How did it start ?</h4><p>Well, it all started with <a href="http://lpan.io/">Lawrence</a>. Lawrence is a really good friend of mine and also an absolute legend. Back when I was still working at TD Lab last summer, he told me he was working on a vim clone, <a href="https://github.com/lpan/viw">viw</a> (Vi Worsen), written completely from scratch using C. According to him, he spent entire reading week break working on that project and nothing else. However, that project did help him get his first internship at Universe. Though eventually I only contributed 8 lines of code to Lawrence’s viw to fix a compatibility issue on macOS, the architecture choice of viv was heavily influenced by viw.</p><p>Few months later, when I finished my internship at TD Lab and went back to school for my 2A study term. Quite coincidentally, the final project for one of the courses that I was taking (CS 246E — Object Oriented Software Development) was writing a clone of vim in three weeks.</p><h4>The Architecture</h4><p>The overall architecture of viv is loosely based on the classic MVC architecture.</p><p>The Model layer consists of two <em>State</em> objects, a <em>PaintableState</em> and a <em>LogicState</em>. Intuitively, the <em>PaintableState</em> object is used to represent everything that’s viewable within the applicaiton, including the current state of the document, syntax highlight infomation, cursor information and viewport information. Conversely, the <em>LogicState</em> object is used to record all information that is not directly viewable.</p><p>The View layer is completely stateless. It takes a constant reference of a <em>PaintableState</em> object and renders it using ncurses library.</p><p>The Controller layer is the one my partner and I spent most of my time debating, because eventually we need to be able to support undo/redo and macro operations. That means viv need to be able to record everything single mutations that were applied to the <em>PaintableState</em> object, and it also need to be able to reverse all the mutations. Naively, our original solution was to make the <em>PaintableState</em> object completely immutable, every command that can be undone will generate a new <em>PaintableState</em> object to replace the old one, and the old <em>PaintableState</em> object will be stored onto a stack. This is probably the easiest viable solution to implement undo/redo, however this solution is probably going to blow up the memory if an large file is being opened. (Say like 20 MB). Moreover, it makes implementing macro very tricky. Since when user undoes a macro, all operations captured by the macro will be undone. That means speical data structures need to be created just to handle this one single feature. This also creates a strong coupling between the Controler layer and the Model layer.</p><p>Our second solution was to store a stack of diff objects that captures the difference between <em>PaintableState</em> objects before and after mutation. This method is way more memory friendly compared to the first method. However, it is still difficult to implement macros using this solution due to the same reasons for the first solution.</p><p>Our final solution is what we eventually ended up using. Instead of directly apply operation to the Model layer, the Controller generates an _Action_ object. Each <em>Action</em> object corresponds to a vim command. All <em>Action</em> objects define <em>Action::execute</em> method. For <em>Action</em> that can be undone, the <em>Action </em>object implements an additional <em>Action::undo</em> method. Then it becomes extremely trivial to implement undo/redo and macros. Following pseudocode illustrate the concept of this strategy.</p><pre>void appLoop() {<br>  int command = Keyboard::getKeystroke();<br>  Action* action = ActionFactory::buildAction(command);<br>  if (action-&gt;isUndoable) {<br>    store_action(action);<br>  }<br>  action-&gt;execute(&amp;paintable_state);<br>  View::render(paintable_state);<br>}</pre><p>Observe that in above code snippet, a lot of method are implemented as static method. This is because most of the objects in viv are actually stateless and there is no need to create a new object (though I could have done it better by just implement them using functions in a nested namespace). This is to minimize the coupling between different modules. However, in the actual code we made a heavy use of `unique_ptr` to manage the memory for us. The advantage of this strategy is it really decouples the main application logic from the logic of each individual action. There are times that we need to implement some hacks to get some <em>Action</em> working, but thanks to this architecture all the ugliness of those dirty hacks are self contained within the <em>Action</em> class itself and will not affect the code quality in other places. Neverthelss, this strategy is not perfect either. There exists a lot of boilerplate code in this project since all <em>Action</em> objects inherits from a single base class. If I remember correctly, we ended up with 121 files and about 50 to 60 classes (the entire project is about ~8800 lines). This becomes extremely troublesome when we need to recompile the entire project, roughly it takes about 40 to 50 seconds to compile everything with all the test cases.</p><h4>C vs C++</h4><p>Compared to Lawrence’s viw, viv does have more features. Though this is mainly due to the fact that we had three weeks and two people to work on this project. Also we were working on a higher abstraction level since we were using C++ instead of C. In Lawrence viw, he spent most of his time implement all kinds of doubly linked list to create abstractions for window and documents. Whereas in C++, the standard library comes with various nice STL containers which we made very heavy use of, and also smart pointers which makes memory management extremely easy. I am not saying C++ is a superior language than C, but it is clear that C++ does have a clear advantage than C when it comes to application development.</p><h4>What’s next</h4><p>I just finished my 2A study term (barely survived) and will start my internship at deeplearni.ng this next year. I thinking about writing another post that summarize everything that happened to me this year, it’s probably just going to be a generic post and not really tech related. And also I’m planning for my next big side project at the moment, I’ll probably post something when I have something that’s working.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60317bf7043b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Journey from a nerd to a developer, my experience at TD Lab Part 1: Background, Work and Code.]]></title>
            <link>https://medium.com/@archer.xn/journey-from-a-nerd-to-a-developer-my-experience-at-td-lab-part-1-background-work-and-code-d63919c6e250?source=rss-d91cbbf7ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d63919c6e250</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Archer Zhang]]></dc:creator>
            <pubDate>Sun, 24 Sep 2017 02:18:48 GMT</pubDate>
            <atom:updated>2017-09-24T02:18:48.780Z</atom:updated>
            <content:encoded><![CDATA[<p>Sept 22, 2017</p><p>So after another month of delay, here comes the blog post that was promised.</p><p>It was difficult to describe my feeling when my first coop term finally came to an end. I had a lot of time to think while I was waiting for the `sudo rm -rf ~/*` to slowly wipe out every single trace of my existence from my work laptop. Different thoughts appeared and then disappeared from my mind like a AWS Lambda Function. It was then that I realized how much I was changed in these 4 months, from a nerd that only wants to learn every single piece of knowledge in the realm of CS, to a developer that not only has a passion for the knowledge, but also knows how to go from a real world problem to a complete end-to-end consumer-facing solution.</p><p><strong>## Background</strong></p><p>Like most of the first-time interns, I had absolutely no idea what to expect from my first internship. In fact, the main reason I chose TD Lab was not because of the job itself, but the place it was located, Communitech.</p><p>Compared to other places that I have been to, Communitech is a completely different beast. It is a place where there is a very big chance the stranger you just run into in the hallway is either a founder of a startup or used to be a founder of a startup. There are also many R&amp;D labs not only from TD, but also from companies like Deloitte, Manuallife and GM. My supervisor once said, Kitchener-Waterloo is a place that has the highest IQ per square foot in the entire Canada. I wasn’t really sure if he was being dramatic or not, but for me, it was my first time to see so many brilliant people in one single building.</p><p>TD Lab was originally founded so that TD developers can explore new technologies and build innovative solutions free of bureaucracy of a big corporation. The project we worked on is either a technology exploration, where we try to build something using a completely new tools or library, (e.g. Machine Learning, Blockchain, OCR) or a consumer-facing solution that directly addresses an existing issue that TD has. We often work with other TD teams in other divisions or other research labs from other companies within Communitech.</p><p><strong>## Work</strong></p><p>Working at TD Lab felt more like working for a startup. We usually have no more than 5 people in each dev team. Since our main objective we to build out technical prototypes to validate our concepts, we iterated through our projects really fast. Usually on every Friday, the team will decide the list of features or new design changes that we are going to be implementing for next week. Then next week from Monday to Thursday we would be implementing, debug and test the new features and design changes from previous week, then present to the rest of the lab on Friday morning and maybe do some user testing. Depending on the feedback, we would decide what to do for next iteration.</p><p>My main role back at TD Lab was a mobile developer. My team was responsible for a 4-month long project that involves both a web console and a mobile client. Back when the coop term first started, Google just announced that Kotlin was going to be the second official development language for Android, and that was exactly what we decided to use.</p><p>The process of transition from Java to Kotlin was almost completely painless. Kotlin itself is simply just a better designed language in general compared to Java. It is way less verbose and has mechanism built into the language itself to prevent a lot of common mistakes that programmers make. Also it’s first class support for `lambda` functions (rather than the sketchy anonymous class) is another reason for me to fall in love with it. When I first started using it, it kind of felt like a combination of Scala and C#.</p><p>However, using Android Studio on a dual-core macbook was a completely different story. (especially the beta version of Android Studio) I am not really sure whom should I really be blaming here, the never-ending memory leak of Android Studio or constant crippled performance of Apple’s macbook. Anyway, despite of having a 16GB of RAM, running both Android Emulator and Android Studio at the same time essentially slowed my laptop so bad that it was basically like watching a slideshow on slow motion. If it is not bad enough, even though we had like a doze of Nexus phones in the lab for testings, there was only ONE USB-C cable in the entire lab. (╯°□°）╯︵ ┻━┻ It was like a war everyday fighting for USB-C cable.</p><p>As for the project that I worked on, it wasn’t that bad, by the standard of a technical prototype. This was the first ever Android project that I have worked on and also the first of my projects that involved more than one person and lasted more than two weeks.</p><p>But if we are using standard of a production project, well, that’s a different story.</p><p><strong>## The Code</strong></p><p>My project was originally a simple customer mobile experience exploration scheduled for 2 months, however when we were halfway through this project, we decided to add in another major features on the web platform.</p><p><strong>### What I have done</strong></p><p>When this project first started, me know absolutely nothing about architecture conventions at the time, chose a sort of an unorthodox architecture. So instead of having regular setters and getters method on the data object, all the data mutation operations were being encapsulated inside a single `update()` method of a singleton data access class. The `update()` method has many optional operators that corresponds to the database schema we had on Firebase. Upon its invocation, `update()` performs mutation operation on certain fields based on the parameters provided. Another operation of `update()` is to make callbacks to the UI classes that registered for the data mutation events. Usually within the callbacks defined in the UI classes, it would perform updates on the UI elements. To perform data access, the data access object exposed an public property (like the ones in C#). Therefore, the data schema classes were completely hid away from the UI codes.</p><p><strong>### Why it is wrong</strong></p><p>It wasn’t until later into the coop term that I realized this architecture was flawed in so many ways, and it eventually turned out to be one of the most valuable lessons I have learned throughout this coop term.</p><p>First of all, there was only one single event that UI class can actually listen to. Which means if multiple UI classes were subscribed to the data mutation event, and when one UI classes triggers the `update()` function, all other UI classes would all be notified. It was perfectly fine in the beginning of the project since the size of the project was still small. We had to actively subscribe and unsubscribe the data mutation event based on the UI class life cycle.</p><p>Nevertheless, when we decided to integrated the mobile app with Firebase and our own web console, things started to get ugly really fast. The `update()` function and public data property of data access object essentially created multiple back channels between different UI components. Sometimes, updates in one UI components can lead to very strange behaviour in other UI components, and due to the existence of a back channel, it becomes extremely difficult to debug. Many times I had to log the entire stack trace to find out that it was the innocent looking `update()` function that was causing all my UI components going crazy.</p><p>Also, using simple callback would cause performance issues. `BroadcastReciever` is essentially an Android class that does exactly the same thing, except that it performs all the notifications of event asynchronously whereas the simple callbacks were being execuated on the same thread. Another with `BroadcastReciever` UI class can register to different events whereas our home-made data access object only provides one single event.</p><p>Then, it is the coupling issue and code modularity. By hiding away all the data schema classes, UI classes are directly interacting with data access object, which creates extremely tight coupling between two unrelated classes. This created huge amount of freaking later when we were trying to refactor the code base to be more modular.</p><p>Other than the issue with the singleton data access object, we were also using the `SharePreference` storage in the most inefficient way. We serialized of data schema objects into json file (using jackson) then directly stored the json string under an arbitrary key. The issue with this was the every time when the app opened, a deserialization must be performed. Sadly, jackson implemented json serialization/deserialization through reflection and reflection is an exceptionally slow part of JDK. This caused a lot of performance issues for us later down the road.</p><p><strong>### How can I make it better?</strong></p><p>First, totally get ride of the json serialization/deserialization. There is absolutely no point of doing that. We were using Firebase as our backend, that means Firebase is going to be performing data serialization/deserialization anyways under the hood. Firebase also has a offline mode that persists the data if the app ever crashes. Even if we were not using Firebase, directly stores values as key-value pair into `SharePreference` was going to be a lot more faster than put everything into json. And for other data it actually makes more sense to store them in local the SQL database.</p><p>Second, explicitly returns the data schema object and delegate how the data schema object was going to be used to UI classes. Firebase networking procedures (or a `Cache` class in this case) should be implemented completely independent from both UI classes and data schema class. In fact, the `Cache` class should not even know what kind of object it was requesting from the server. This can greatly reduce the coupling between different components within the project, and also increases the code reusability and maintainability.</p><p>Third, we should also have used `BroadcastReciever` to connect different components instead of a home-made callback to boost the performance and also the maintainability.</p><p>Also, it would be a lot better to use the built-in `Intent` to pass data object between different UI classes instead of directly interact with the data access object. UI classes needs to explicitly invokes a function that commits all the mutations performed on the data object. There are few advantages of doing this. First, decreased coupling between data layer and UI layer. When we were approaching the end of the coop term, the code refactoring was almost impossible due to the extremely tight coupling between our data storage layer and UI layer. Data were implicitly passed between different components via back channel that we created, and this eventually led to unpredicable behaviours of the applicaiton. And Second, it’s going to be a lot easier to implement `undo` or `redo` operations on the data storage layer. I can just simply put all the committed data objects into a stack, then push/pop the object when it’s needed.</p><p><strong>### Other stuff</strong></p><p>So as the title suggested, this is only the Part 1 of this post. Part 2 will focus more on the people and the culture aspects of my coop term. The length of this blog post has become way longer than what I originally planned. I am also planning writing a summary for the project I recently worked on during the Hack the North. But with all my assignments, tests and internship interviews piling up, I have absolutely no idea when I will be able to finish writing them. Well, we will see how it goes.</p><p>(to be continued)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d63919c6e250" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BETA v0.2 release note]]></title>
            <link>https://medium.com/@archer.xn/beta-v0-2-release-note-853096b1cfba?source=rss-d91cbbf7ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/853096b1cfba</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Archer Zhang]]></dc:creator>
            <pubDate>Mon, 04 Sep 2017 05:24:04 GMT</pubDate>
            <atom:updated>2017-09-04T05:24:04.439Z</atom:updated>
            <content:encoded><![CDATA[<p>(imported from <a href="https://archerzhang.me/blogs/17">https://archerzhang.me/blogs/17</a>)</p><p>After 1107 insertions and 71 deletions, now we have the v0.2 release. There has been some delays so this release actually came out about two weeks behind my schedule.</p><p>This release consist of few additions of couple backend endpoints and a complete rewrite of the frontend using ReactJs.</p><p>This is probably going to be the last beta release. All the planned core features will be implemented in next release, which should be v1.0 .</p><h3>Backend</h3><p>In this release, the /refresh endpoint is completely replaced with RESTful endpoints:</p><pre>POST   /blogs <br>PATCH  /blogs/:id<br>DELETE /blogs/:id</pre><p>As before, since all these endpoints are performing mutations on the backend database, authentication token is required or the server will return 403 forbidden error message.</p><p>POST /blogs and PATCH /blogs/:id currently takes a base64 encoded file string. These two endpoints decode the uploaded file then extract necessary information from the from the files, then they perform updates on the database. This is a bit hacky since currently I only have a very basic command line client that encode the markdown file and upload it to the corresponding endpoint. In next few updates, I will probably add in another stand alone client that handles information extraction. Then the function of the backend API would simply become validating the request and then update the database.</p><p>Another big update in the backend is the new /projects endpoints. /projects endpoints are currently not being used for this version of release.</p><p>When I was working on this endpoint, I did run into a bit of troubles. The <a href="https://raw.githubusercontent.com/Azhng/siteV2-frontend/master/_projects.png">design</a> of this page includes a list of technologies that were used. Originally, I was planning store them as a list in one of the fields of each project entry. But soon I realize list is not a data type that’s being directly supported by sqlite3. Even though it is being supported by mysql and postgresql, there aren’t that much resources left on my 128MB-RAM server to power another database server. The alternative solution I came up with was to store them as a special formatted string (E.g. “C^C++^Java”), then I can parse the string on the client side. This way I can get away with the limitation of unable to store list in sqlite3. However the drawback of this solution is the relationship between project and technology becomes one-to-many relationship. But in real life this is not the case. This is equivalent of saying the Firebase used in project1 is completely different from the Firebase used in project2. Therefore, a better relationship model for project and technology is has-many-belongs-to-many relationship.</p><p>To actually implement HMBTM (has-many-belongs-to-many), it would require implement two tables that store projects and technologyseparately. Then we can use a third table that stores the mapping between projects and technology. In some sense, the third mapping table can be viewed as the list that I was originally planning on using.</p><p>Same as /blogs endpoints, /project endpoints consist of:</p><pre>GET    /projects<br>GET    /projects/:id<br>POST   /projects<br>PATCH  /projects/:id<br>DELETE /projects/:id</pre><p>and since I added another technology table in the database, there is another set of api endpoints for /technology:</p><pre>GET    /technologies<br>GET    /technologies/:id<br>POST   /technologies<br>PATCH  /technologies/:id<br>DELETE /technologies/:id</pre><h3>Frontend</h3><p>As mentioned above, the frontend in this release was completely migrated from plain HTML/CSS/Javascript to ReactJs. The main reason for this was to solve the routing issue. In the v0.1 version, the routing was implemented using localStorage in HTML5. The id of the blog was stored in the localStorage before user leaves the index page and read when user first enter the blogs page. When user goes from index page to blogs page, the url changes from /index.html to /blogs.html. The issue here is that the url does not reflect which blog user is currently reading, and user would not be able to share the blog post with another user by sending the url. The information stored in the localStorage would be lost during that process.</p><p>ReactJs comes with react-router, which provides client-side routing functionality. The new url scheme using ReactJs becomes / for index page, and /blogs/:id for blog page, where :id is the blog id that is required to fetch the blog post from my api. By using react-router, it completely eliminates the need of using localStorage and each page becomes, in some sense, stateless. And of course, this would enable users to share the blog post with other users directly by sending the url.</p><p>Also, Bootstrap was being used for layout in this release. This means that the blog is now fully responsive and will change its layout depending on the device type. (Desktop/Tablet/Phone) Though currently the layout is a bit weird on the Tablet screen.</p><h3>ReactJs</h3><p>After using ReactJs for about a week, I found myself completely fall in love with this library and the ideology behind it - <strong><em>Unidirectional data flow</em></strong>.</p><p>Component is the fundamental building block in React&#39;s UI tree. The state of the entire UI flows from the top Component of UI tree to its leave Components. The main advantage of this ideology is it essentially brings functional paradigm into UI development. The UI components evolved from <strong><em>stateful</em></strong> to <strong><em>stateless</em></strong>. There is no back channel between different UI components and the output of the function solely depends on the parameters that were provided. With unidirectional data flow, UI development actually achieved <a href="https://wiki.haskell.org/Referential_transparency">referential transparency</a>.</p><h3>Future and Beyond</h3><p>With school starting in 4 days and Hack the North in two weeks, the development of this blog is probably going to slow down quite a bit. I am still planning to write something about my summer internship at TD Lab. So that is going to be my priority right now for this blog.</p><p>The project page is definitely going to be finished by next release, which means the next release will mainly be an UI update. Some new features I planned right now for next few releases include Signup/Login, Comment, Sharing and RSS subscription, and possibility some form of analytics of the traffic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=853096b1cfba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BETA v0.1 release note]]></title>
            <link>https://medium.com/@archer.xn/beta-v0-1-release-note-20aebfc22a10?source=rss-d91cbbf7ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/20aebfc22a10</guid>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Archer Zhang]]></dc:creator>
            <pubDate>Mon, 04 Sep 2017 05:23:08 GMT</pubDate>
            <atom:updated>2017-09-04T05:23:08.521Z</atom:updated>
            <content:encoded><![CDATA[<p>(imported from <a href="https://archerzhang.me/blogs/15">https://archerzhang.me/blogs/15</a>)</p><p>2 repositories, 4 days, 29 commits, ~400 lines of code, 519 mins of Spotify. That’s how much it took for me to hack together the bare minimum of this site. Not a bad start.</p><p>Nerdy level of this post: ★★★★☆</p><h3>Overview</h3><h3>Progress</h3><ul><li>Finalized and implemented the designs for index page. ✔</li><li>Implemented basic backend API. ✔</li><li>Set up navigation between different pages. ✔</li><li>Deploy backend API service onto my own vps . ✔</li></ul><h3>Frontend</h3><p>The frontend of this blog is pretty simple. Few simple webpages linked using hyperlinks written in vanilla html/css/javascript. I was intentionally minimize the usage of any third party libraries to improve the load time of the page. All the blogs are asynchronously retrieved using Javascript’s <a href="https://developer.mozilla.org/en/docs/Web/API/Fetch_API">fetch</a> API from the API endpoints from the server. Originally I was planning on only using a simple file server that serves static markdown documents. The compilation from markdown to html was supposed to occur at the client side each time when the client loads the page. However, the flaws of that design is although it reduces the complexity of the server code, it makes managing all the blog posts difficult. Each time when I write a new blog post I would have to either use scp or ssh into my server. It would also creates unnecessary overhead for clients to compile markdown documents each time.</p><h3>Backend</h3><p>The entire backend of this site is written in Ruby on Rails. As the first web framework that I learned, Rails does have a special place in my heart. The API is currently deployed on my own vps. However, I might be moving the API to UWaterloo CS Club server in the future because my vps only has 128MB of RAM and 128MB of swap. I was not even able to run bundle install command without running out of memory and get killed by Operating System. This is probably because I am also running two VPN servers and another node API server on that vps.</p><p>The app server I used is puma, and the web server I used is apache. The way I setup everything up was a bit hacky and I am pretty sure there is a better way of doing this. But due to the limitation of memory, compromises had to be made. So I wrote a upstartscript that starts the Rails server when the OS is first booted.(Yes, I am still using Ubuntu 14.04 in 2017) Then the Rails server will listen to a port that I specified. Then I use ProxyPass from apache to set up reverse proxy and expose the internal APIs to /api endpoint. This way I will still be able to have SSL encryption for my Rails API.</p><p>I ran into a bit of troubles with rvm (ruby version manager). Clearly rvm was using some shell macro hacks to export all the binary path. And it appears that upstart scripts are all executed before the scripts in ~/.zshrc was executed. (Yes, I am also using Zsh) As the result, I have to switch my ruby executables from the one provided by rvm to the one provided by the system. (which means reinstall Rails on a single core system with 128MB of RAM)</p><h3>API</h3><p>Currently, the backend server only have three APIs, /blogs , /blogs/:id and /refresh.</p><pre>GET  /api/blogs</pre><p>This returns a list of blog entries from sqlite3 database with only minimum information:</p><pre>[{<br>    &quot;id&quot;: [uint],<br>    &quot;title&quot;: [string],<br>    &quot;preview&quot;: [string],<br>    &quot;date&quot;: [string]<br>},<br>{<br>    ...<br>}]</pre><p>preview field and date field contain the raw string represent the preview of the complete blog and the date that blog was originally written. The id field can be used to retrieve the full blog using /blogs/:id endpoint. Client side js will create a title =&gt; id dictionary when the page is first loaded. When the blog link is clicked, the title of the clicked blog post is cachced and the script on the blog.html page will use this cached value to contruct another fetch query to blogs/:id endpoint.</p><pre>GET  /api/blogs/:id</pre><p>This API endpoint will return detailed information of the requested blog post.</p><pre>{<br>    &quot;id&quot;: [uint],<br>    &quot;title&quot;: [string],<br>    &quot;preview&quot;: [string],<br>    &quot;content&quot;: [string],<br>    &quot;date&quot;: [string],<br>    &quot;created_at&quot;: [string],<br>    &quot;updated_at&quot;: [string]<br>}</pre><p>The response of this endpoint is very similar to previous one. It additionally returns content field, created_at field and updated_at field. The later two fields are automatically created by Rails framework. The content field contains the full blog post in html form.</p><pre>POST /api/refresh</pre><p>/refresh API is currently not open to public. (probably will never be) This endpoint requires an authentication token.</p><pre>{<br>    &quot;auth_token&quot;: [string]<br>}</pre><p>This endpoint bascially gives me a way to upload and edit the blog posts on the server. When /refresh is called, the Rails server deletes all cached compiled blog entries in the sqlite3 database. Then it loops through all the markdown files stored on the filesystem and stored the compiled blog post into database. This endpoint will be deprecated in next version and will be replaced with the proper REST APIs listed below:</p><pre>CREATE /api/blogs<br>PATCH  /api/blogs/:id<br>DELETE /api/blogs/:id</pre><p>Depends on the result of authentication, this endpoint will return one of the two response:</p><pre># Success<br>{<br>    &quot;status&quot;: 200,<br>    &quot;message&quot;: &quot;Database Override&quot;<br>}</pre><p>or</p><pre># Failed <br>{<br>    &quot;status&quot;: 403,<br>    &quot;message&quot;: &quot;Unauthorized&quot;<br>}</pre><p>Authentication token are being stored as an environment variable.</p><h3>What is coming?</h3><p>The currently architecture of this blog is a bit overengineered. I was bascially treating this blogs as a playground to try some of the technologies that I really want to try.</p><p>Next version will be a small functionaility update. The hacky /refresh endpoint will be deprecated and replaced with a proper REST API. Next version will also finish implementing projects.html and add corresponding API endpoints to the server side.</p><p>Afterward I am going to write a web console for myself to manage all the blogs and projects. I probably won’t put the console on public but I will definitely release the source code. I am planning on write this web console using React, because... Well, why not? I have been wanting to try out React for quite a while after using React Native during the hack week back in TD.</p><p>Also, mobile version of the console is coming to iOS, because… I only have an iPhone. I still haven’t decided yet whether should I use React Native or just native SDK.</p><p>Next step, the plan is to replace the current REST API with newer GraphQL API. There is no specific reason for this. I just really want to try it out. I will also probably rewrite the all the html page with React.</p><p>There are few more things that I really want to try on this blog. One is to use either WebGL or process.js to create animations similar to the one the Itseez used to have on their website. I also want to throw OpenCV into this blog somewhere, because of my own obsession with it.</p><p>The source code for both <a href="https://github.com/Azhng/siteV2-frontend">frontend</a> and <a href="https://github.com/Azhng/siteV2-backend">backend</a> are now public on my Github. Code review, pentest and stress test are all welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20aebfc22a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello World]]></title>
            <link>https://medium.com/@archer.xn/hello-world-c6118906f6e5?source=rss-d91cbbf7ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6118906f6e5</guid>
            <category><![CDATA[hello-world]]></category>
            <dc:creator><![CDATA[Archer Zhang]]></dc:creator>
            <pubDate>Mon, 04 Sep 2017 05:22:21 GMT</pubDate>
            <atom:updated>2017-09-04T05:22:21.964Z</atom:updated>
            <content:encoded><![CDATA[<p>(imported from <a href="https://archerzhang.me/blogs/14">https://archerzhang.me/blogs/14</a>)</p><p>I can’t even remember how long have I been helplessly staring at this empty document without doing anything. Trying to figure out what to say for this very first blog post without making myself look like a complete fool. Trying to carefully word every single sentence so that I would look like someone who has received proper literacy eduction. But for a nerd that have spent more time talking to machines than living humans since the age of 15, it’s apparently not a very trivial task. Well, I suppose nothing in life is going to be trivial, isn’t it? So if I make myself look like a complete fool in this post, so be it. It’s easier to learn things when you just treat yourself as an idiot that knows absolutely nothing.</p><p>So if the rest of this post looks more like a core dump from a segmentation fault than the writing from an intelligent human being, please accept my sincere apology. /* I meant it */</p><h3>Who is this blog for?</h3><p>Originally, I started building this blog just for myself. I was trying to start recording the steps that I will be slowly taking over the course of next few years, and maybe give something to myself to laugh at in the future. But I slowly realize this could be the perfect platform to showcase my skill sets and abilities to those who might be interested. It could also provides me with opportunities to connect with people that may share similar interests as me. So feel free to spam my inbox using the email link below and I will be more than happy to discuss about almost anything, including the best text editor in this world. (of course it’s VIM)</p><h3>So, who is this guy?</h3><p>I am an undergraduate CS student at University of Waterloo. A typical Asian math nerd that is socially awkward but also craving for social interactions. A judo orange belt that can’t stop harassing his friends to join the judo club. A coder with weird obsession with OpenCV and functional programming language. And also an idiot that knows nothing but eager to learn.</p><h3>What is the future of this blog?</h3><p>On the technical side, the priority right now is to finish building the project gallery page and the about page. After that my plan is to build a simple server that compiles markdown to html. I will either use Node.js or Ruby on Rails. In the end, I am planning on writing my own markdown-to-html compiler and use it to replace redcarpet compiler that I am currently using.</p><p>For the blog posts, I will probably write another post summarize my experience at TD Lab as an intern this summer before the school starts. After that, I will try to regularly post somethings related to the projects that I will be working on, or just things in my life.</p><p>So, it begins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6118906f6e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>