Posts

First-Principles Derivation of A Bank

What is a Bank? A bank borrows money from people with money but low-risk appetite, and lends money to people who need money to take potentially rewarding risks. Say we live in a toy society with $10 in circulation and 2 people (a farmer and a cook). In this society, the farmer grows vegetables and the cook processes vegetables for food – both activities essential for survival. Assume that both parties start with $5 each. The farmer sells vegetables for $1 per serving and can produce 2 servings per day. The cook prepares food for $2 per serving and also has the capacity to produce 2 servings per day. Every day, the farmer sells 2 servings of vegetables to the cook for a total of $2 . Then, the cook prepares 2 servings of food and sells 1 serving to the farmer for $2 . In this perfectly balanced society, everybody eats, and money never needs to “rest.” Let's break the above equilibrium by adding a time component. In this society, vegetables take thr...

I'm looking For a Man In Finance... Wait what is Finance?

My girlfriend showed me a music remix of a viral video where a woman says that she is looking for a man in finance who is 6' 5", has blue eyes, and is affiliated with a trust fund. This got me thinking: What does a man in finance do? What is finance even? What service does this "man in finance" provide that this woman needs to access? After some thinking and reading, I've decided to try my hand at explaining what is finance. Finance seems to be the study of how to keep track of who owns what, and a financial system seems to be a system that keeps track of who owns what. In the early prehistoric days, the financial system was quite simple: You own what you can defend. If you thought you owned a nice rock, you kept track of it by holding it and attacking whoever tried to take it. Trading ownership meant handing your rock to another caveman, and simultaneously they would hand you a fish or something you wanted to trade for. These were simple times, but you could onl...

How did modern markets develop? (A Tulip Market Analogy)

I've been interested in how our modern stock markets work for a while now, and recently I've been trying my best to understand all these fancy terms, like "T+1", "clearing firm", "broker-dealer', etc. Here's a situation that I came up with, that helped me understand how markets may have evolved. Imagine you're living in 17th century Amsterdam, and you're looking to buy a lot of tulips. How would you do this? You need to find a seller, you need to know the price. Then, if you choose to buy at that price, you need to sign an agreement to exchange money for tulips at a later date that's convenient for the two of you. Where can you find a seller? You heard there's a tulip market where the tulip buyers and sellers hang out. It runs weekdays from 9:30AM to 4:00PM. There's also a pre-market and a post-market, but there aren't too many people there, so it's a lot less liquid outside of the main hours. This place is called an ...

The Very Basics of Android: Starting Activities

Image
When you click on a link on a webpage to navigate to another webpage, what do you need to tell the backend in order for it to fetch the right page for you? First, you have to tell the backend which page you want to see. Second, you have to tell the backend any extra information it might require. You take these two pieces of information, package them into a nice bundle of data called a URL and send it off to the backend. When we launch an activity, we do a very similar thing. First, we get the name of which activity we want to open. Then we package together any extra information we might need to show this page into a nice bundle. We package these two pieces of information together into an object called an Intent  and then we send it off to the Android OS using the very aptly named `startActivity` command. Here's what an Intent  looks like in code: Intent(context, SearchActivity::class.java) .apply { putExtra("q", "duolingo") } Ignoring the context for now, t...

The Very Basics of Android: Tasks, Activities, and the Backstack

Image
Welcome to The Very Basics of Android ! This series is aimed at folks just starting out on Android, and the goal is by the end of the series, you should be familiar enough with common Android topics to be able to go on to other intro materials. To start, this first article will discuss the terminology we use when talking about the UI of the app: Tasks, Activities, and the Backstack. Go onto your Android phone, and click on the small square button at the bottom of the screen. This screen represents all of the tasks running that you have opened! Here's what it looks like on my screen: As you can see, I most recently opened Duolingo and second most recently opened the calculator app, so I have a Duolingo task as well as a calculator task. Each one of these tasks is just a stack of "webpages", called the backstack . Each one of these "webpages" we call an activity . Here's my artist's rendition of what this looks like: When browsing a webpage, you are clicki...

Reading "The Design of Everyday Things"

