<?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 Royce Ho on Medium]]></title>
        <description><![CDATA[Stories by Royce Ho on Medium]]></description>
        <link>https://medium.com/@royce963?source=rss-dff7a0264154------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y1jqzOgZrVWd0zB_VkqFYw.jpeg</url>
            <title>Stories by Royce Ho on Medium</title>
            <link>https://medium.com/@royce963?source=rss-dff7a0264154------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:41:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@royce963/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[End to end authorization code test case for Spring Authorization Server using WebClient]]></title>
            <link>https://towardsdev.com/end-to-end-test-cases-for-spring-authorization-server-using-webclient-e3ed0397e036?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ed0397e036</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oauth]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 07:27:59 GMT</pubDate>
            <atom:updated>2024-02-13T01:35:20.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*jJrwxS9hDQBpXkb9.png" /></figure><p>To understand OAuth 2.0 flows, do check out <a href="https://www.oauth.com/playground/">OAuth 2.0 Playground</a> first. Today we look at Authorization Code Flow and how to write a test case that cover that entire flow. Link to my repository can be found below.</p><h3>Why I am writing this article</h3><p>There were several challenges I faced when trying to write the test cases. Firstly, a lot of references found online used <em>MockMvc</em> instead of <em>WebClient</em> to make requests. However, the former has no real HTTP communication while the latter is as close as it is to the real thing. (Nothing wrong with using <em>MockMvc</em> though).</p><p>Secondly, I had to understand HTTP headers and understand session management across requests via JSESSIONID cookie in order to track them through requests. More on this later.</p><p>Hence, it would be good to document my learnings down.</p><h3>Getting started</h3><p>Firstly, you need a spring authorization server up and running. To do so, you can clone my source code from <a href="https://github.com/TheSpaceCuber/spring-authorization-server-sample">here</a>, which is a slightly modified version of the authorization server from the docs <a href="https://docs.spring.io/spring-authorization-server/reference/getting-started.html">Getting Started :: Spring Authorization Server</a>. The reason I did not use their authorization server was because it currently has some issues as of 2024 Feb:</p><ul><li>Throws a <em>No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken </em>error upon user login via Authorization Code Flow. This is fixed by adding a password encoder when hardcoding the user’s password and the client’s secret.</li><li>Uses User.withDefaultPasswordEncoder() which is deprecated. This is fixed by using User.withUsername() instead and using the password encoder separately.</li><li>.csrf(AbstractHttpConfigurer::disable) is required in SecurityFilterChain bean to prevent assertion error (getting 200 OK instead of 302 FOUND after logging in) during JUnit test <em>(Big thanks to my colleague Loh Zi Ying for spotting this issue!)</em></li></ul><p>Secondly, you should have Postman installed for testing the various grant types. Postman has a built-in mechanism for running OAuth 2.0 tests; <a href="https://learning.postman.com/docs/sending-requests/authorization/oauth-20/">Authenticate with OAuth 2.0 authentication in Postman | Postman Learning Center</a>, which will allow you to better understand the HTTP requests made before you write the test cases.</p><h3>Testing on Postman</h3><p>To design the test case, we have to understand the HTTP requests made, and to do so, we can do a Authorization Code Flow test run on Postman and examine the HTTP requests made before converting them into JUnit tests.</p><p>Create a new HTTP request, under Authorization -&gt; Type, select OAuth 2.0 and fill up the blanks accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*canFINX5URTJuSaULEz0OA.png" /><figcaption>Select OAuth 2.0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*qVIeadHdxuTW6Ks1G4wACA.png" /><figcaption>Details can be referenced in SecurityConfig.java</figcaption></figure><p>Start up the authorization server in your IDE (i.e. Intellij). Click on “Get new access token”, enter <em>user</em> and <em>password</em> in the fields respectively when prompted and you should get the token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*8XtBflGIETXMnKgCxNAtcg.png" /></figure><p>Once done, open up the console in Postman and observe the HTTP requests made by Postman and the HTTP codes returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqHnV4Siv4Bvppf9px0k-A.png" /><figcaption>Note the URLs and HTTP status codes</figcaption></figure><p>Take a look at the details of EACH request, there are several HTTP headers that you need to take note of:</p><ul><li>Content-Type — This has to be specified for some requests made in the JUnit test.</li><li>Cookie header (requests) and Set-Cookie header (responses) — If you notice carefully, the JSESSION is the same pre-login but changes post-login. This means these headers have to be explicitly tracked and specified in some of the HTTP requests made in the JUnit test.</li><li>Location — This generally contains the redirect URL that the next request needs to go to.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1-Ny26UukytHREYUiKEYA.png" /><figcaption>Underlining some of the headers of interest</figcaption></figure><h3>Writing the JUnit test</h3><p>Since there are 5 main steps, I broke down the test into 5 parts (still a single test case).</p><ul><li>Step 1: GET /oauth2/authorize</li><li>Step 2: GET /login</li><li>Step 3: POST /login</li><li>Step 4: GET /oauth2/authorize</li><li>Step 5: POST /oauth2/token</li></ul><p>Since the source code is linked, I will only explain step 3’s code snippet.</p><pre>// Step 3: POST /login<br>MultiValueMap&lt;String, String&gt; formData = new LinkedMultiValueMap&lt;&gt;();<br>formData.add(&quot;username&quot;, USERNAME);<br>formData.add(&quot;password&quot;, PASSWORD);<br><br>HttpHeaders loginResponseHeaders = webTestClient.post()<br>  .uri(&quot;/login&quot;)<br>  .header(HttpHeaders.COOKIE, preLoginSetCookieHeader)<br>  .contentType(MediaType.APPLICATION_FORM_URLENCODED)<br>  .bodyValue(formData)<br>  .exchange()<br>  .expectStatus().is3xxRedirection()<br>  .returnResult(String.class)<br>  .getResponseHeaders();<br><br>String postLoginRedirectLocation = loginResponseHeaders.getFirst(HttpHeaders.LOCATION);<br>String postLoginSetCookieHeader = loginResponseHeaders.getFirst(HttpHeaders.SET_COOKIE);</pre><p>Content-Type is specified under:</p><pre>.contentType(MediaType.APPLICATION_FORM_URLENCODED)</pre><p>JSESSION was previously received via a Set-Cookie header in a response, and has to be set as a Cookie header in step 3’s request. We then capture the new JSESSION under loginResponseHeaders once the login is completed.</p><p>That should be all the knowledge required to write the test for authorization code flow and more! You can reference the repository for the full code.</p><p>Github link: <a href="https://github.com/TheSpaceCuber/spring-authorization-server-sample">TheSpaceCuber/spring-authorization-server-sample (github.com)</a></p><h3>Sequence Diagram</h3><p>Use this to better understand and recap the entire flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*9DjUUOtI_BCTByCP" /></figure><h3>What’s next?</h3><p>The above isn’t fully comprehensive, and next steps could include the following:</p><ol><li>Include testing of refresh token</li><li>Validation of token generated</li><li>Tests for other OAuth 2.0 flow</li></ol><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ed0397e036" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/end-to-end-test-cases-for-spring-authorization-server-using-webclient-e3ed0397e036">End to end authorization code test case for Spring Authorization Server using WebClient</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A review and guide for AWS re:Invent]]></title>
            <link>https://medium.com/@royce963/a-review-and-guide-for-aws-re-invent-be94705bcef7?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/be94705bcef7</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 15:08:27 GMT</pubDate>
            <atom:updated>2023-12-24T15:17:27.880Z</atom:updated>
            <content:encoded><![CDATA[<h4>Based on my experience in 2023 (Bonus: ABW Grant information)</h4><p>I attended re:Invent 2023 and had an amazing week of learning new technologies and meeting people from all around the world. This article highlights what to expect at re:Invent, as well as my thoughts on the conference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*KXUTKJpvO9BFRK9M.png" /></figure><h3>Table of Contents</h3><p><a href="#3bcd">1. Hotel Layout</a><br><a href="#cd7a">2. Before the conference</a><br> ∘ <a href="#fb07">Reserved seating</a><br> ∘ <a href="#caa5">If you’re AWS Certified…</a><br> ∘ <a href="#7162">RSVP for Conference Parties</a><br> ∘ <a href="#6752">Arriving early</a><br><a href="#6e92">3. During the Conference</a><br> ∘ <a href="#5ed2">Sessions</a><br> ∘ <a href="#da37">Expo</a><br> ∘ <a href="#9af2">Meals</a><br> ∘ <a href="#d835">Transportation between venues</a><br> ∘ <a href="#a7da">re:Play</a><br><a href="#3300">4. (Bonus) If you are a All Builders Welcome (ABW) Grant Recipient…</a></p><h3>1. Hotel Layout</h3><p>One mistake that I made was not caring about the hotel layout before booking my sessions. It is important to understand where each of the hotels are located due to the travel time between them. For 2023, the conference locations were Encore, Wynn, Venetian, Caesar’s Forum, MGM Grand and Mandalay Bay.</p><p>The expo and keynotes were held at the Venetian, and that area definitely felt like the central hub of the conference. It is probably a good idea to stay near it! MGM Grand and Mandalay Bay are located far away from the rest, so it would be important to not only account for travel times, but to allocate only one or two specific days to travel all the way out there. You don’t want to be heading all the way out to Mandalay Bay everyday as it can tire you out really easily.</p><p>Also, even though shuttle buses are provided, traffic along the strip can become really bad in the evening. For example, I know of people who were stuck in traffic for up to an hour in the evenings, so if you’re heading from Mandalay Bay back to the Venetian, do it before 4pm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgWbji2JyI3aUUEs92Mp5g.png" /><figcaption>2023’s hotel map — Notice how 1,2,3,4 are grouped together, but 5 and 6 are far away</figcaption></figure><h3>2. Before the conference</h3><h4>Reserved seating</h4><p>Reserved seating opens about slightly more than a month before the start of the conference. Even though walk-ins are available, I was turned away twice on my first day due to the number of people queuing for walk-ins for popular sessions. I decided to avoid walk-ins afterwards unless I was sure that I had a good chance to enter. I didn’t want to queue an hour just to be sure that I could walk-in. Reserved seats are given up 10 minutes before the session starts.</p><p>Make sure to plan out your schedule in accordance with the locations way ahead of the conference. But, if you make a mistake of not doing so like me, that’s fine too, you could just go with the flow. I ended up checking which sessions had available slots to reserve the night before (or even an hour before), but of course that means missing out on many of the popular ones. During the conference, there will be people that unreserve their seats to book other sessions as well, so you can refresh the catalog to be on the lookout for new slots released.</p><p>I would say, as a guideline, you only need to have about 2–3 sessions planned for each day. There’s a good chance that you may not follow your schedule as well due to reasons such as lunches, meeting new people or perhaps even genuine mistakes in planning, so don’t try to force yourself to stick tightly to your schedule. Sometimes, the best moments are unplanned. You also should allocate time to yourself to recharge, as well as to walk the expo to collect some swag.</p><h4>If you’re AWS Certified…</h4><p>If you are AWS certified, you should link your certification to your badge. That way, your badge will be printed with a “tick”, which gives you access to AWS Certified SWAG (it was just a tshirt for 2023) and the certification lounge. If your badge doesn’t have a “tick” but you are AWS Certified, the badge counter can help you with it as long as you provide proof via Credly.</p><h4>RSVP for Conference Parties</h4><p>Make sure to use your work email for the conference, as this may attract the attention of companies who want to invite you for some of their parties in the evenings, which usually run from Monday to Wednesday night. Quite a number of parties will be listed at <a href="https://conferenceparties.com/">Conference Parties — Unofficial lists of Conference and Vendor Parties</a>, so you can try to apply for a spot via those links.</p><p>Do note that not all parties are equal. If you’re looking for free dinners at one of these parties, there’s only a few of them so you’ll have to look out for them. Otherwise, most usually serve light food or even none at all, only drinks. This is important as some of these parties are usually 6–9pm, and it can be annoying to be on a hungry stomach throughout. Do note the dress code if there is one required.</p><p>Some of these parties are also unique in nature. For example, I attended a perfume making session at a bar which allowed me to bring back 2 perfumes of my own making! I also managed to attend an invite-only Sphere event for free to watch the <em>Postcard from Earth</em> movie through one of these conference parties, which was amazing given that the tickets were wildly expensive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*3PHeNDBJ7Jl72EcNNbpMNA.png" /><figcaption>On my way to the sphere!</figcaption></figure><p>Of course, you don’t have to attend these events if you find yourself tired from the day, there are a few cheap food options such as at food courts along the strip if you want to save money on dinner as well.</p><h4>Arriving early</h4><p>If it is your first time, it may be good to arrive 1–2 days before the conference to walk around and familiarise yourself, as well as allow your body to adjust to the jet lag if you’re flying from other parts of the world. It is also a great time to have meet people on Sunday as well due to the hectic nature of the conference where everyone has conflicting schedules and is all over the place during the week.</p><h3>3. During the Conference</h3><h4>Sessions</h4><p>You can find a good introduction for the types of sessions <a href="https://www.lacework.com/blog/the-types-of-sessions-at-an-aws-conference-and-why-they-matter/">here</a>. Personally, I preferred hands-on sessions (builders’ sessions and workshops) and level 300 sessions to learn more about technically challenging topics. I didn’t attend any keynotes; I did hear that they are spectacular but can get long and boring (2.5 hours).</p><h4>Expo</h4><p>This is where booth staff will scan your badge to get your email in exchange for swag such as tshirts, plushies etc. Some booths require some tasks to be done, and lucky draws are quite common. I know A LOT of people who won prizes such as mechanical keyboards, bags, drones and more. I would recommend being picky with the swag that you choose, since you don’t want to be filling up your luggage space with swag that you will never use. Also, the first day can be extremely crowded, so you can consider going on the second day onwards only.</p><h4>Meals</h4><p>Breakfast and lunch is provided at most conference hotels, and there are some companies which will hold breakfast and lunch events that you can sign up for. There are takeaway options available, and you can eat at your session as well. As mentioned earlier, you can get free dinners through some of the conference parties but those are rare. I would recommend getting dinners from food courts if you are looking for budget options. Most hotel malls should have their own food court.</p><h4>Transportation between venues</h4><p>Shuttle buses are provided between conference hotels. Uber is an option too. If you’re commuting between Wynn/Encore/Venetian/Caesar’s Forum, you could just walk. Traffic along the strip isn’t really good, and during the evening it can get really bad, so try to avoid commuting by vehicle in the evening!</p><h4>re:Play</h4><p>AWS re:Play is held on thursday night from around 7pm — 12am, and it is a festival where you can eat, party, dance and try out fun activities like dodgeball. They will usually announce the guest lineup during the week of the conference, so look out for that. One of my favourites this year was DataDog’s slide, where participants race each other to run through a bouncy castle and climb up a slide. It can get cold as well since the event is held outdoors, so dress warm.</p><h3>4. (Bonus) If you are a All Builders Welcome (ABW) Grant Recipient…</h3><p>Congratulations! You are now part of a community during AWS re:Invent. Be prepared to meet people from all around the world! Here are some things that you might want to know before the conference based on my 2023 experience:</p><ol><li>The ABW Lounge is a great place to sit down and chill during the conference. You can meet other Grantees in the lounge as well and snacks are provided all the time. If you want to do catch up on work, it is a great place to do so as well.</li><li>There will be some optional but recommended events during the conference, so you have to account for those in your schedule as well. For 2023, there was a luncheon with AWS mentors, an evening ABW reception to party and a closing reception on Thursday where people could share about their stories and how the ABW Grant has helped them. We even had a special guest, Adam Selipsky during the closing reception!</li><li>The hotel that we stayed at, Treasure Island, is opposite the Venetian and convenient! There is gym on the 3rd floor which you can use, as well as get hot water from since there are no kettles provided in the rooms.</li><li>Try to arrive by Sunday afternoon as there is an activity on Sunday night for Grantees to hang out. This is a good time to meet your mentor group and fellow Grantees.</li><li>For 2023, we were all given a unique AWS backpack and it made it easy for us to identify each other during the conference, which in turn allowed for easy conversation starters.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDg3SRrK6HDQQ4JRpd8tCg.png" /><figcaption>My mentor group</figcaption></figure><p>That’s all for now! Have a good one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be94705bcef7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using AWS Lambda, S3 and Secrets Manager to backup RDS as csv files]]></title>
            <link>https://awstip.com/using-aws-lambda-s3-and-secrets-manager-to-backup-rds-as-csv-files-3d6a889a23c4?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d6a889a23c4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 14:03:10 GMT</pubDate>
            <atom:updated>2023-09-22T22:03:27.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*-ts0wR-NQIOrEg3k0srSgQ.png" /></figure><p>This writeup covers the use case of having a secondary backup on top of RDS automated backup (using snapshots) and uses csv files as the backup format. Each csv file represents a single table on the database and all csv files are zipped up to give a single backup entry.</p><p>The overall workflow:</p><ol><li>Lambda function obtains secret (i.e. RDS hostname, username and password) from Secrets Manager</li><li>Connect to RDS</li><li>Read from RDS</li><li>Create CSV files and zip them</li><li>Upload to S3</li></ol><h3>Considerations before getting started</h3><p>Although the general workflow is simple, this writeup is also to document some issues faced / learning points when dealing with the following considerations (which makes for some great learning points).</p><h4>Lambda functions deployed in a specified VPC</h4><p>If you deploy your lambda function in a specified VPC, it will not have access to the internet and AWS services outside of your VPC. This includes S3 and Secrets Manager. You will need to create an S3 VPC gateway endpoint and a Secrets Manager VPC interface endpoint.</p><blockquote>By default, Lambda runs your functions in a secure VPC with access to AWS services and the internet. Lambda owns this VPC, which isn’t connected to your account’s <a href="https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html">default VPC</a>.</blockquote><p>No issues if you create the lambda function by default (no specified VPC) and the lambda function will be able to access S3 and Secrets Manager without any issues.</p><h4>IAM Permissions</h4><p>In order to ensure fine grained access control with the least privilege, we need the following policy as the lambda function’s execution role.</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:GetObject&quot;,<br>        &quot;s3:PutObject&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::my-example-bucket/*&quot;<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: &quot;s3:ListBucket&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::my-example-bucket&quot;<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: &quot;kms:Decrypt&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:kms:${Region}:${Account}:key/${KeyId}&quot;<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: &quot;secretsmanager:GetSecretValue&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:secretsmanager:${Region}:${Account}:secret:${SecretId}&quot;<br>    }<br>  ]<br>}</pre><p><strong>kms:Decrypt</strong> is only necessary if you plan to use a customer managed key (shown later).</p><p>Important: Although <strong>s3:ListBucket</strong> is not necessary (we don’t need to list objects, but it may come in handy), I added it to showcase that <strong>s3:ListBucket</strong> acts on a bucket itself, while <strong>s3:GetObject</strong> and <strong>s3:PutObject</strong> acts on the objects in a bucket, hence the additional /* in the resource field.</p><p>When it comes to creating policies, for some reason, the official <a href="https://awspolicygen.s3.amazonaws.com/policygen.html">AWS Policy Generator</a> does not support /* in its syntax (you have to manually add it), but <a href="https://www.awsiamactions.io/generator">AWS IAM Actions</a> is a good alternative that can do so.</p><h3>Setting up resources</h3><p>We first provision the following resources:</p><ol><li>S3 bucket: Create a standard S3 bucket with default settings.</li><li>RDS instance: Create a MySQL RDS instance (free tier, if necessary, and settings can be default but you can configure accordingly depending on which VPC / security groups / etc) — other RDS instances are fine too.</li><li>Customer Managed Key: Creating one via KMS is optional, as you can use the aws managed key. However, if you do create one, make sure your IAM role for lambda function has <strong>kms:Decrypt</strong>.</li></ol><p>Once the RDS instance is completed, create the secret in secret manager as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Uvz5-0xqx5ARHGwSj3CBBg.png" /><figcaption>Enter your username and password for the RDS instance you created. Choose your own encryption key if you want to use a customer-managed key.</figcaption></figure><h3>Lambda function</h3><p>Next create a lambda function. The sample code covers the workflow, but you are encouraged to read each section and amend accordingly. The sample code assumes the database has already been created and seeded with data.</p><blockquote>If you need to connect to your RDS to seed data, you can use MySQL workbench to do so. If your RDS is public, you can <a href="https://repost.aws/knowledge-center/connect-rds-mysql-workbench">simply connect via the endpoint</a>. If your RDS is non-public (by default), you will need to create an EC2 instance first that has a public ip (AWS charges for public ips, there is no free tier) and follow the instructions to ssh tunnel <a href="https://repost.aws/knowledge-center/rds-mysql-ssh-workbench-connect-ec2">here</a>.</blockquote><p>You can refer to <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-package.html">Working with .zip file archives for Python Lambda functions — AWS Lambda (amazon.com)</a> on how to upload dependencies as we need to use <strong>pymysql</strong>.</p><pre>import pymysql<br>import csv<br>import os<br>import boto3<br>import tempfile<br>import zipfile<br>import datetime<br>import base64<br><br> <br># RDS database settings<br>db_host = os.environ[&#39;DB_HOST&#39;]<br>db_user = os.environ[&#39;DB_USER&#39;]<br>db_name = os.environ[&#39;DB_NAME&#39;]<br><br># S3 bucket settings<br>s3_bucket = os.environ[&#39;S3_BUCKET&#39;]<br># Use a timestamp in the S3 object key<br>timestamp = datetime.datetime.now().strftime(&#39;%Y-%m-%d_%H-%M-%S&#39;)<br>s3_key = f&#39;backup_{timestamp}.zip&#39;<br><br># Your secret&#39;s name and region<br>secret_name = &quot;database-1-secret&quot;<br>region_name = &quot;ap-southeast-1&quot;<br><br>#Set up our Session and Client<br>session = boto3.session.Session()<br>client = session.client(<br>    service_name=&#39;secretsmanager&#39;,<br>    region_name=region_name<br>)<br><br>def lambda_handler(event, context):<br>    try:<br>        # Calling SecretsManager<br>        secret_value_response = client.get_secret_value(<br>            SecretId=secret_name<br>        )<br>        db_password = secret_value_response[&#39;SecretString&#39;]<br><br>        # Connect to the RDS database<br>        conn = pymysql.connect(host=db_host, user=db_user, password=db_password, db=db_name)<br>        <br>        # Create a cursor<br>        cursor = conn.cursor()<br>        <br>        # Execute SQL queries to fetch data from tables<br>        table_queries = {<br>            &#39;user&#39;: &#39;SELECT * FROM user&#39;,<br>            &#39;transaction&#39;: &#39;SELECT * FROM transaction&#39;,<br>        }<br>        <br>        # Create a temporary directory to store CSV files<br>        temp_dir = tempfile.mkdtemp()<br>        <br>        # Fetch and write data to CSV files<br>        for table_name, query in table_queries.items():<br>            cursor.execute(query)<br>            result = cursor.fetchall()<br>            <br>            # Create a CSV file for each table<br>            csv_filename = os.path.join(temp_dir, f&#39;{table_name}.csv&#39;)<br>            with open(csv_filename, &#39;w&#39;, newline=&#39;&#39;) as csv_file:<br>                csv_writer = csv.writer(csv_file)<br>                csv_writer.writerows(result)<br>        <br>        # Create a zip file containing all CSV files<br>        zip_filename = os.path.join(temp_dir, &#39;data.zip&#39;)<br>        with zipfile.ZipFile(zip_filename, &#39;w&#39;, zipfile.ZIP_DEFLATED) as zipf:<br>            for table_name in table_queries.keys():<br>                csv_filename = os.path.join(temp_dir, f&#39;{table_name}.csv&#39;)<br>                zipf.write(csv_filename, f&#39;{table_name}.csv&#39;)<br>        <br>        # Upload the zip file to the S3 bucket<br>        s3_client = boto3.client(&#39;s3&#39;)<br>        s3_client.upload_file(zip_filename, s3_bucket, s3_key)<br>        <br>        return f&quot;CSV data zipped and uploaded to S3 bucket &#39;{s3_bucket}&#39; as &#39;{s3_key}&#39;&quot;<br>        <br>    except Exception as e:<br>        return f&quot;Error: {str(e)}&quot;</pre><p>Since the sample code uses environment variables, you will need to go to Configuration &gt; Environment.</p><p>This should be all that is required. Deploy and run the function.</p><h3>Alternatives for backup</h3><p>You can consider using a RDS proxy as shown here:</p><p><a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-lambda-tutorial.html">Tutorial: Using a Lambda function to access an Amazon RDS database — Amazon Relational Database Service</a></p><p>Additionally, RDS already has automated backups as a feature, hence this may not be necessary. You can also enable cross region replication for s3 or multi-AZ for RDS.</p><h3>References</h3><p><a href="https://stackoverflow.com/questions/48945389/how-could-i-use-aws-lambda-to-write-file-to-s3-python">amazon web services — How could I use aws lambda to write file to s3 (python)? — Stack Overflow</a></p><p><a href="https://beabetterdev.com/2022/11/26/aws-lambda-and-secrets-manager-tutorial-in-python/">AWS Lambda and Secrets Manager Tutorial in Python — Be a Better Dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d6a889a23c4" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/using-aws-lambda-s3-and-secrets-manager-to-backup-rds-as-csv-files-3d6a889a23c4">Using AWS Lambda, S3 and Secrets Manager to backup RDS as csv files</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NUS Module Reviews: CS3203, CS4218, IS4302]]></title>
            <link>https://medium.com/@royce963/nus-module-reviews-cs3203-cs4218-is4302-40a9e6676a86?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a9e6676a86</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[students]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[university]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Wed, 03 May 2023 08:56:14 GMT</pubDate>
            <atom:updated>2023-05-03T08:56:14.378Z</atom:updated>
            <content:encoded><![CDATA[<p>These modules were taken during AY2022/23 Semester 2 and all opinions are my own and do not represent the views of NUS. I only took these 3 modules for this semester as well.</p><ul><li>CS3203 Software Engineering Project</li><li>CS4218 Software Testing</li><li>IS4302 Blockchain and Distributed Ledger Technologies</li></ul><h3>CS3203 Software Engineering Project</h3><p>One of the heaviest modules ever from week 3–8 (even the Professor admitted it could feel like 16–20MCs), especially if you’re an average student in an average team. But also, where you’ll learn a lot through coding and software design. You’ll have to team up with 2 others and will get paired with another subgroup to form a team of 6 where you’ll work with for the project through sprints.</p><ul><li>1 intro lecture, 1 closing lecture</li><li>2hr classes from week 3–8 (if i remember correctly)</li><li>1 weekly retrospective/standup with TA</li><li>1 group test</li><li>2 take home assignments</li><li>2 presentations</li><li>3 project milestones (code and report submissions)</li></ul><p>This module mainly consists of learning a “made up” basic programming language called SIMPLE (think Python but stripped down) and designing a Static Program Analyzer (SPA) that has 3 major components:</p><ul><li>Source Processor (SP): Generally, consists of a parser that takes in a source code and builds an abstract syntax tree (AST), and a design extractor that traverses the tree to extract design abstractions (relationships between various lines and variables) and inserts them into the PKB.</li><li>Program Knowledge Base (PKB): Essentially a database of relationships in the source code.</li><li>Query Processing Subsystem (QPS): Takes in a “made up” query language (think of SQL), that queries out relationships in the source code, by interacting with the PKB. Consists of a pre-processor that parses the query to build a query object and an evaluator that uses the query object to extract information from the PKB before returning the output.</li><li>Testing: Testing isn’t part of SPA, but you’ll need to write unit, integration and system tests if you want to score on correctness. Other types of tests, such as end-to-end tests, load tests, stress tests can be helpful too.</li></ul><p>The initial learning curve was insane, especially working with a greenfield C++ project that is cross platform (Mac/Windows) and turning grammar rules into various tree node classes in the abstract syntax tree, as well as creating a design extractor that visits the tree to extract out all the required relationships between the nodes. This was what I did (Design Extractor), and would differ for each member. The workload of each component differs as well throughout the semester, with SP being extremely heavy for the first project milestone, QPS being heavy for the final milestone, and PKB being medium throughout.</p><p>In terms of coding, designing and writing tests, you will be doing a lot of those, which is great (CS2103T and CS3219 doesn’t come close at all). Having to discuss interfaces and APIs within components was a tough but fruitful experience, and the project requirements revealed the importance of writing tests as well. Continuous Integration (CI) is also really helpful, so it’s good to have that going right out of the box.</p><p>For my semester, lectures were converted to classroom activities, where we prepared for the content before coming, and if i recall correctly, the last class was in week 8, no need to come school after that. The Professor (Ganesh) is new to the module as well, and seeks to improve it with feedback (one of the assignments was cancelled due to complains of high workload in week 7). The report now has very few pages needed, and no slides are required for the 2 presentations in the module (just use the report).</p><p>Overall, this is a useful mod if you’ve only taken CS2103T/CS2103 and/or CS3219 but beware of the workload. Most likely there will be continuous improvements over the next semesters (after my conversation with the Professor at the end of the module).</p><h3>CS4218 Software Testing</h3><p>This module has a project component which took up 40%, as well as lectures and labs.</p><ul><li>Lectures</li><li>Labs (I think they became optional consult sessions after week 9, attending 4 of them gives you max attendance score)</li><li>1 Project</li><li>1 “Hackathon” period where you find bugs in other teams’ project submissions</li><li>1 final exam</li></ul><p>Because all lecture content was only tested for finals (perhaps a little useful during the project), I did not watch any of them at all. Rather I focused on the project, which was a buggy and partially implement shell written in Java. For finals preparation it was possible to start with PYP straightaway and use ChatGPT to pick up concepts quickly.</p><p>Writing tests is related to understanding relationships in a program’s source code, so I would say CS3203 helped a lot in understanding some of the content, such as control flow graphs and def-use pairs. This module runs through all the types of testing, namely a few include:</p><ul><li>Unit, Integration, End to End</li><li>System</li><li>Load, Stress</li><li>White Box, Black Box</li><li>Structural, Requirements</li><li>Performance</li></ul><p>If not for the project and the importance of testing in software engineering, this module would be quite useless. Fortunately, it is good to have exposure to a lot of the concepts taught, and the nature of the project forces you to write test cases in a new way compared to past modules (i.e. taking into account different types of code coverage, pairwise testing), making this one of the modules where you might actually use what you learnt in the future as a software engineer.</p><h3>IS4302 Blockchain and Distributed Ledger Technologies</h3><p>I took this module because I did a Defi take home assignment from a defi algorithmic trading firm and found it interesting. But after this module, I would say my interest has declined a lot…mainly because I feel like I didn’t learn anything useful.</p><ul><li>Project</li><li>Midterms (it’s a practical exam to write smart contracts)</li><li>4 Labs</li><li>Lectures</li><li>3 written assignments</li></ul><p>I don’t think this is a very good module because the labs are basically a solidity/smart contract tutorial which you can do online. The written assignments are simply short essays to some problems in crypto and Defi, partially interesting but I had already learnt about them during my take home assignment. The project was extremely vague (no project requirements PDF) was even given, and I have no idea how it is going to be graded.</p><p>Also, solidity development with truffle didn’t really feel enjoyable, but perhaps that’s something personal.</p><p>That’s all I have for module reviews for this semester!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a9e6676a86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NUS Module Reviews: CS3230, CS3219, GET1029]]></title>
            <link>https://medium.com/@royce963/nus-module-reviews-cs3230-cs3219-get1029-c37fb7f6af6d?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37fb7f6af6d</guid>
            <category><![CDATA[students]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[university]]></category>
            <category><![CDATA[review]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 07:00:00 GMT</pubDate>
            <atom:updated>2022-12-09T07:01:19.964Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://nusmods.com/modules/CS3230/design-and-analysis-of-algorithms">Design and Analysis of Algorithms</a> (CS3230), <a href="https://nusmods.com/modules/CS3219/software-engineering-principles-and-patterns">Software Engineering Principles and Patterns</a> (CS3219), <a href="https://nusmods.com/modules/GET1029/life-the-universe-and-everything">Life, the Universe, and Everything</a> (GET1029)</h4><p>These modules were taken for AY2022/23 Semester 1 and may not reflect subsequent/other semesters. All opinions are my own. I also underloaded (again) for this semester with 3 mods (12 credits).</p><h3>CS3230</h3><p>This module was more interesting than I expected (I was dreading all the math and proving) but still proved to be as difficult as I thought it was. We had weekly assignments that needed to be submitted on top of weekly tutorials, as well as 1 midterms and 1 finals. There were 2 optional programming assignments, one of which was a codeforces problem.</p><p>Some of the topics that you would learn about include:</p><ul><li>Asymptotic analysis</li><li>Divide and conquer</li><li>Randomized algorithms</li><li>Hashing (Universal hashing)</li><li>Amortized analysis</li><li>Dynamic programming</li><li>Greedy algorithms</li><li>Incremental algorithms (i.e. Flow networks — Ford Fulkerson)</li><li>Linear programming</li><li>Reductions (converting one problem into another)</li><li>P vs NP</li><li>Approximation algorithms</li></ul><p>Some of the topics were closely related, meaning gaps in knowledge could quickly snowball. For example, reductions are used in converting various problems to other problems when learning about NP/NP-Complete/NP-Hard problems. It was then followed up with how we could come up with faster solutions to non-polynomial problems through approximations (I still didn’t really learn this as I was too slow).</p><p>Attendance was not marked for tutorials and lectures were hybrid in nature (some of which were really hard to understand, watching MIT OpenCourseWare made it slightly better).</p><h3>CS3219</h3><p>A very practical module focused on designing systems/software and web applications. Unfortunately, I did not manage to bid for this in year 3. This module has weekly tutorials, some lecture quizzes, OTOT individual assignments, 1 group project and 1 final exam.</p><h4>Group project</h4><p>Students have to form a group of 4 by themselves and work on a web app called “Peerprep”, which matches students in pairs to work on a collaborative coding interview with one student acting as an interviewer and another as the interviewee. The module provides guidance on how to develop the web app (i.e. microservice architecture, tech stack, etc) but it is up to the group to decide whether they want to follow it. You’ll learn about various frontend, backend, database, DevOps, and cloud technologies, which may include (as in my case): ReactJS, NodeJS, ExpressJS, MongoDB, Docker and Redis.</p><h4>OTOT assignments</h4><p>These individual assignments are released at the start of the semester and students have to submit them sometime near the end of the semester. They include learning about technologies such as:</p><ul><li>Kubernetes</li><li>Docker</li><li>JWT, Bcrypt</li><li>Kafka</li><li>Redis</li><li>Frontend/Backend</li><li>Serverless functions</li></ul><p>Essentially some of these technologies will be used in your group project, so it would be helpful to focus on some of them first.</p><h4>Lecture/Exam content</h4><p>The rest of the module focuses on aspects such as learning about architectures and patterns such as</p><ul><li>Microservices</li><li>Messaging patterns</li><li>Design patterns (this is important! although sadly, it was the last lecture)</li></ul><h3>GET1029</h3><p>This philosophy module covers the breadth and foundations, with topics such as:</p><ul><li>Right and wrong</li><li>Goodness and Pleasure</li><li>Eating meat</li><li>Governments (Statism &amp; Anarchism)</li><li>Free will</li><li>The problem of Evil (God and Evil in this world)</li><li>Mind and Body (Materialism vs Dualism)</li><li>Simulation theory</li><li>The self (Does the self endure?)</li></ul><p>Weekly quizzes were difficult but didn’t require much time unless you really wanted to get full marks. I did not read the mandatory readings so I’m not sure if they were actually useful. Tutorials were really chill, you do not have to prepare anything beforehand (although that would definitely help). There was 1 final exam (MCQ) where about 50% of the students left before it ended, and that was about it.</p><p>Low workload module in my opinion where some lectures could be skipped and read up upon instead. There is one thing to take note: the prof may not necessarily agree with what you find on the internet, hence his answers may differ.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37fb7f6af6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VPC Architecture Design & Deployment for a basic 3-Tier Web Application (React/Node/MySQL)]]></title>
            <link>https://awstip.com/vpc-architecture-design-deployment-for-a-basic-3-tier-web-application-react-node-mysql-8e3453a4204b?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3453a4204b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Sat, 25 Jun 2022 11:28:49 GMT</pubDate>
            <atom:updated>2022-07-07T10:33:50.479Z</atom:updated>
            <content:encoded><![CDATA[<h4>Separating a web app into 3 separate instances across a VPC</h4><p>This article outlines the process of deploying a web application onto AWS in a VPC with a public and private subnet, and how the frontend, backend and database connects together, as well as pitfalls I encountered during my journey.</p><p>To deploy a React/Node/MySQL application on a single EC2 instance, please see my other article <a href="https://towardsdev.com/deploying-a-react-node-mysql-app-to-aws-ec2-2022-1dfc98496acf">here</a>. I would suggest reading that before coming over here.</p><p>To check out the repository I used, see <a href="https://github.com/TheSpaceCuber/webappdemo">here</a>. Note that this is a general guide for ubuntu-based systems, not a detailed step-by-step process example. But this applies to the repo highlighted, so you may refer to the repo as well.</p><h3>Cloud Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*_1Ncfutz1wRXsbGx" /><figcaption>This is the setup that we’re going for today.</figcaption></figure><h4>Virtual Private Cloud (VPC)</h4><p>We create a <a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario2.html">VPC with public and private subnets</a>, where our App Server (Node) and Database Server (MySQL) will reside in the private subnet, and the Web Server will reside in the public subnet.</p><p>Let’s breakdown the components in our VPC:</p><ul><li>Internet Gateway (IGW): This allows for traffic to move between the internet and the VPC.</li><li>NAT Gateway: Allows for EC2 instances in private subnets to connect to the internet or services outside the VPC, but external services cannot initiate a connection with those instances.</li><li>Subnets: 1 public subnet and 1 private subnet.</li><li>Route Tables: Not included in the diagram, each subnet requires a route table. Please see here for more <a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario2.html#:~:text=The%20main%20route%20table%20associated,the%20NAT%20gateway%20over%20IPv4.">info</a>.</li><li>Web Server: This is where our frontend React app and Nginx web server lie. Ideally React can be stored in an S3 bucket to serve static files, but we can store it in EC2 also.</li><li>App Server: This is where the Node server runs. It will handle API calls from the front end and make requests to the database accordingly.</li><li>Database Server: This is where MySQL is installed. You could use other types of DBs as well.</li><li>Security groups: This is not reflected in the diagram, but each EC2 instance should have a security group that allows the TCP ports in the diagram to be open, as well as port 22 for SSH in case you need to troubleshoot.</li></ul><p>There are a lot of details missing here which I may add at a later date, but if you would like to see the exact config of the VPC, you may refer to my terraform files <a href="https://github.com/TheSpaceCuber/webappdemo/tree/main/terraform">here</a>.</p><p>You may also notice that the image has the server addresses of the App and Database instances. You can ignore it here as the following instructions will guide you to use whatever private IP is there. Of course, you may explicitly define the private IP upon instance launch in a VPC as per the image, which is what I did.</p><h3>Web server — Nginx</h3><p>Nginx acts as a <a href="https://www.cloudflare.com/learning/cdn/glossary/reverse-proxy/">reverse proxy</a> and we’ll need to point the requests for the app server to the private IP of the instance itself. SSH into the Web instance first.</p><pre>sudo vim /etc/nginx/sites-available/default</pre><p>Edit the config file to proxy API requests over to the private IP address of the App instance by adding proxy_pass . You can get the IP address of the backend server by going to EC2 Dashboard → Instances → Select your instance → See details or networking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*KtydCCLF5km6gkeFMp3hfw.png" /><figcaption>Requests with /api at the start will be proxied over to the App instance. For example, /api/read. Remember to specify the port as well, in this case it is 8081.</figcaption></figure><p>Next, restart or reload nginx.</p><pre>sudo systemctl restart nginx</pre><h3>Database Server — MySQL</h3><p>Next, before we start the App server, we need to make sure that the DB instance can accept MySQL connections from another instance.</p><p>If you do not have MySQL installed on your DB instance, this is the example I used in my repo to create a database for employee data.</p><pre>sudo apt update<br>sudo apt install -y mysql-server<br>sudo mysql -e &quot;CREATE DATABASE employee_db;&quot;<br>sudo mysql -e &quot;USE employee_db; CREATE TABLE employees ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(150) NOT NULL, description VARCHAR(150) NOT NULL, age INT NOT NULL, PRIMARY KEY (id) );&quot;</pre><pre># to enter the mysql database<br>sudo mysql</pre><h4>Create a user for remote access</h4><p>You need to create a user that can remotely access MySQL</p><pre>CREATE USER &#39;myuser&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;mypass&#39;;<br>CREATE USER &#39;myuser&#39;@&#39;%&#39; IDENTIFIED BY &#39;mypass&#39;;</pre><pre>GRANT ALL ON *.* TO &#39;myuser&#39;@&#39;localhost&#39;;<br>GRANT ALL ON *.* TO &#39;myuser&#39;@&#39;%&#39;;<br>FLUSH PRIVILEGES;</pre><p><a href="https://stackoverflow.com/questions/16287559/mysql-adding-user-for-remote-access">Mysql adding user for remote access</a></p><h4>Change bind-address</h4><p>Next, you need to ensure that the MySQL server can accept connections from external services as currently it only allows localhost connections. You may do this by editing the bind-address at /etc/mysql/mysql.conf.d/mysqld.cnf .</p><pre>sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf</pre><p>Edit the bind-address to accept all connections.</p><pre># change from <br>bind-address = 127.0.0.1</pre><pre># change to<br>bind-address = 0.0.0.0</pre><p>You may read up more here:</p><p><a href="https://stackoverflow.com/questions/9766014/connect-to-mysql-on-amazon-ec2-from-a-remote-server">Connect to mysql on Amazon EC2 from a remote server</a></p><p>Now your DB should be able to accept incoming connections.</p><h3>App Server — Node</h3><p>Now, you can SSH into the app server, and point the MySQL connection at the database instance,</p><pre>const db = mysql2.createConnection({<br>    user: &quot;myuser&quot;,<br>    host: &quot;localhost&quot;, // REPLACE WITH DB SERVER PRIVATE IP ADDRESS<br>    password: &quot;mypass&quot;,<br>    database: &quot;employee_db&quot;<br>})</pre><p>and use <a href="https://pm2.keymetrics.io/docs/usage/quick-start/">pm2</a> to start the backend service.</p><pre>pm2 start index.js</pre><p>You may check the status of pm2 in case any errors occur.</p><pre>pm2 status</pre><h3>Troubleshooting</h3><p>More than often, you may face issues with connectivity.</p><ol><li>Try using the <a href="https://docs.aws.amazon.com/vpc/latest/reachability/what-is-reachability-analyzer.html">reachability analyser</a>. This helps you to pinpoint where exactly is the connection broken.</li><li>Check server logs. For Nginx, see /var/log/nginx/error.log .</li><li>Check security groups.</li></ol><p>All the best!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3453a4204b" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/vpc-architecture-design-deployment-for-a-basic-3-tier-web-application-react-node-mysql-8e3453a4204b">VPC Architecture Design &amp; Deployment for a basic 3-Tier Web Application (React/Node/MySQL)</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a React/Node/MySQL app to Amazon EC2 (2022)]]></title>
            <link>https://towardsdev.com/deploying-a-react-node-mysql-app-to-aws-ec2-2022-1dfc98496acf?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dfc98496acf</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 07:17:45 GMT</pubDate>
            <atom:updated>2022-10-29T12:12:03.420Z</atom:updated>
            <content:encoded><![CDATA[<p>Documenting this because of troubles faced during my deployment attempts.</p><p>This article outlines the process of deploying a full-stack application using ReactJS as the front-end, NodeJs as the back-end and MySQL as the database, as well as potential issues faced along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MztKM1jAK7ztCjn3uloVeQ.png" /></figure><h3>1. Launch EC2 instance</h3><p>In AWS console, go to the EC2 Dashboard → Instances → Launch Instances.</p><p>Use the following configuration:</p><ul><li>AMI: Ubuntu Server 22.04 LTS (20.04, 18.04, 16.04 is fine as well)</li><li>Instance Type: T2.micro (other instance types work as well, but this is in the free tier)</li><li>Network:<br>- Leave the VPC as the default one for convenience (or change it)<br>- Create a new security group that allows SSH, HTTP and HTTPS traffic from anywhere, or use an existing one that meets the same criteria<br>- Select a key pair (Do not proceed without one)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*aAGdHPeVyS7xzdmd4Zobdg.png" /></figure><p>Click on Launch instance.</p><h3>2. SSH into instance</h3><ol><li>Click on instance, then “connect”.</li><li>See instructions for connecting via SSH.</li></ol><h3>3. Install Nginx, Git and Node</h3><p>Nginx acts as a web server and a <a href="https://www.nginx.com/resources/glossary/reverse-proxy-server/">reverse proxy</a>. In this article, we will open port 80 for HTTP requests to enter from the web. Given that there is only one incoming port (80) but 2 services (frontend and backend), a reverse proxy acts as an abstraction to direct requests to 2 different ports (3000 for frontend and 8081 for backend in this example). This <a href="https://adhasmana.medium.com/how-to-deploy-react-and-node-app-on-aws-a-better-approach-5b22e2ed2da2">article</a> gives a good overview.</p><p>We use git to pull in our source code from GitHub, and Node is required for our backend.</p><pre># update/refresh the list of available packages<br>sudo apt update</pre><pre># install git to pull repo from github<br>sudo apt install git</pre><pre># install node 16.x<br>cd ~<br>curl -sL https://deb.nodesource.com/setup_16.x -o /tmp/nodesource_setup.sh<br>sudo bash /tmp/nodesource_setup.sh<br>sudo apt install nodejs</pre><pre># install nginx as reverse proxy &amp; web server<br>sudo apt install -y nginx</pre><pre># nginx should&#39;ve started, this is optional<br>sudo systemctl start nginx</pre><p>Fun fact: When installing dependencies, apt is the newer version of apt-get. See <a href="# https://embeddedinventor.com/apt-update-vs-apt-get-update-differences-explained/">here</a>.</p><p><strong>Troubleshooting -</strong> Check Nginx status or error logs or restart the service:</p><p>service nginx status</p><p>sudo cat /var/log/nginx/error.log</p><p>sudo systemctl restart nginx</p><p><a href="https://stackoverflow.com/questions/35868976/nginx-service-failed-because-the-control-process-exited">nginx.service failed because the control process exited</a></p><p>In the AWS console, under your EC2 instance, click on your public IPV4 DNS address. If you see the Nginx welcome page, you’re on the right track and nginx is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MZnH1qb08xeFrCtT.png" /><figcaption>Default nginx page</figcaption></figure><h3>4. Clone repository and install dependencies</h3><pre>git clone https://github.com/TheSpaceCuber/webappdemo.git </pre><pre># install front-end node dependecies &amp; create build folder<br>cd webappdemo/client <br>sudo npm install<br>sudo npm run build</pre><pre># install back-end dependencies<br>cd ../backend/ &amp;&amp; sudo npm install</pre><p>If you’re not sure about npm run build for React, see <a href="https://stackoverflow.com/questions/43830866/what-is-npm-run-build-in-create-react-app">here</a>.</p><p>The current directory structure should look something like:</p><pre>webappdemo/<br>    client/<br>        ...<br>        build/<br>            index.html<br>    backend/ <br>        ...<br>        index.js</pre><p>We want to point Nginx at the index.html file for frontend, and launch index.js for backend.</p><p>Copy the build folder over to the directory /var/www/ . The reason for this is explained in part 6 later.</p><pre>cp -R /home/ubuntu/webappdemo/client/build /var/www</pre><h3>5. Configure Nginx sites-available/default</h3><pre>sudo vim /etc/nginx/sites-available/default</pre><p>Use the following configuration:</p><pre>server {<br>    listen 80 default_server;<br>    listen [::]:80 default_server;</pre><pre>    # We want the root folder to point at index.html<br>    root /var/www/build;<br>    index index.html index.htm index.nginx-debian.html;<br><br>    server_name _;<br><br>    location / {<br>        # First attempt to serve request as file, then<br>        # as directory, then fall back to displaying a 404.<br>        try_files $uri /index.html $uri/ =404;<br>    }<br>    <br>    location /api {<br>        proxy_pass http://localhost:8081;<br>    }<br>}</pre><p>Note: Do not miss out on “;”. Check the logs if there are issues with Nginx using the command sudo cat /var/log/nginx/error.log</p><h4>Explanation of the above file</h4><ul><li>80 represents the HTTP port which Nginx listens for web traffic</li><li>root sets the directory for requests. In other words, usually your root file (index.html) should be in the folder. In this case, it is in our build folder for React.</li><li>server_name does not need to change, as there is only one server block. See <a href="https://nginx.org/en/docs/http/server_names.html">here</a> for more info.</li><li>location / and location /api specifies the configuration based on a request URI. In this case, the latter means that all requests with a prefix of /api will be proxied to the Node server.</li></ul><h4>References for Nginx config:</h4><ul><li><a href="https://dev.to/asim_ansari7/deploy-a-react-node-app-to-production-on-aws-2gdf">https://dev.to/asim_ansari7/deploy-a-react-node-app-to-production-on-aws-2gdf</a></li><li><a href="https://jasonwatmore.com/post/2019/11/18/react-nodejs-on-aws-how-to-deploy-a-mern-stack-app-to-amazon-ec2">https://jasonwatmore.com/post/2019/11/18/react-nodejs-on-aws-how-to-deploy-a-mern-stack-app-to-amazon-ec2</a></li></ul><h3>6. Give write permission to the app folder</h3><p>Skip this command, see the update for 19/6/2022 below.</p><pre>s̶u̶d̶o̶ ̶c̶h̶m̶o̶d̶ ̶7̶7̶7̶ ̶w̶e̶b̶a̶p̶p̶d̶e̶m̶o̶</pre><p>̶I̶ ̶b̶e̶l̶i̶e̶v̶e̶ ̶t̶h̶a̶t̶ ̶y̶o̶u̶ ̶m̶a̶y̶ ̶n̶e̶e̶d̶ ̶t̶o̶ ̶d̶o̶ ̶t̶h̶e̶ ̶s̶a̶m̶e̶ ̶f̶o̶r̶ ̶c̶h̶i̶l̶d̶ ̶d̶i̶r̶e̶c̶t̶o̶r̶i̶e̶s̶ ̶o̶f̶ ̶t̶h̶e̶ ̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶.̶ ̶Y̶o̶u̶ ̶c̶a̶n̶ ̶c̶h̶e̶c̶k̶ ̶n̶g̶i̶n̶x̶ ̶l̶o̶g̶s̶ ̶f̶o̶r̶ ̶a̶n̶y̶ ̶p̶e̶r̶m̶i̶s̶s̶i̶o̶n̶ ̶i̶s̶s̶u̶e̶s̶ ̶i̶f̶ ̶f̶a̶c̶e̶d̶ ̶a̶n̶d̶ ̶t̶r̶a̶c̶e̶ ̶t̶h̶e̶ ̶p̶a̶t̶h̶ ̶r̶e̶q̶u̶i̶r̶e̶d̶.̶</p><p>sudo cat /var/log/nginx/error.log to check nginx logs.</p><h4>Update 19/6/2022:</h4><p>After reading this post:</p><p><a href="https://stackoverflow.com/questions/25774999/nginx-stat-failed-13-permission-denied">Nginx: stat() failed (13: permission denied)</a></p><p>It seems like it is better to copy the build folder containing index.html into /var/www/ instead, where there is already read permission for web users to access the files. I’ve updated the nginx/sites-available/default file above and added an extra step to copy the build folder over to /var/www.</p><h3>7. Install and Configure MySQL + Possible Trouble</h3><pre>sudo apt install -y mysql-server</pre><pre>sudo mysql</pre><pre>ALTER USER &#39;root&#39;@&#39;localhost&#39; IDENTIFIED WITH mysql_native_password BY &#39;your_password_here&#39;;</pre><pre>FLUSH PRIVILEGES;</pre><p>Reference: <a href="https://towardsdatascience.com/running-mysql-databases-on-aws-ec2-a-tutorial-for-beginners-4301faa0c247">https://towardsdatascience.com/running-mysql-databases-on-aws-ec2-a-tutorial-for-beginners-4301faa0c247</a></p><h4>Fix the password issue</h4><p>Check out the following link first as you will likely face authentication issues on the backend with the database.</p><p><a href="https://stackoverflow.com/questions/39281594/error-1698-28000-access-denied-for-user-rootlocalhost">ERROR 1698 (28000): Access denied for user &#39;root&#39;@&#39;localhost&#39;</a></p><p>I used the first option:</p><pre>sudo mysql -u root # I had to use &quot;sudo&quot; since it was a new installation<br><br>mysql&gt; USE mysql;<br>mysql&gt; UPDATE user SET plugin=&#39;mysql_native_password&#39; WHERE User=&#39;root&#39;;<br>mysql&gt; FLUSH PRIVILEGES;<br>mysql&gt; exit;<br><br>sudo service mysql restart</pre><h4>Set your password</h4><pre>sudo mysql<br>mysql&gt; ALTER USER &#39;root&#39;@&#39;localhost&#39; IDENTIFIED WITH mysql_native_password BY &#39;your_password_here&#39;;mysql&gt; FLUSH PRIVILEGES;<br>mysql&gt; exit<br>mysql -u root -p # enter your password when prompted</pre><p>If you can log in to mysql, you can move on.</p><h4>Create employee table</h4><p>This is for the current repository used, you may ignore if you are using a different database schema.</p><pre>mysql -u root -p # enter mysql server</pre><pre>mysql&gt; CREATE DATABASE employee_db;</pre><pre>mysql&gt; USE DATABASE employee_db;</pre><pre><br>mysql&gt; CREATE TABLE employees</pre><pre>(</pre><pre>id INT NOT NULL AUTO_INCREMENT,</pre><pre>name VARCHAR(150) NOT NULL,</pre><pre>description VARCHAR(150) NOT NULL,</pre><pre>age INT NOT NULL,</pre><pre>PRIMARY KEY (id)</pre><pre>);</pre><h3>8. Install pm2</h3><p>PM2 is an acronym of Process Management Module which is used to run and manage Node applications. It’s an open-source with an in-built load balancer. When a process goes down, PM2 will automatically restart the service and make it live.</p><pre>npm install pm2 -g</pre><pre>pm2 start index.js</pre><pre>pm2 status</pre><p>Ensure that the status has no ERROR. If there is, you could use tmux to troubleshoot since pm2 doesn’t show any logs normally.</p><pre>tmux</pre><pre># while in the backend directory, start the node server<br>node index.js</pre><h3>9. Check website</h3><p>If everything goes well, check the public IPv4 DNS address of the EC2 instance from the AWS console. It should show your web application.</p><h3>10. If something isn’t right…</h3><ul><li>Check Nginx &amp; Pm2 status</li><li>Check browser console</li><li>Check Nginx logs</li><li>If you have a CORS error, ensure that the port numbers are correct and that your backend uses CORS.</li></ul><p>Good luck in your deployment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dfc98496acf" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/deploying-a-react-node-mysql-app-to-aws-ec2-2022-1dfc98496acf">Deploying a React/Node/MySQL app to Amazon EC2 (2022)</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Module Reviews: Year 3 in NUS Computer Science]]></title>
            <link>https://medium.com/@royce963/my-year-3-semester-2-review-for-nus-computer-science-d9ce65c2181b?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ce65c2181b</guid>
            <category><![CDATA[students]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[university]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Sat, 30 Apr 2022 07:41:20 GMT</pubDate>
            <atom:updated>2022-05-04T13:09:14.265Z</atom:updated>
            <content:encoded><![CDATA[<h4>Taking only 3 modules for the first time</h4><p>This week marks the final week of the semester, as well as the end of my third year at the National University of Singapore. During the semester, I underloaded and took a total of 3 modules (yes, you can do that!), while doing a part-time internship (not credit-bearing) at GovTech Singapore, making academics for this semester drastically different from the past semester. And I’m glad to say that my third year has been much more relaxed compared to my first two years in NUS.</p><h4>The modules that I took this semester (Year 3 Semester 2) were:</h4><ul><li>CS5224 Cloud Computing</li><li>CS4225 Big Data Systems for Data Science</li><li>LSM1303 Animal Behaviour</li></ul><h3>CS5224 Cloud Computing</h3><p>(Note: This module is offered for postgraduate students, but undergraduates are still able to bid/appeal for it in later rounds).</p><p>This module covered the basics of cloud computing, following the textbook <em>Essentials of Cloud Computing</em> by K. Chandrasekaran. Some of the topics covered ranged from understanding cloud architectures and data centres to virtualization and various cloud service models (IaaS vs PaaS vs SaaS vs FaaS). Throughout the module, we had weekly lectures, 6 quizzes, 4 guided AWS labs, 2 AWS lab assignments, and 1 project which involved the development of a web application using any cloud provider’s services.</p><p>As I had previously covered quite a bit during my preparation for the AWS Solutions Architect Associate exam, the contents of this module were relatively easy due to many overlapping concepts, although the module mainly covered general cloud concepts, rather than focusing on one particular cloud provider such as AWS. This module felt very different from previously foundational modules, as it covered high-level concepts and industry applicable concepts, and we were able to understand the architectures that many companies use today in the real world. We were also given AWS accounts with $75 worth of credits for our labs and projects, which meant that we were able to try out paid services without worrying about costs, although I have to say that there were definitely some who exceeded them (not sure if they had to pay the extra!).</p><p>The content for this module felt very conceptual, yet at the same time applicable for understanding cloud computing today, given that it is a large field that continuously grows, as seen from the insane growth in revenue for the cloud providers. Although, I have to say that a very good alternative would just be to clear the AWS SAA exam instead, given that you’ll receive a useful certificate at the end while understanding cloud concepts in-depth as well. Yet, CS5224 is one of the few mods in NUS that I enjoyed!</p><h3>CS4225 Big Data Systems for Data Science</h3><p>Another module that I looked forward to taking since my first year, CS4225 covers the various types of databases that are used in the industry today, as well as the platforms and processing techniques used to handle big data. For databases, there was an overview of the various types of NoSQL databases used, which opened my eyes to how large the world of NoSQL was. I previously thought that NoSQL was solely about key-value storage, while SQL was relational. But NoSQL extends far more than that, from graph databases to column-oriented databases. We had weekly lectures and tutorials (the TA didn’t even show up for the first tutorial with 200+ attendees on zoom LOL), as well as 2 assignments on Hadoop followed by Spark and 1 group project on building a data lake.</p><p>For the assignment on Hadoop, we first learned about the basics of MapReduce and worked on the variation of the WordCount program as seen <a href="https://hadoop.apache.org/docs/stable/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html">here</a>. For the second assignment, we used Spark to process an OSM map of NUS and had to process the road data into an adjacency list, followed by finding a path between any 2 given nodes in the map. Overall, both assignments were relatively difficult as little information was given to us, and we had to code out the Spark program in Java while most documentation found online was in Python and Scala, which made things annoying.</p><p>The project to build a data lake was interesting as we were given free roam to design a data science project as we see fit (which may be a good or bad thing, depending on the team’s project plan), perform processing on collected raw data, monitor system performance, and visualize all of it. As the module took in far more students this semester than usual, each group had 6 members. As my group decided to fully utilize the power of AWS, we were able to do an end-to-end project with a large scope using various AWS services. This would likely not have been possible if we did things without cloud services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N9xc7Zjvr_AsUGvx.png" /><figcaption>This was the architecture that I helped my group to design. I was so happy when it was done!</figcaption></figure><p>Overall, this module was enjoyable mainly because of the project we planned ourselves, although when it came to the content taught and assignments, I felt that I didn’t learn much despite the fact that the content was very industry-relevant. There were chapters that breezed by really quickly, and the assignments could’ve had better guidance, which may change in the following semesters. There is still much room for improvement for the team behind this module.</p><h3>LSM1303 Animal Behaviour</h3><p>Not a CS module, but I took this to fulfil my science requirement as it seemed fairly interesting. This module was about understanding animals and the various behaviour they exhibit. We learnt about topics such as foraging, territoriality and courtship. There were about 4 labs we had to attend in person as they had group activities for us to do, but mainly it was because the team felt that in-person teaching was more effective. There was a project component in which we had to research and observe a particular animal of interest in the wild and record our findings and conclusions which would be then shown in the final report. The professor, <strong>Sivasothi N., </strong>is truly passionate about what he teaches and does a great job at explaining concepts. This module actually reminded me a little about GET1020: Darwin and Evolution due to the many different documentary clips shown during lectures, but the difference would be that this module had lesser content, presumably because the project would take up some time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pk5QYq_xjpvonbp4.jpg" /><figcaption>The white-breasted waterhen was chosen as our animal of focus for my team’s project.</figcaption></figure><h3>Final Thoughts</h3><p>As with every semester, this felt long yet short at the same time. The content I learned this semester was enjoyable as I didn’t really like the theoretical aspects of many computer science mods at NUS, and the fact that I could use so much of AWS services was really fun as well! Perhaps it was because both my CS modules were at high levels (CS5224 was for postgraduates mainly, CS4225 had some postgraduates) and hence it was more industry-relevant?</p><p>Given that I stopped watching lectures for both my CS modules in week 4 and only read lecture slides (I learned better this way, reinforcing concepts on YouTube instead), my semester felt much more relaxed. What a change of pace since year 1! It also seems like modules at higher levels have a focus on learning compared to obtaining good grades, or perhaps our mindsets have shifted since our first year.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ce65c2181b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up JupyterLab and a virtual environment]]></title>
            <link>https://medium.com/@royce963/setting-up-jupyterlab-and-a-virtual-environment-c79002e0e5f7?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/c79002e0e5f7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 08:16:38 GMT</pubDate>
            <atom:updated>2022-04-17T08:16:38.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Objectives</h3><ul><li>Setting up a data science environment</li><li>Understand the importance of virtual environments</li></ul><h3>Prerequisites</h3><ul><li>Basic Python knowledge</li></ul><h3>Jupyter</h3><p>IPython Notebooks are interactive computational environments in which you can combine code execution, rich text, mathematics, plots and rich media. We will use JupyterLab as it is the most popular platform for using notebooks. VSCode can be used to run notebooks as an alternative as well.</p><h4>Installation</h4><p>Ensure you have python installed. If you are using a macOS version that comes with Python 2, run pip3 instead of pip. Other ways of installing are stated <a href="https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html">here</a>. Run the following command in your terminal.</p><pre>pip install jupyterlab</pre><h4>Starting JupyterLab</h4><p>Ensure that you are in your preferred directory for your project(s). Run the following command in your terminal.</p><pre>jupyter lab</pre><p>Click on Python 3 Notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*cl_-5bLQ4CR0Pp-H" /></figure><p>You can now write code in the interactive notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*AraZmdaLK0HyKnX2" /></figure><h3>Virtual Environments</h3><p>Previously jupyter lab was installed as a global package, which is fine since it is a package that is used by multiple projects. However, different projects will require different packages / dependencies / libraries, and to install all of them globally would potentially cause problems.</p><p>This is where virtual environments come in, which is creating isolated environments for each python project that you have. That way, you will not mix up your packages or have conflicting ones.</p><p>To create a virtual environment for your project, cd into the root directory of your project and run the following:</p><pre>python -m venv my-env</pre><pre># alternatively if the above doesn&#39;t work<br>python3 -m venv my-env</pre><p>This creates a folder called my-env in the root directory of your project. Once you’ve created a virtual environment, you may activate it.</p><p>On Windows, run:</p><pre>.\my-env\Scripts\activate</pre><p>On Unix or MacOS, run:</p><pre>source my-env/bin/activate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ridfb6YMk7oQVPV2IHf3KA.png" /></figure><p>Once an environment is activated, all pip installs and uninstalls will point to the virtual environment folder created, and all your libraries for that particular project will be stored there. To deactivate an environment, simply run the following:</p><pre>deactivate</pre><h3>Using JupyterLab with virtual environments</h3><p>If you are running .py files, you may simply run the files while the environment is activated. As JupyterLab uses notebooks (.ipynb) instead, the approach is slightly different as seen from this <a href="https://www.geeksforgeeks.org/using-jupyter-notebook-in-virtual-environment/">guide</a>. We will test out the matplotlib library, but you may use any other library.</p><p>With the virtual environment <strong>activated</strong>, do the following.</p><pre># install ipykernel, which consists of IPython as well<br>pip install ipykernel</pre><pre># create a kernel that can be used to run notebook commands inside the virtual environment<br>python -m ipykernel install --user --name=my-env</pre><pre># install the matplotlib library so that we can test it out<br>pip install matplotlib</pre><pre># launch JupyterLab<br>jupyter lab</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5uDz-0-JT32-UIJPFfXqw.png" /><figcaption>You may run the above to ensure libraries such as IPython as matplotlib is installed. If they are not installed an error will pop up as shown from importing pandas.</figcaption></figure><p>Click on my-env.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*f3sE8ZodQByrU_cPcIzpnA.png" /></figure><p>Run the following code from <a href="https://matplotlib.org/stable/tutorials/introductory/pyplot.html">here</a>.</p><pre>import matplotlib.pyplot as plt<br>plt.plot([1, 2, 3, 4])<br>plt.ylabel(&#39;some numbers&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*O9v-E0J0yRy5Pis9v-tTdA.png" /></figure><p>That’s all, you’re done!</p><h3>Removing environments</h3><p>To show which kernels were added and remove my-env:</p><pre># shows you the list of kernels you added<br>jupyter kernelspec list</pre><pre>jupyter kernelspec uninstall my-env</pre><p>You can then manually delete the my-env folder.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c79002e0e5f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modules I took at NUS School of Computing]]></title>
            <link>https://medium.com/@royce963/modules-i-took-at-nus-school-of-computing-9d8a56dbe88a?source=rss-dff7a0264154------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d8a56dbe88a</guid>
            <category><![CDATA[singapore]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[university]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Royce Ho]]></dc:creator>
            <pubDate>Mon, 01 Nov 2021 14:41:05 GMT</pubDate>
            <atom:updated>2023-11-05T07:12:57.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modules I took at NUS: School of Computing</h3><h4>Year 1–3</h4><p>This is a quick recap of the modules I took at NUS for my major, Computer Science, from 2019–2021, and my experience may differ from many others. Majority of modules taken in year 1 and 2 and similar for most students, and in year 3 and 4 we are quite free to choose from the various focus areas offered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZHCZlLhVOkZP7IXO.jpg" /></figure><p><em>This is an ongoing series:</em></p><blockquote>Part 1: <a href="https://medium.com/@royce963/nus-computer-science-diaries-part-1-58c5a3d0b476">What is NUS Computer Science really about?</a></blockquote><blockquote>Part 3: <a href="https://medium.com/@royce963/challenges-as-a-computer-science-student-b86bf4510343">Challenges as a Computer Science Student</a></blockquote><ol><li><a href="#d6e6">Year 1, Sem 1: CS1101S, CS1231S, MA1521</a></li><li><a href="#aa38">Year 1, Sem 2: CS2030, CS2040S, MA1101R, IS1103</a></li><li><a href="#d80f">Year 2, Sem 1: CS2103T, CS2100, CS2105, CS2101</a></li><li><a href="#c1d5">Year 2, Sem 2: CS2102, CS2106</a></li><li><a href="#6162">Year 3, Sem 1: CS4226, CS3237, CS2107</a></li></ol><h3>Year 1, Semester 1</h3><h4>CS1101S Programming Methodology</h4><p>Probably one of the hardest modules that I took. NUS uses a language called Source, which is a stripped down version of JavaScript, to teach functional programming. We spent most of our time solving “missions”, which were essentially algorithmic questions. If you’re good at Leetcode, this module would probably be a breeze. Recursion was a pretty big part of the first half, and I remember miserably trying to wrap my head around it. Aside from algorithms, some of our tests include questions that involve confusing code and finding the output, to attempting to learn states using <a href="https://sicp.sourceacademy.org/chapters/3.2.html">environmental diagrams</a>.</p><p>In my opinion, this mod was catered towards students who were capable or had lots of potential in solving algorithmic problems. It was a very tough module for the majority, and not taught in the best way. The textbook is <a href="https://sicp.sourceacademy.org/">here</a> if you want to check it out.</p><h4>CS1231 Discrete Math</h4><p>Another notoriously tough mod, this mod introduces logic, number theory, graph theory, relations, probability and more. Confusing but some of the basics are useful down the road. SOME. I don’t even remember much of this module to be honest. Some mathematical proofs were really painful, and majority of the time I simply watched how the tutor did it as I could not even fathom what was going on during tutorials.</p><h4>MA1521 Calculus</h4><p>Math and stats mods were offered by the Faculty of Science (now renamed as College of Humanities and Sciences) and it felt that close to no effort was put into these modules by the teaching team. It was basically only lectures, tutorials and 2 exams. Half of which was covered in JC, and there were some new topics. Teaching assistants were PHD students, probably having to do so to fulfill certain requirements. Tutorial attendance did not matter at all, so you could do this entire module without attending a single tutorial.</p><h3>Year 1, Semester 2</h3><h4>CS2030 Programming Methodology II (now CS2030S)</h4><p>This was basically an introduction to Object Oriented Programming (OOP) in Java. It felt like after week 4 or 5, all the basics were covered, and we moved on to more advanced concepts such as generics, optionals, streams, async. The first few weeks are really useful for the years to come. I’m not sure about the rest as I don’t remember much actually. The lab assignments were not easy at all, and I sometimes found myself stuck for 8 hours straight till 4am. But, a very much needed mod, though I felt that the difficult of the 2nd half could be adjusted or at least taught better because most of my learning came from the labs. Oh, yes and another important part was design. We were taught the SOLID principles, and how things such as abstraction and inheritance work. Those were really useful!</p><h4>CS2040S Data Structures and Algorithms</h4><p>Really really useful mod. We learnt how data structures worked and how algorithms made use of such to solve various types of problems. Possibly the most important mod if you want to be able to get better at coding interviews and Leetcode. From arrays to trees and then to graphs, some of the content were difficult to grasp, but it was an engaging module nevertheless as one can clearly see the use of many of these algorithms.</p><h4>MA1101R Linear Algebra</h4><p>Not much to say on this. A lot of matrices involved. Wasn’t an easy mod but once again a very typical lecture + tutorial + exams kind of mod. No other stuff.</p><h4>IS1103 Ethics in Computing</h4><p>A non-technical module that introduced us to the various forms of ethical theories such as deontology and consequentialism. And more such as social contract, golden rule etc. A module with a notorious reputation for unexpected random grades because it was basically down to weekly quizzes and 2 reports based on your quiz responses and the Professor’s method of grading differed each semester. Close to no workload at all.</p><h3>Year 2, Semester 1</h3><h4>CS2103T Software Engineering</h4><p>This introduces us to building actually applications in Java with an individual project and a team project. This module is perhaps the most important in terms of basics needed because it exposes us to brainstorming, version control with Git, coding as a team, and delivering the app together with documentation. Time required on this module was above average. We even had a practical exam in which we had to find bugs with other teams’ apps to score points. We were also introduced to software engineering practices and design patterns, which are really useful! Really recommend this mod and I would place it at the top, together with data structures and algorithms if you’re only doing a CS minor and have limited choices.</p><h4>CS2100 Computer Organization</h4><p>Hell. This mod introduces us to low level computing. We learn C, followed by assembly and the MIPS architecture. Concepts such as pipelining were really difficult to follow but when it came to playing around with logic gates, I kinda liked it. You really learn how a computer takes 1s and 0s into a CPU that does computation, and how that connects to instructions in assembly. Interesting concepts but painful module because I felt quite lost most of the time.</p><h4>CS2105 Introduction to Networks</h4><p>A module mostly based around networking concepts and the OSI model. There were 3 programming assignments that were challenging but other than that the module was quite light in terms of workload. This module is probably quite important as networking knowledge applies in many fields and is useful even as background knowledge.</p><h4>CS2101 Effective Communication</h4><p>Not gonna talk much about this. This module is not technical related, but rather focused on critical thinking and presentation skills instead. It was taught by the Centre for English Language Communication (CELC) instead of the school of computing. There were 4 continuous assessments which involved presentations and the workload wasn’t light.</p><h3>Year 2, Semester 2</h3><h4>CS2102 Introduction to Databases</h4><p>This module taught us relational algebra, entity relation diagrams, SQL queries and normal forms. Pretty useful information although the way that it was taught wasn’t great at all. I was lost during tutorials and the lectures were painful to watch. I ended up turning to YouTube for most of my learning, which was a much better experience (although this applies for most introductory mods due to better content on YouTube).</p><h4>CS2106 Introduction to Operating Systems</h4><p>This was supposedly the sequel to CS2100 Computer Organization but it didn’t feel that way to me. We learnt basic concepts used in operating systems such as handling concurrency, file management, memory management and synchronization. Damn, synchronization was tough to learn. The labs were difficult but some of the lecture content was taught well. Perhaps the fact that the lecturer (Uncle Soo) was also my tutor helped as well in terms of the learning experience. But of course, by no means an easy, or even medium module.</p><h3>Year 3, Semester 1</h3><p>Okay, this is where I am right now, at the point of writing this article!</p><h4>CS4226 Internet Architecture</h4><p>First 4 weeks is probability…damn, but looking back, it was pretty cool. There’s lots of queuing theory involved, since we’re looking at packets. Now we’re learning about Software-Defined Networking (SDN) and using mininet and POX to create a custom simulated network. Possibly useful mod, though I’m not sure if I will ever need this knowledge.</p><h4>CS3237 Internet of Things</h4><p>The first half is machine learning, which covers traditional ML to deep learning. We use sklearn and tensorflow during the labs to create basic models and overall the first half has very little workload and is relatively easy. The lectures are for background knowledge as well! The second half consists of backend programming and understanding IoT devices (we are given a CC2650 sensortag). Our project weighs 70% of the module, and we are given the freedom to propose anything that makes use of our sensortag. Overall a low effort module (until the project), and mainly for exposure to IoT if you wanna check it out.</p><h4>CS2107 Introduction to Information Security</h4><p>This module covers a lot of the basics, from cryptography to web vulnerabilities. Tutorials cover a good amount of content as well. There are 2 Capture-The-Flag (CTF) assignments which are really really tough. I spent hours and hours stuck on individual challenges but overall a really good mod for exposure and helps one to consider if cybersecurity is a potential path.</p><h3>That’s all</h3><p>And…that’s all for now! Looking back the modules are all widely spaced out in terms of coverage, like there’s a lot of breath covered in the field of computer science. Lectures are generally subpar compared to YouTube content and assignments have room for improvement when it comes to giving students a better understanding of what is going on and where to look. But all in all, I look forward to my remaining 3 semesters (okay technically the current one has ended yet :P).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d8a56dbe88a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>