Life so far It's been a tough 2022 so far. I'm burned out at work, my grandpa is ill, my old car broke down, etc. Hence the general lack of motivation to write anything. I feel like this year will be learning year for me, where I get my ass handed to me by life, and I come out of it battered but more mature. In this vein of learning, I've been trying to institute a few changes in my life to help alleviate some of the things that are going on in my life. Basically, try to stay in control of my life as much as I can. A few basic ones: Work exactly 8 hours a day and push back on deadlines that would require working more than 8 hours a day. Write every so often. In my blog, in my random notebooks. Keep in contact with family. Keep my girlfriend in the loop about my stresses and struggles (she's a psych major!) Always be learning something new. Let's hope everything works out! *knock on wood* Reading "The Design of Everyday Things" In terms of my goal to always...

Thinking about fuzzy logic and implementing black boxes

Today, Google did a doodle about Dr. Lotfi Zadeh who published a paper that proposed fuzzy logic. It feels like it's been forever since I studied anything that has to do with machine learning so I decided why not, let me learn a bit about this. It turns out, fuzzy logic is actually really applicable to my job (which involves no machine learning at all) not because I need to implement a bunch of ambiguous things on the app (although dealing with ambiguity is a big part of the job) but it proposes a really neat way to think about constructing a black box. First, my understanding of a fuzzy system. It is effectively a black box, with rules that you can configure. You feed in your raw data on one end, it goes through the "fuzzifier", the "inference engine", the "defuzzifier" and some new data emerges from the other end. The core of this box is the inference engine. Basically, this part of the system holds the rules that you and your product folks come up w...

Scary Spookvember: Regex!

Image
This is the first blog post in a new series of blog posts that involves me learning and blogging about things that scare developers. I came up with this idea basically right after Halloween ended, so unfortunately this has to be the Scary Spookvember series now instead of Spooktober, which would've made more sense 🤦. This first article is about Regex. Many developers think of it as like a template that can match strings, but actually, Regex is a simple programming language! To show this, let's take a look at a simple Regex that matches a simple lowercase UUID, such as e81dd3ba-44bb-11ec-81d3-0242ac130003 . The Regex that I found on stack overflow is: \b([0-9a-f]){8}-([0-9a-f]){4}-([0-9a-f]){4}-([0-9a-f]){4}-([0-9a-f]){12}\b At first glance, this looks quite confusing and scary, but once we reformat it a bit, things begin to start taking shape: \b # match the beginning or end of a word ( [0-9a-f] # match any character from 0-9 or a-f ) {8} # loop 8 times - # match the...

Link Prediction Using Friends Common ++

Image
Imagine the following scenario: You are provided a list of people in a conference, and you can see all of their Facebook friends. You want to know which people probably know each other. How can you do that in a way that is efficient?  Idea 0: If they are FB friends, then they are probably real life friends Right off the bat, you know that if somebody at the conference is Facebook friends with another person at the conference, then they're very likely to know each other. This is pretty quick to compute. You just build a map of conference goers to Facebook Friends, then go through all their Facebook Friends and check if they are a conference goer. However, now that we know who probably directly knows each other based on their Facebook friends, how can we figure out who might know each other at the conference but have not added each other on Facebook? Idea 1: Count the number of common Facebook friends One easy way to do this would be to say, for any two people, the more Facebook frie...

Supporting RTL languages on Android, Bidi (Bidirectional) text

Recently I've found myself spending a lot of time trying to make sure things look nice on both LTR as well as RTL locales, so that folks with UIs in Arabic, Hebrew, Persian, or Urdu can also have an A+ experience on Android. I ran into an annoying problem where international phone numbers, such as +9708675309 would show up in the app as 9708675309+. The issue was that in RTL languages, numbers should be LTR, so the phone number portion was displayed correctly, but unfortunately the + was displayed on the right side of the phone number. After a good amount of Googling, the fix is actually really simple. Just place the Left-to-Right Isolate Unicode mark on the left of the text you want to be LTR, and then place the Pop Directional Isolate Unicode mark on the right of the text, so that it doesn't make the entire rest of the text LTR. It looked sort of like this in Kotlin: "\u2066+9708675309\u2069" and it worked like a charm!

A list of useful RxJava things!

Over the past year I've learned a bunch of useful tricks for RxJava, and I'm gonna post them here as I remember them or use them. Hopefully this'll grow to a large list/cheatsheet! Here is a way to take the first element multiple flowables that may emit the same data (but loaded from disk or memory or network) and then emit the first one that returns. Concat checks flowable1 first, and then flowable2. I got this from this blog post from Dan Lew . Flowable .concat(flowable1, flowable2) .firstElement() Dan uses it for loading data first from memory, then from disk, and finally from network, so there's a lot of other stuff you can add to it too. He demonstrates how you can use a side effect to create a flowable that saves to network requests to disk and memory whenever you load it from remote: val cache: Flowable<Data> = ... val network: Flowable<Data> = ... val networkWithCaching: Flowable<Data> = network .doOnNext { data -> add...

Reliably showing the Android keyboard for ViewGroups too

The other day, I was browsing through the Android blog world (make sure to check out https://blog.danlew.net/ ), and found this really awesome blog post from the developers over at Square about reliably displaying the Android keyboard, which is controlled by a rather difficult API. After trying out their code, however, I realized that it did not work for my purpose which was to focus a SearchView after clicking a button. The bug was really strange, because while we had called requestFocus() on the SearchView , when we queried it for isFocused , it would return false ! Turns out, after a lot of struggling, I found that requestFocus() actually may give focus to one of the descendants of the View instead. SearchView is actually a ViewGroup , so focus was actually given to a TextView that was a child of the SearchView . After learning about this, the fix was easy: Instead of only directly checking the SearchView for isFocused , do a recursive check on the focusedChild of the Searc...

Thoughts about what makes a great developer

People seem to agree that a great developer is better than many mediocre developers and I think that is true with good reason. Developers are craftsmen, in my opinion, like stonemasons, woodworkers, or carpenters. We make things that are useful to people outside the field, and, if well made, can be even artistic to those who understand the field. Similarly, like craftsmen, you can't replace someone with a skilled hand with many people with unskilled hands. They tried using automation and large factories to churn out things like mass-produced furniture, but at the end of the day, the IKEA fast furniture just really isn't up to the quality of a similar piece made by a real artisan. However, developers these days seem to earn a lot more than other craftsmen, and I think that is largely because for many people buying things like furniture or pottery (especially the young folks like me), cost is a lot more important than quality and most people would rather pay, say, 10% of the cost...

Is it worth it to speed up caches even more?

I think about a cache like a faster database that you check before checking the main database, but at the end of the day, if you do have a cache, you have to check 2 databases. If the cache is sitting in some remote machine, like Memcached, you run into various things that may slow it down by hundreds of microseconds such as intrinsic latency or network latency, and if you choose to query between datacenters you may even get dozens of milliseconds of latency. I wonder how important it would be to shave off these microseconds, or to even just find a way that we could avoid cache queries when they are misses. I'll keep thinking on this and read more about how hyperscalers use caches.

Recyclerview History

Recently I discovered this old talk from Google I/O 2009  and in the first 14 minutes they explain the Recyclerview, the Adapter, and the Viewholder incredibly well. Here's a few important takeaways from this video, although I'd recommend watching it in its entirety: 1. The Adapter takes in data and generates Views via a function Adapter.getView() that takes in a position, a View, a parent ViewGroup, and returns a View. 2. The naive solution to implement Adapter.getView() would be to use the position to get the right data and then just inflate a new View that belongs to the parent ViewGroup. 3. The first optimization is that we can avoid inflating new views by just recycling old views when they leave the visible area. We would use the position, the View (recycled when it is not visible) and just bind new data into that existing View. 4. The second optimization is that we can avoid doing new findViewById() calls by storing all the referenced Views in a class called a ViewHold...

Can the Mirai botnet teach us how to make Android apps faster?

Recently, I've been spending a lot of time thinking about Android app performance, specifically regarding network requests. Developers working on mobile apps are allowed a lot more customization for low-level details (for example, we get to customize our own network stack!) but in exchange, we must plan for our applications to work in some crazy environments. Our users might be on WiFi, 5G, 4G, or even GPRS. They could be sitting in a coffee shop or riding on a high speed rail with their cell service hopping to a new cell tower every 10 minutes. They could even be using satellite if they're sailing on a boat or flying through the air. On top of all this, we need to be able to support everyone using a $100 to $1000 smart phone. Interestingly enough, the conditions that mobile developers have to run their mobile apps in is actually reminiscent of the conditions that botnet developers have to run their malware in! The Mirai botnet malware ran with a tiny memory footprint, a tiny e...

Non-Obvious Denial of Service

I was looking back at Computer Networking: A Top-Down Approach  by Kurose and Ross, a textbook I used for CS145 , (shoutout to Professor Yu who is a really excellent professor) and I noticed this excerpt from the chapter called "Networks Under Attack": Most Internet DoS attacks fall into one of three categories: Vulnerability attack. This involves sending a few well-crafted messages to a vulnerable application or operating system running on a targeted host. If the right sequence of packets is sent to a vulnerable application or operating system, the service can stop or, worse, the host can crash. Bandwidth flooding. The attacker sends a deluge of packets to the targeted host―so many packets that the target's access link becomes clogged, preventing legitimate packets from reaching the server. Connection flooding. The attacker establishes a large number of half-open or fully open TCP connections at the target host. The host can become so bogged down w...

Can we use Varnish as the backend?

In college, one of my favorite classes in college was a cloud networking class where we did a lot of work with programmable switches using P4, a domain-specific language for networking devices like routers and switches. The language was very limited in that you could not have loops or even do simple tasks like division, but these limitations allowed you to process packets at line rate. Using P4 to write custom switch logic, creative researchers have recently been able to figure out how to do a lot of interesting things like accelerate SQL queries or load balance servers. I recently found out about Varnish and the Varnish Configuration Language (VCL), and it reminds me of P4. While switches deal with data on the network layer, a Varnish cache deals with HTTP requests on the application layer data. While programmable switches run P4, a domain-specific language that has limits in order to keep code fast, Varnish caches can run VCL, a domain-specific language that is also similarly limited...

Play-by-play of the Mirai botnet source code - Part 3 (scanner.c)

Image
In this entry about the Mirai botnet, we'll begin by entering the main parts of the Mirai botnet code that set it apart from most botnets of its day. In this portion of the code, the beginning of the "Main logic loop", it sends out SCANNER_RAW_PPS (160) SYN packets to random IP addresses around the world. This is the first stage of what is known as SYN scanning. // Main logic loop while (TRUE) { // (A) fd_set fdset_rd, fdset_wr; struct scanner_connection *conn; struct timeval tim; int last_avail_conn, last_spew, mfd_rd = 0, mfd_wr = 0, nfds; // (B) // Spew out SYN to try and get a response if (fake_time != last_spew) { last_spew = fake_time; // (C) for (i = 0; i < SCANNER_RAW_PPS; i++) { struct sockaddr_in paddr = {0}; struct iphdr *iph = (struct iphdr *)scanner_rawpkt; struct tcphdr *tcph...

Be careful when using websockets!

I was playing skribbl.io with a couple of my friends the other day, and I decided to download this Chrome extension called AutoDraw for skribbl.io . Basically, what it would do is you drag and drop in an image, and then it would automatically draw your super awesome image onto skribbl.io. I was having a lot of fun playing around with this extension, so I decided to check out what was going on under the hood.  It turns out that skribbl.io actually opens up a websocket connection from your browser to their server (mine was probably located somewhere probably in France (the IP belonged to OVH and the ping was 18ms from both London and Amsterdam) and it was sending my mouse movements every 50ms to the server in 195 byte messages. For those keeping count at home, this is around 0.0312 Mbps that I have to pay. Now, my friends in the game were also receiving these 0.0312 Mbps from the server to their browsers, free of charge.  If we had max-ed out the room to the size limit of 12 pla...