<?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 Rami Awar on Medium]]></title>
        <description><![CDATA[Stories by Rami Awar on Medium]]></description>
        <link>https://medium.com/@ramiawar?source=rss-4710ac41d86b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*WeXvsSk5yZPqGEZzqOkzNg.png</url>
            <title>Stories by Rami Awar on Medium</title>
            <link>https://medium.com/@ramiawar?source=rss-4710ac41d86b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:01:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramiawar/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[Chat with your Snowflake database]]></title>
            <link>https://ramiawar.medium.com/chat-with-your-snowflake-database-27bfd5c50d48?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/27bfd5c50d48</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 07:34:38 GMT</pubDate>
            <atom:updated>2024-06-24T07:34:38.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_hNYS4wRqf2ignP2QgbzQ.jpeg" /><figcaption>Data analysis on Snowflake made easy through AI chat with DataLine</figcaption></figure><p>Data analysis is changing fast. Tools like Snowflake make it easier to handle large amounts of data. But what if you could query Snowflake using natural language? Enter DataLine.</p><p><a href="https://dataline.app/">DataLine</a> is an AI-driven open source and privacy-first platform for data exploration through chat. This makes data analysis more accessible, especially for those who aren’t data experts. It’s easy to install and stores all your data locally making it great for self-hosting and using in businesses where <a href="https://dataline.app/faq">data security is crucial</a>. Today we’ll be plugging it into a Snowflake database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ooseam3EdXakGXNKL8hCHg.gif" /><figcaption>short gif showcasing DataLine’s ai data analysis and visualization features</figcaption></figure><p>That’s enough of an intro, I know you’re excited to get your hands dirty. Let’s get to it.</p><h3>Connecting with Snowflake</h3><p>Today we’ll be working with the Snowflake samples, as that requires no setup. You can create a new Snowflake account if you don’t have one already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvW1dNzKzWfgYE6k1AzJTQ.png" /></figure><p>Jump into your Admin -&gt; Account settings and let’s get our host name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0D19sK6tcYxI2QPqyoJcdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-brgOEe_tZnbXdJwVOUzzA.png" /><figcaption>snowflake admin menu getting host name</figcaption></figure><p>Here you can see the host name is ‘<em>jcaiijn-qr76787’</em>. Other than that, we just need our username and password (Snowflake user password), and we’re all set!</p><p>For a username of ‘bob’ and password of ‘thebuilder’, the DSN (database connection string) here would be:</p><blockquote>snowflake://bob:thebuilder@jcaiijn-qr76787/SNOWFLAKE_SAMPLE_DATA/TPCH_SF1</blockquote><h3>Plugging in to DataLine</h3><p>Now all you need to do is add your database connection string from above in to DataLine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ovd20IzvbbYuQStYjJjwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7WBQ5QsG8FeLwSMFoUPoA.png" /><figcaption>DataLine Snowflake connection</figcaption></figure><h3>Playtime</h3><p>We’re already here? Whew.. that was fast.</p><p>You can just type your questions in plain english and it’ll figure out what needs to be done. Here I’ll explore this sample DB with DataLine’s help. Let’s start with asking for some example questions so we get an idea about what’s in there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DB04m5c3M9aKOwrqz3-IEg.gif" /><figcaption>gif demonstrating DataLine AI data analysis features with the snowflake sample DB</figcaption></figure><p>Woah cool! That would’ve taken a data expert at least 10 minutes to get an idea of what the data looks like and go through all the tables. DataLine translated your question into several Snowflake queries, retrieved the tables and analyzed them. You see the answer in seconds but there was a lot of work behind the scenes!</p><h3>There’s more?</h3><p>DataLine doesn’t stop at answering questions. It also helps you visualize the data. Let’s see what the average order quantity per customer is, and ask for a chart of the distribution per customer for the top 10 customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou0fqNr1hqjvxronnaM5Jg.png" /><figcaption>screenshot showing DataLine AI returning data analysis results and an image showing a chart of the distribution requested from Snowflake</figcaption></figure><p>Ok seriously though, how long would it have taken a data analyst to lookup the schemas, write this query, export the data, and build such a pretty chart? That’s what this is all about. Saving tons of time and tons of money and making this more accessible to non-technical folks. It was always about the question, not about how we get to an answer. We were just drowning in the details.</p><p>AI really is transforming data analysis, in a good way. With tools like DataLine, the focus shifts from writing complex queries to asking the right questions. Now:</p><ul><li>Non-experts can analyze data without learning SQL or other query languages</li><li>We get insights faster by skipping the query-writing process.</li><li>(Eventually) AI will minimize errors in data interpretation compared to humans. Not there yet but not that far off.</li></ul><p>Aand that’s a wrap! DataLine and Snowflake together make AI data analysis more intuitive and powerful. We’re always looking for help building this awesome open-source product, and we have big plans for its future. If you’re interested, <a href="https://dataline.app/">you know where to find us.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27bfd5c50d48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vanna AI vs DataLine]]></title>
            <link>https://ramiawar.medium.com/vanna-ai-vs-dataline-4829b1d2fad5?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4829b1d2fad5</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 20:13:58 GMT</pubDate>
            <atom:updated>2024-06-28T07:02:30.988Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owgGXvs0Z8h1cuw95HHETA.png" /></figure><p>I just learned about <a href="https://vanna.ai/">Vanna.AI</a>, so I thought I’d write a comparison article since I’m deeply familiar with <a href="https://dataline.app/">DataLine</a>’s inner workings.</p><p>In this article I’ll go over the <strong>feature </strong>differences, an example of <strong>quality </strong>differences on a sample dataset (with pictures of both), and importantly, <strong>privacy and security </strong>differences that are relevant for users.</p><p><strong>TLDR:</strong> VannaAI is more tailored towards developers, and single question/answer flows. It supports advanced integrations and has built a lot of features around contextual knowledge. DataLine is also suitable for non-technical personnel (ex. PMs, BAs) and is focused on a simpler and less customizable user experience.</p><h3>What are these to begin with?</h3><p>Both Vanna.ai and DataLine were created to help developers and non-technical people query their data with natural language. They’re both open source, can generate SQL, tables, and charts to answer user queries. They both target regular users as well as enterprise customers, with self-hosted deployments and fully open-sourced codebases.</p><p>To look at the differences, we have to dig deeper. There differences in how data security is handled, and some feature differences as well, both of which are relevant for enterprise users mainly.</p><h3>Vanna.ai Features</h3><p><strong>Vanna</strong> supports quite a few features:</p><ul><li>Web interfaces built on top of Python’s <a href="https://streamlit.io/">Streamlit</a>, allowing re-use of community building blocks but limiting frontend development to Python</li><li>Connecting to multiple SQL databases (Snowflake, Postgres, BigQuery, SQLite, and more)</li><li>Supports adding contextual examples like example queries or documentation to aid with query generation on complex datasets (which they market as “training” to communicate to the masses)</li><li>Has a user interface with chat, that generates SQL, results, and plotly charts that are generated by executing python code sent by the LLM (more on this later)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5apfvXO6PV82bwYDVyK_A.png" /></figure><ul><li>Supports a slack connector, allowing access to results from slack threads</li><li>Is also a Python library, allowing others to extend it building their own products and interfaces on top</li></ul><h3>DataLine Features</h3><p><a href="https://github.com/ramiawar/dataline"><strong>DataLine</strong></a> is built a little different:</p><ul><li>Web platform is built from the ground up in React and FastAPI, allowing the broader dev community to contribute to a standard web app and allowing for easier customization of UX/UI</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ooseam3EdXakGXNKL8hCHg.gif" /><figcaption>Gif of demo of dataline chat</figcaption></figure><ul><li>Connecting to multiple databases + sources is supported (CSV, SQLite, Postgres, MySQL, Snowflake, and more)</li><li><strong>Does not yet </strong>support adding contextual examples. Experimented with this at some point but failed to get a significant quality bump so scrapped it, but we’re working on it again now.</li><li>Has a chat interface with SQL and table results</li><li>Major difference in charting: DataLine has ChartJS charts that allow for customization and replayability of results when the SQL is modified. More on chart differences in the security section 👀</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FudixSQi3yTlcliTcGnevA.png" /></figure><h3>Enough talk! How do they differ in quality?</h3><p>I could dig into the technical details of both implementations, but not all of you are interested in that, so I’ll jump right into an example. I’ll still mention a few things on the tech side at the end!</p><p>Let’s start with Vanna. I booted up a container to install it and run the interface in a sandbox environment (more on this in the security section). It was a little frustrating to run locally, the docs all recommend the hosted solutions. Honestly took me around 10 minutes to get things up and running, but was excited to try it out!</p><p>I will use GPT-3.5-turbo for both tests, and a Titanic dataset (https://www.kaggle.com/datasets/ibrahimelsayed182/titanic-dataset) to keep things simple.</p><h4>Testing exploration abilities</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3rLBX66wThRUeoWBPv0fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkmApUVza4UBdoQ4-S8PZw.png" /></figure><p>It had some issues with one of my sqlite samples, but the titanic dataset worked fine. It was very frustrating that it wasn’t a chat however, I had to ask a new question in a new page every time. Also had to modify the SQLite query to fetch table metadata to make this work.</p><p>In DataLine, I went with the command line install and ran brew tap ramiawar/dataline &amp;&amp; brew install datalineand got it running with dataline</p><p>Also got some examples and it worked fine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4iT_f0F5TlIF_h_hbylfSQ.png" /></figure><h4>2. Specific data fetching</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeCYuMtFyKyrU1Auz4PkzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-upuGYLt6zrIHF5cz7ypFw.png" /></figure><p>This was pretty fast compared to DataLine. That’s due to the more complex flow in DataLine internally. Vanna.ai has a straightforward flow on the other hand: generate SQL, generate chart, and we’re done. That can be a positive or a negative (in case query fails or chart generation fails for example, DataLine could self-correct and try again until it succeeds).</p><p>Alright. Let’s spice it up. Can I ask multiple questions? Running out of ideas here!</p><h4>3. Multiple questions:</h4><p>Okay Vanna got flustered with this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NChtXkOlBU0TT5FXVDOlBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yST-5U1qZ0_pgu8iowQbWw.png" /></figure><p>DataLine has got result grouping as well, related tables/charts/SQL is grouped visually to help users understand which answers reply to which questions!</p><p>Enough yapping, let’s move on to the last section.</p><h3>Privacy and Security</h3><p>I dug into Vanna.ai’s code and noticed a few things.</p><p>First of all, the only things sent to LLMs are metadata about the table. Schemas and such. That’s similar to DataLine in this sense, and it can be disabled optionally through code. You could go and add the flag `allow_llm_to_see_data=True` to let the LLM see your data.</p><p>You can also do this in DataLine with a simple toggle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cn8dlYCEV_iK5AgCXHwkA.png" /></figure><p>Moving on to the spicy parts: How are the results generated?</p><p>Well both systems here perform similarly. They both run the query locally, and they fetch the results. That means nothing goes over the internet (unless you’re using the hosted version of Vanna.ai, but this comparison will look at the more secure options).</p><h4>How does charting work in both cases?</h4><p>Vanna.ai asks LLMs to generate Python code that draws a Plotly chart to draw the graphs. They mention that this is unsafe in their “hardening” docs section (<a href="https://vanna.ai/docs/hardening-guide/">https://vanna.ai/docs/hardening-guide/</a>).</p><h4>What does this even mean? Why is it a big deal?</h4><p>Well if the LLM is generating code that will be run dynamically on a user’s computer or on a company server, then there’s a chance this code is malicious because it can’t be fully trusted. It’s also a vulnerability because if hackers ever impersonated the LLM, they could execute arbitrary code on those machines. <a href="https://thehackernews.com/2024/06/prompt-injection-flaw-in-vanna-ai.html">I’ve already seen it mentioned by cybersecurity researchers.</a></p><p>To turn it off is not very simple. You’d have to override a function in the code to prevent it from actually generating code dynamically. In that case, Vanna will attempt to auto-deduce what kind of chart to plot. In general, Vanna is very tailored towards developers I feel like.</p><p>You can see the <a href="https://github.com/vanna-ai/vanna/blob/14dd2fadda05b0abe8a2bbebf3691db69e24a6e7/src/vanna/base/base.py#L1999C1-L1999C13">Python exec and auto inference here</a>.</p><h4>DataLine’s approach</h4><p>DataLine takes a simpler approach: Using an LLM to generate ChartJS json and then rendering the chart.</p><p>This also gives the frontend the ability to easily regenerate the chart and customize it, something that isn’t as easy when using plotly and controlling the chart from the backend.</p><h4>Quick summary of technologies used</h4><p>Techies, this one is for you.</p><p>Digging into Vanna’s code, they seems to use custom constructions from the ground up. No langchain or mirascope or anything for doing the LLM queries. I think this is very lightweight and is what gives them fast response times. But sadly we live in a world where LLMs make mistakes and tools fail, so I think there needs to be more work done to handle such failures gracefully.</p><p>DataLine on the other hand uses <a href="https://langchain-ai.github.io/langgraph/">Langgraph</a> and <a href="https://docs.mirascope.io/">Mirascope</a> to build a state machine with different nodes. This allows DataLine to be more flexible in it’s responses and more resilient to errors.</p><p>Already talked about charting and result generation.</p><h4>To conclude</h4><p>There’s <strong>a lot</strong> more in <strong>both</strong> tools that I didn’t go over, I just wanted to cover the basics: Will this replace writing SQL? Can non-technical people use this? And I think I answered those questions. I could dig deeper into different areas if you’re interested, so be sure to leave comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4829b1d2fad5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an OCR pipeline in Python]]></title>
            <link>https://medium.com/agriplace/building-an-ocr-pipeline-in-python-5531fc055d42?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5531fc055d42</guid>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[agriplace]]></category>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 13:29:22 GMT</pubDate>
            <atom:updated>2023-06-27T13:29:22.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ZCqM99H_xfwsv_Mc.jpg" /></figure><p>In our winter 2-day hackathon at <a href="https://www.agriplace.com/">Agriplace</a>, the day started with diverse teams forming around pitched ideas. Every team had a mix of marketing, sales, product, customer support, and development members. Our team had the idea to experiment with extracting certain document content and analyzing it.</p><p>To do that, we tested out several methods of doing OCR for the extraction part, and learned a few things that are worth sharing along the way. This was only one part of our hackathon project, but would set the foundation for our production OCR pipelines later on!</p><h3>PyTesseract</h3><figure><img alt="Tesseract animation" src="https://cdn-images-1.medium.com/max/256/0*FG8qKq2F8m88yZtN.gif" /></figure><p>As a first attempt, we used <a href="https://pypi.org/project/pytesseract/">PyTesseract</a> to test out some basic OCR. That worked ok as it supported multiple document types, multiple language packs, and had a simple interface. We performed OCR once to deduce the language, then another time with the right language pack. That took quite some extra time, but that wasn’t a big deal since the processing didn’t have to be realtime.</p><p>However when looking into deploying it, we realized that we’d have to create an API wrapper around our little pipeline to deploy it as its own microservice so that it can be used by several of our teams.</p><p>We knew that Amazon Textract would fit the task perfectly. But given that we had hundreds of thousands of documents with no limit on their number of pages, we estimated that using Textract would cost us thousands of dollars for this small experiment and limit us to PDFs mainly.</p><h3>Tika</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/0*oNitQlCr4FF4qZim.png" /></figure><p>At this point we discovered <a href="https://tika.apache.org/">Apache Tika</a>, a content analysis toolkit that supports over <strong>a thousand</strong> file types. The Tika team has also built a containerized API wrapper that offers a simple interface and is deployable with ease.</p><p>One thing that was missing though was a Python client for this API. We found several out there, but none that had the customization we were looking for after going over the <a href="https://cwiki.apache.org/confluence/display/TIKA/TikaServer">Tika Server documentation</a>. We set out to build our own, starting with wrapping the core functions we were planning to use. And thus, <a href="https://github.com/agriplace/pytika">PyTika was born</a>! We also borrowed a cool design pattern from Golang (<a href="https://www.softgrade.org/the-innovation-of-functional-options/">Functional API Options</a>) to flexibly configure the client.</p><p>After processing the document outputs, we started noticing weird errors: “April” was extracted as “Apri!”, colons were captured as characters, and more. Lots of words that were nearly correct had one bad character somewhere which caused errors in our content analysis down the line. We also noticed this when using Tesseract (Tika uses Tesseract for OCR internally), so we knew it wasn’t a Tika problem.</p><p>Running the same documents through Amazon Textract however (supposedly best in class OCR as of this moment) we found that it somehow avoided these errors. They either have a better OCR model running or they’re somehow post-processing the output and correcting the results.</p><h3>OCR Needs Error Correction</h3><p>We learned the practical way that error corrector modules are a big factor in what makes a specific OCR product good or bad. There are a few papers on writing error corrector modules for OCR outputs, one of which is <a href="https://arxiv.org/pdf/1604.06225.pdf">https://arxiv.org/pdf/1604.06225.pdf</a>. I bet a big reason of why Textract is so good is a top tier error-corrector in their post-processing of documents.</p><p>We started with a simple multi-lingual dictionary based error-corrector and that already fixed a lot of the errors we were seeing. Now “Apri!” would get mapped to “April” which is the ‘closest’ word from the dictionaries provided.</p><h3>What’s Next?</h3><p>There’s much room for improvement still, but we kind of got all we needed from this simple implementation for now. In startup and hackathon spirit, we’ll fix it when it breaks! And with some Friday afternoon food and drinks, our winter hackathon came to a close.</p><p>For future OCR cases, we could just use Amazon Textract since we won’t be paying a massive cost upfront. Instead it’ll be distributed over years of documents collected, making it much more tolerable. But combining with Tika gives us maximum flexibility over different file types while still benefitting from Textract’s accuracy with PDFs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5531fc055d42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agriplace/building-an-ocr-pipeline-in-python-5531fc055d42">Building an OCR pipeline in Python</a> was originally published in <a href="https://medium.com/agriplace">Agriplace</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Rental Search Problem]]></title>
            <link>https://ramiawar.medium.com/the-rental-search-problem-a68f5e64ad5f?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a68f5e64ad5f</guid>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 06:12:06 GMT</pubDate>
            <atom:updated>2022-09-02T06:12:06.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hSxvceRzVP7884_XplGJw.jpeg" /><figcaption>Abstract calendar with booked dates view</figcaption></figure><p><em>How to efficiently filter by rental resource availability</em></p><p>While looking into a house rentals website, I noticed an interesting problem: How do they filter the results by booking availability?Here’s Airbnb’s UI for this just so the feature I’m discussing is clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*HyJVsa4HGd3d9ida.png" /></figure><p>The search on that website was blazing fast even with tons of results, and it was using Algolia (probably closer to NoSQL, custom search engine in C++), so I knew there was no slow ‘JOIN’s happening in the background. The filters also included other details related to houses.I’ve worked with Elasticsearch and other NoSQL databases, and from a data modeling perspective there has to be some embedded field that the query was using to filter by available dates for it to be this fast.</p><p>After looking into the problem for a couple of hours and finding zero write ups on this, I decided to break it down in this post.So what are the functional requirements here?</p><ul><li>Filter results by a start and end date</li></ul><p>Non-functionally, we just want to use a pre-existing database, so we can’t come up with custom data structures here.</p><h3>Building this with a JOIN</h3><p>Given a table with room reservations (one entry per day reserved for example), we can use this query to filter our results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*OykUUXr8hjoioune.png" /></figure><p>This does result in an expensive JOIN however.</p><h3>Importance of this feature</h3><p>In any ‘resource’ rental application, this search feature is probably going to be the most used feature in the app. So an expected minimum number of queries per day is going to be #DAUs x 5. If this feature is slow then your users are probably going to try another site instead.To avoid JOINs, the easiest workaround is embedding some field on each entry. The filtering would also be a lot faster since it doesn’t have to combine entries from two tables to do the filtering.</p><h3>So what do we embed?</h3><p>First thought that comes to mind is embedding a list of reserved date tuples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*5KF7O4QW73zLRjNY.png" /></figure><p>But this is hard to search efficiently. No database offers filtering on an array of date tuples with a numeric range.</p><p>I think finding the right solution here was extra hard for me because I was unconsciously trying to store all this information in one document. The solution became clearer when I relaxed that constraint and allowed partial duplication.</p><p>The solution I came to is the following: For every available time range, we store a new document for this resource. Now that we have ‘available_from’ and ‘available_to’ fields, it’s easy to filter by a numeric range.</p><p>White is available, black is booked/unavailable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HA2Wzy2MIhfJgWBM.jpg" /></figure><p>With a little bit of extra storage, we’ve massively sped up this query.</p><p>The new query looks something like this, and can be run pretty efficiently (just a numeric range query):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*YYZwdQdvOKKdX7u_.png" /></figure><p>Now how do we populate this data? Upon every reservation made, we’ll have to do some post-processing and update these documents / generate new ones as well.</p><p>Keep in mind that this isn’t suggesting you store your primary data like this. Think of this more of a replica of your data or a completely separate collection/table. In some examples below we completely delete the resource document, which is a problem if it’s your primary data source.</p><h3>Does this cover everything?</h3><p>To check that this solution covers all cases, here are all the edges I can think of:</p><ul><li>If the rental request covers a subset of the available range, then the resource document is just updated to reflect the new range, and potentially a new document is added to show availability on the other edge. Ex. someone books 3 only here.</li><li>Resource availability has a finite range (ex. available from x to y only) and the booking completely covers this range (x to y request to book). In this case we just delete the remove the document. It might be that the resource is available in the future, but that’s a separate document in the resources collection.</li><li>Rental request splits an infinite range (as in the first image posted above). In this case we also get two documents out of it, unless the rental request was on the left edge. In that case the document is only updated:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x7UMa56aZxv0EI4H.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-POCzAAh4Lk5x1_V.jpg" /></figure><h3>Conclusion</h3><p>Sometimes duplicating documents with different properties can provide us with clever ways to do efficient search. The rental availability search problem seems like a prevalent problem in many applications, and we shed the light on an efficient solution that doesn’t involve any joins in this writeup.</p><p>I hope you enjoyed this design deep dive! If you’d like to see more of this, make sure to subscribe to this newsletter to let me know that you’re interested! Right below is a link to sign up.</p><p>You can find me on Twitter every day <a href="https://medium.com/twitter.com/iamramiawar">@iamramiawar</a>, feel free to shoot me a DM!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a68f5e64ad5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SvelteKit $lib Alias Setup]]></title>
            <link>https://ramiawar.medium.com/sveltekit-lib-alias-setup-1252c05742db?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1252c05742db</guid>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[sveltekit]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 04:12:24 GMT</pubDate>
            <atom:updated>2022-08-03T04:12:24.777Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*G85xIKcwbXRx7bIw" /></figure><p>Two steps are needed to get the $lib alias working in your SvelteKit project:</p><ol><li>Add the following paths key to your tsconfig.json or jsconfig.json</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/609d0cd53812fffc7b8cc9a81c9ec323/href">https://medium.com/media/609d0cd53812fffc7b8cc9a81c9ec323/href</a></iframe><p>2. Add the following resolve section to your vite.config.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cb4aefb1176b5b85fdfa918b37aec09/href">https://medium.com/media/7cb4aefb1176b5b85fdfa918b37aec09/href</a></iframe><p>That’s a wrap! Reload your editor for the changes to take effect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1252c05742db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Superpet: A Developer’s Best Friend]]></title>
            <link>https://ramiawar.medium.com/superpet-a-developers-best-friend-c99038979ef2?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99038979ef2</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[snippet-manager]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Mon, 04 Jul 2022 12:10:23 GMT</pubDate>
            <atom:updated>2023-11-29T23:40:06.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7__gjPgUBriE_QhE.jpg" /></figure><p>Pet is a command line snippet manager written in Go that has massively sped up all my command line work. I’ve extended it into <a href="https://github.com/RamiAwar/superpet">Superpet</a> to allow environment variable management as well, and I found it to be a huge time saver and worth sharing with others.</p><p>Edit: I’ve since become a collaborator on Pet! I’ll be adding in all the sweet Superpet features in and more when I have some time!</p><p>I’ll first quickly describe Pet, and then explain what <a href="https://github.com/RamiAwar/superpet">Superpet</a> is and show usage examples. I won’t write too much as I think the examples are sufficient to sell the idea.‌<br>‌‌<br>‌Pet gives you the ability to create snippets, tag them, search them, list them, and even parametrize them. It also automatically syncs any changes I make to my snippets across machines through free Github gists. (Yes, you heard that right. There can exist a sync feature without having to pay a monthly fee. I nearly forgot that such things could exist!)</p><p>Here are a bunch of useful features of Pet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*E1ddurjVKYxyHnlm.png" /><figcaption>Example of searching for a command to execute with ctrl+s or pet exec</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*ByVnW6EW7QxXuXbK.png" /><figcaption>Parametrized Pet snippet for deleting all documents from an Elasticsearch index</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*PX9aWn9v78nhmWqm.png" /><figcaption>Pet list command, showing a bunch of command snippets I’ve saved</figcaption></figure><p>‌Pet really streamlined my workflow, but I felt that it could do even more. Managing environment variables is a very similar problem to managing snippets: you’d normally have a bunch of environment variables associated with doing a single task. For this reason, it made sense to group them in one place and have the ability to call upon them as we do with snippets.‌<br>‌</p><p>To use <a href="https://github.com/RamiAwar/superpet">Superpet</a>, you can use the following commands for managing env vars. Similar to many “environment activation” tools out there (think virtual environments in Python), <a href="https://github.com/RamiAwar/superpet">Superpet</a> is able to “activate” an environment for you, inheriting the current environment variables and extending them with those of the namespace specified.‌</p><pre>$ superpet listenv</pre><pre>$ superpet activate  # Similar to pet exec, but searches environments<br>					 # and activates them</pre><pre>$ superpet editenv</pre><pre>$ superpet newenv  # Creates a new environment‌</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*elFimI_AilpyKd5Z.png" /><figcaption>Creating a new environment example</figcaption></figure><p>‌When listing environments, <a href="https://github.com/RamiAwar/superpet">Superpet</a> hides the values of the variables, but shows their names to better describe the environment.‌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*quuN-gAUW8tYp2eg.png" /><figcaption>Example of listing all environments</figcaption></figure><p>It’s also easy to edit the environments and snippets using superpet edit and superpet editenv. All the snippets/environments are saved in .toml files that are stored in ~/.config/pet/ by default.‌<br>‌‌<br>‌To activate/deactivate environments:‌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/0*C7AgUELjLRtOTY50.png" /><figcaption>Activate Superpet environment shell</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/0*QT75doxNSDpgb43E.png" /><figcaption>Exit Superpet environment shell</figcaption></figure><p>We’ve also started using <a href="https://github.com/RamiAwar/superpet">Superpet</a> to streamline onboarding. Providing newcomers with a bunch of preconfigured snippets and environments would supercharge their onboarding experience. Installation instructions can be found in the repository.</p><p><a href="https://github.com/RamiAwar/superpet">GitHub - RamiAwar/superpet: Simple command-line environment and snippet manager, written in Go.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99038979ef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Services Need Observability]]></title>
            <link>https://ramiawar.medium.com/why-services-need-observability-5146cdb21c59?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5146cdb21c59</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Thu, 28 Oct 2021 10:22:09 GMT</pubDate>
            <atom:updated>2021-10-28T10:23:22.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b9C2doVa7GRw9Los.jpg" /></figure><p>In our current world of massively distributed systems, the number of points of failure in software services has skyrocketed. Due to this, the need for a way to gain insights into distributed systems for error detection, debugging, and business analysis has emerged. Enter buzzword, Observability.</p><p>To break down observability, we’ll tag along Sophia’s journey building a microservice for her health app. One of the API routes allows for uploading images (used when logging meals for example).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c0df386fd85fd97c509981797106bc4/href">https://medium.com/media/8c0df386fd85fd97c509981797106bc4/href</a></iframe><p>One month after deploying this feature, a customer complains that image upload is not working. After spending some time debugging, Sophia figures out that her document storage server had run out of memory and has been down for a whole month! This meant that customers were getting upload errors all throughout the past month, and Sophia’s team was none the wiser. After fixing the issue, the team <a href="https://sre.google/sre-book/postmortem-culture/">gathers for a post-mortem meeting</a>.</p><p><em>How could this have been detected sooner?</em></p><h3>Monitoring</h3><p>The first pillar of observability is monitoring. This could be as simple as checking that a server is up (health check), setting up alerts when some metric (ex. CPU usage) exceeds some threshold, or tracking more complicated metrics with dashboards.</p><p>As an attempt to prevent this issue from recurring, Sophia setup an automatic health check that would ping the document storage server every 5 minutes and alert her if it was ever down.</p><p>Some solid principles on how and what should be monitored can be <a href="https://sre.google/sre-book/monitoring-distributed-systems/">found in Google’s SRE book</a>.</p><h3>Probing further</h3><p>As Sophia’s company grew, another team became responsible for storing documents of all types (health report PDFs, images, internal documents, …). For this purpose, they built a storage microservice and deprecated the old document storage server. Sophia’s service also grew, and is now composed of several instances behind a load balancer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04cc162b484a8c33acc962e0a67c68bf/href">https://medium.com/media/04cc162b484a8c33acc962e0a67c68bf/href</a></iframe><p>Now a request to upload an image would internally send a request to the storage microservice. Sophia’s distributed system was growing in complexity.</p><p>Some reports started coming in about images failing to upload, even though some images were being successfully uploaded by other users. Is the problem from Sophia’s service? Could it be that the image format is invalid? Or is the issue from the storage service? Could that be overloaded or mishandling saving some image formats? Is the error from the health application itself (frontend)?? Is the load balancer failing to forward some requests? Debugging this has become harder, and this is in fact <a href="https://tsh.io/blog/what-are-microservices-in-2020-key-findings-from-survey-report/">one of the biggest problems facing distributed systems developers nowadays</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AhQc9YfD_ji8WZZT.jpg" /></figure><p>As the system grows, debugging complexity increases at an exponential rate. After spending <strong>too long</strong> on this, Sophia and the other team realized that the .jpeg image format was not among the accepted formats by the storage microservice, even though it was a valid format in Sophia&#39;s validation function. Post-mortem organized, questions asked.</p><p>How do we detect such a bug before users report it? How do we debug this without guesswork? What can we do to reduce the search space from too many points of failure to just a few?</p><h3>Tracing and Logging</h3><p>What we need here is the second and third pillars of observability, tracing and logging. A trace represents the journey of a request as it propagates through a distributed system. By tracing requests, we can also monitor them and create alerts when we have a significant number of failures for a certain route.</p><p>With this tool, Sophia setup a tracing library (<a href="https://opentracing.io/">ex. OpenTracing</a>) and connected that to a dashboard (<a href="https://www.jaegertracing.io/">ex. Jaeger Tracing</a>). From this dashboard, her whole team can see <em>aggregate request statistics</em>, like some image upload requests failing before customers report anything. They can also trace requests through their system, and directly see that the <em>failures are coming from the storage microservice</em>. Notice how much the problem search space has been reduced.</p><p>Note that aggregating these statistics is really important, as Sophia’s “service” is actually bunch of services acting as one using a load balancer. Traditional debugging is no longer sufficient in this case, as the problem could be caused by the distributed nature of the system and not be replicable in isolation!</p><p>As for logging, Sophia setup some logging functions to log exceptions after catching them. Her team also used these loggers to add informative logs throughout the application and routes, logging the request ID with each call. They aggregated these logs using some logging aggregation service (<a href="https://www.elastic.co/logstash">ex. Logstash</a>). Log aggregation is necessary since the service is actually a bundle of services, and examining every instance’s logs is simply not feasible. Searching logs for a particular request ID to complement the traces is also helpful when debugging. This might very well allow us to find the problem without digging any deeper.</p><h3>One more?</h3><p>One day, while a product manager was uploading a meal image, he noticed that the upload was exceptionally slow. He remembered trying it the other day and it was at least twice as fast. Naturally, Sophia was called and the bug was logged. That seemed strange to Sophia, as none of her teammates touched the image upload code.</p><p>The slowdown had to be coming from the storage microservice. After contacting them, it turns out that they had added a compression mechanism to the upload route, and accounted for the slowdown. Naturally, Sophia mentioned that the slowdown was affecting their customers, and that the compression should take place after the upload is done as a background job.</p><p>This one’s a tricky one. How could they have known sooner? How can a team detect such performance regressions as soon as they happen? (Without adding performance end-to-end tests that is!)</p><p>The answer to that is by monitoring and analyzing request-response times. Statistical anomalies can be attributed to performance regressions/improvements. Setting up such a system is way easier than it sounds thanks to open source. Tools like Jaeger tracing offer root-cause analysis out of the box. Another very powerful open source tool that I haven’t mentioned is <a href="https://www.elastic.co/apm">Elastic APM</a>.</p><p>Larger companies that ship B2B software and have to deliver on performance would instead run performance tests (E2E tests with stats that are compared to historical stats), but that is a very tiny portion of software when compared to what’s out there.</p><h3>Wrapping Up</h3><p>When developing distributed systems, observability becomes a key part of the stack. With complete observability over their services, Sophia’s team reaps many benefits:</p><ul><li>Business developers automatically get API usage analytics, allowing them to make data-backed decisions about what direction to take their product in (ex. unused meal logging image upload might indicate that developing an image analysis feature is not worth the effort)</li><li>Engineers get alerts when any of their services need their immediate attention (ex. servers down, service overloaded, …)</li><li>Debugging time is massively reduced, as tracing and logging help pinpoint the source of the problem</li><li>Analyzing traces and API route metrics allows for detecting regressions due to recent code changes (ex. image upload taking twice as long after last deploy, which means that change had a massive performance impact)</li></ul><p>As a final note, there are many services that offer plug-and-play observability, which would involve installing an ‘agent’ on all your instances and easily integrating a library in your codebase. Some examples are <a href="https://instana.io/">Instana</a>, <a href="https://www.datadoghq.com/">DataDog</a>, and <a href="https://stackify.com/">Stackify</a>, all of which I’ve personally tried and had a good experience with. Their integrations are equally easy and smooth, however they differ in features. One of those features is continuous profiling, which is worthy of its own post. This ease of integration has made observability accessible even to the busiest of teams.</p><p>This post is originally published on <a href="https://softgrade.org/">https://softgrade.org</a> . To get the print hot off the press, consider subscribing as a free member there! Medium posts will follow after a couple of months.</p><p><a href="https://softgrade.org/">Softgrade</a></p><h3>Further Reading</h3><ul><li><a href="https://sre.google/sre-book/monitoring-distributed-systems/">Google SRE Book — Monitoring Distributed Systems</a></li><li><a href="https://www.manning.com/books/microservices-in-action">Microservices in Action — Chapter 11, 12</a></li><li><a href="https://blog.codinghorror.com/the-problem-with-logging/">The Problem with Logging — Jeff Atwood</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5146cdb21c59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Testable Code]]></title>
            <link>https://medium.com/javarevisited/how-to-write-testable-code-d23a5f1dac2e?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d23a5f1dac2e</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Sat, 02 Oct 2021 17:49:49 GMT</pubDate>
            <atom:updated>2021-10-28T10:18:36.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*FGv3mXLE4DzHT1Q0.jpg" /><figcaption><a href="https://softgrade.org/writing-testable-code/">https://softgrade.org/writing-testable-code/</a></figcaption></figure><p>This post is not about Test Driven Development, or testing best practices, or any advanced concept in testing. Instead, the goal is to recommend a simple mindset change that allows for <a href="https://softgrade.org/writing-testable-code/">writing testable code</a> without needing to write any tests first.</p><p>The point of this is to <strong>eventually</strong> write tests, because not every team has the luxury of test driven development. This mindset change will allow writing code that can be easily tested at a later point in time, and that carries some of the benefits of <a href="https://javarevisited.blogspot.com/2019/04/top-5-junit-and-unit-testing-courses-java-programmers.html#axzz6qnblZnVj">TDD </a>without having to write tests beforehand.</p><h3>But first, a story…</h3><p>Will has just joined an online education company as a software engineer. His first task was to add a class average metric to a job that runs after an exam is completed.</p><p>The product manager explains the task clearly, and Will digs into the code. After asking a coworker, he figures out where the code for this job lies and finds the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ab47a2e47111addce64ed92cc3c47ad/href">https://medium.com/media/3ab47a2e47111addce64ed92cc3c47ad/href</a></iframe><p>Seems like an easy enough job, Will modifies the code to add an average statistic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3630e6726e4e45707e3af1513cf0dec6/href">https://medium.com/media/3630e6726e4e45707e3af1513cf0dec6/href</a></iframe><p>Excited to have finished the task pretty quickly, the only thing left was to make sure that his implementation works without breaking anything. After such a check, he could commit the code with confidence.</p><p>Talking to his coworker again helps him understand how to test the platform, so he goes ahead and creates a new class, creates an exam, creates two students, logs in as each and submits the exam. The post exam job runs, and luckily, the results seemed fine.</p><p>However, it took Will half a day to setup the end-to-end test and create all that dummy data. It would also take him around an hour to do this again in case someone requested another change to this piece of code. He’d have to try an end-to-end test with multiple input examples to try to cover edge cases.</p><h3>Productivity Drains</h3><p>In the above story, Will encounters multiple potential productivity drains that affect his independence as a <a href="https://medium.com/javarevisited/10-books-java-developers-should-read-in-2020-e6222f25cc72">developer</a>, his coworkers’ productivity, and his speed and confidence in committing changes to the code. Having tests would probably solve all of these problems:</p><ul><li>Test suites act as documentation (no heavy dependence on coworkers)</li><li>Running tests will make sure the change did not break any previous functionality, and ensure new functionality works as expected</li><li>Writing tests will make the developer think about edge cases</li></ul><p>But you probably don’t need any convincing on the usefulness of tests. The above drains would also be encountered if Will was an<a href="https://javarevisited.blogspot.com/2018/02/top-5-java-design-pattern-courses-for-developers.html"><em> experienced developer</em></a> at the company.</p><h3>Let’s talk about Testability</h3><p>Our definition of testability will be simply how easy it is to test a certain piece of code. Consider this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76b3957c0dd9bcb540d8c4081cd8fde4/href">https://medium.com/media/76b3957c0dd9bcb540d8c4081cd8fde4/href</a></iframe><p>For the change Will introduced, the only part that would need testing is the newly introduced average score (Let’s ignore the meaning of a schema change for this db for simplicity). It would have sufficed if Will wrote a test for max_score, min_score, and avg_score to confirm that his code will work.</p><p>The issue is with the way the code is organized. It’s hard to test with the presence of dependencies on a database (and potentially many other things in production code). A more “testable” code would be the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63621d8a728a6639de0736ddbef47569/href">https://medium.com/media/63621d8a728a6639de0736ddbef47569/href</a></iframe><p>If we wanted to write a test for this code, we could simply test calculate_stats with some dummy data.</p><p>The change needed to go from untestable to testable in this example is pretty simple to make, which isn’t the case in the real world. This toy example serves to illustrate that just adopting a testable code mindset will result in testable functions, which we could easily write tests for sometime in the future.</p><p>If the code Will came across was testable, he would have modified the code, then wrote a test to confirm that it works as expected. There would have been no need for setting up an end-to-end test and wasting time populating frontend dummy data then running the whole job to check if it works for different inputs.</p><p>This would probably be different if Will saw complicated dependencies throughout the code. Adding tests to such code requires refactoring large sections, and as a newcomer, that is very hard to do since it requires knowledge of the code. Over time, Will would probably get used to the untestable code style and low levels of productivity.</p><p>Example of testable code with the addition of a test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/932b66183519901c0cc07fa6ed673928/href">https://medium.com/media/932b66183519901c0cc07fa6ed673928/href</a></iframe><p>This shows us how testable code (even if we ignore the test) has achieved the following:</p><ul><li>Code documentation (stats extraction is in its own function called calculate_stats)</li><li>Ease of writing tests (since code is properly separated) compels developers to add tests</li><li>Gives developers the confidence to make changes quickly by creating and running tests</li></ul><p>The above code would also be the outcome of applying a separation of concerns pattern but reached differently by simply thinking of code testability. The benefits of such a mindset exceed those of <a href="https://medium.com/javarevisited/7-best-online-courses-to-learn-object-oriented-design-pattern-in-java-749b6399af59?source=---------10------------------">extensive design pattern knowledge</a>. Simpler foundations result in more elegant, developer-friendly code.</p><p>In summary, adopting a mindset of writing testable code yields many benefits; free documentation, ease of adding tests in the future, and increasing confidence in committing changes due to simpler code are just some of them. This is the essence of <a href="https://medium.com/javarevisited/5-best-junit-and-test-driven-development-books-for-java-developers-2d3fecb5c9ac">test-driven development</a>, without forcing a tests-first approach.</p><p>This post is originally published on <a href="https://softgrade.org/">https://softgrade.org</a> . To get the print hot off the press, consider subscribing as a free member there! Medium posts will follow after a couple of months.</p><p><a href="https://softgrade.org/">Softgrade</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d23a5f1dac2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/how-to-write-testable-code-d23a5f1dac2e">How to Write Testable Code</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running MongoDB on Android]]></title>
            <link>https://medium.com/pumpkinbox-blog/running-mongodb-on-android-7e90cbe52651?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e90cbe52651</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[termux]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[unix]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 13:42:37 GMT</pubDate>
            <atom:updated>2020-12-29T13:42:37.584Z</atom:updated>
            <content:encoded><![CDATA[<p>A short guide on installing a MongoDB server as a service on Android over SSH from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*suRKbdoC3RKin83A_HjAuQ.png" /></figure><h3><strong>Installing</strong> OpenSSH</h3><p>Step one, we need to SSH into our phone. Make sure your computer and android device are on the same network. Download Termux to get access to a unix environment on your android.</p><p><a href="https://play.google.com/store/apps/details?id=com.termux&amp;hl=en&amp;gl=US">Termux - Apps on Google Play</a></p><p>Run Termux and install OpenSSH.</p><pre>apt install openssh</pre><p>To setup a passwordless ssh access (which is required when using Termux for reasons out of the scope of this guide), we need to copy our public ssh key from our computer to our android device, and add it to the authorized_keys. I won’t go into the details of generating an SSH key and explaining pub/priv keys here, so refer to another guide for this part. Once you have the key on your android device, you can run the following. (Note that you might have to change the permissions as necessary for SSH to work)</p><pre>mkdir ~/.ssh<br>touch ~/.ssh/authorized_keys<br>cat &lt;my_id_rsa.pub&gt; &gt; ~/.ssh/authorized_keys</pre><p>Now we can run the ssh daemon using:</p><pre>sshd</pre><p>At this point we can log in to our android device through ssh and its ip address, and it should not ask for a password, for example:</p><pre>ssh 192.168.0.100</pre><h3>Installing MongoDB Server</h3><p>Step two is installing MongoDB. For this, another guide offers some helpful tools for setting this up:</p><p><a href="https://medium.com/swlh/running-mongodb-server-on-android-da7e7de3d24c">Running MongoDB Server on Android</a></p><p>Summarizing the steps mentioned there,</p><pre>pkg install curl<br>curl -LO https://its-pointless.github.io/setup-pointless-repo.sh<br>bash setup-pointless-repo.sh<br>pkg update<br>pkg install mongodb</pre><p>At this point, mongod and mongo are installed (server and client respectively). To run the server, simply:</p><pre>mongod --bind_ip=0.0.0.0</pre><p>Binding the IP is needed if you wish to access the database from another device through the IP address of the android device.</p><p>What is left is to set up mongod as a service, having it run automatically and have its lifecycle managed by a tiny service manager on Termux.</p><p><a href="https://wiki.termux.com/wiki/Termux-services">Termux-services</a></p><pre>pkg install termux-services<br>exec &quot;$SHELL&quot;</pre><p>We can now run sshd as a service using:</p><pre>sv-enable sshd</pre><p>We can check the status of the service using:</p><pre>sv status sshd</pre><p>As a final step, we can write our own service.</p><pre>cp -r $PREFIX/var/service/sshd $PREFIX/var/service/mongod</pre><pre>echo &quot;exec mongod --bind_ip=0.0.0.0 2&gt;&amp;1&quot; &gt; $PREFIX/var/service/mongod/run</pre><pre>ln -sf $PREFIX/share/termux-services/svlogger $PREFIX/var/service/mongod/log/run</pre><pre>exec &quot;$SHELL&quot;</pre><p>And now we can run a MongoDB server as a service using:</p><pre>sv-enable mongod</pre><p>Hope someone finds this useful, sorry for not going into more details but this is more of a summary guide than an in-detail guide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e90cbe52651" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pumpkinbox-blog/running-mongodb-on-android-7e90cbe52651">Running MongoDB on Android</a> was originally published in <a href="https://medium.com/pumpkinbox-blog">PumpkinBox Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Procedural Map Generation with Godot — Part 3]]></title>
            <link>https://medium.com/pumpkinbox-blog/procedural-map-generation-with-godot-part-3-c0c57ae7c949?source=rss-4710ac41d86b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0c57ae7c949</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[godot]]></category>
            <category><![CDATA[procedural-generation]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Rami Awar]]></dc:creator>
            <pubDate>Wed, 13 May 2020 20:22:19 GMT</pubDate>
            <atom:updated>2021-08-27T05:54:57.080Z</atom:updated>
            <content:encoded><![CDATA[<h3>Procedural Map Generation with Godot — Part 3</h3><h4>For previous articles in this series, visit <a href="https://medium.com/pumpkinbox-blog/procedural-generation-series">https://medium.com/pumpkinbox-blog/procedural-generation-series</a></h4><p>In this post, we’ll be setting walls throughout the map, going over breadth first search and starting to post-process the generated grid to get it closer to what our vision of the map is. This is what we’ll achieve by the end of this post:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*kJLGMRMh5O9W7z9VHgFhVA.jpeg" /><figcaption>Final result of 3rd post</figcaption></figure><p>To create the walls you see below, we have to find the edges of the generated map. That can be done by checking every floor tile for any surrounding empty tiles. If an empty tile exists around a floor tile, then that tile should be a wall. One tiny note problem we get using this tileset is that the dirt tiles are 16x16, while the wall tiles are 32x32. To overcome this, we can change the CellSize to 32x32 in our code, and when placing dirt tiles, place 4 in a square to get a 32x32 tile. Minor inconvenience but easier to solve it than create our own tileset for the time being. Let’s code that quickly:</p><p><a href="https://gist.github.com/RamiAwar/cd346b781b8410c4a1d084d6f15f823c">LINK TO CODE</a></p><p>We get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*gGn3phzKy9db6wrCIfhkUw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*NWiJXLCAPUB5NL0PjdA9jw.jpeg" /></figure><p>One thing we can do to make this look better automatically is replace all the empty tiles with wall tiles as well, so we don’t get these gaps. That would make things look more natural, and its a tiny modification to our code (We also need it so that when we check for single tiles, the single tiles — discussed below — on the edges are not counted).</p><p>The thing that stands out the most in this map is the single tiles. We have so many single tiles generated, with no neighbors, and I feel that they serve no real purpose and aren’t very aesthetic, so let’s remove those. Similar to what we did before, we need to loop over the grid, and any wall tile that has no neighbors should be converted to a dirt tile.</p><p><a href="https://gist.github.com/RamiAwar/6617a78b5e937434c5ea43df484d5777">LINK TO CODE</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*s99xZGHz9lUHNhD9mBa1Zg.jpeg" /><figcaption>Removing all singleton walls, filling empties with walls</figcaption></figure><p>Our map is starting to look good! One more thing we obviously don’t want is leaving openings to the out of bounds area, so we also need to line up the edges with walls. We can do that by modifying our loops to process tiles from 1 -&gt; width-2 instead of 0 -&gt;width-1, and the same goes for the height. We get the following result:</p><p><a href="https://gist.github.com/RamiAwar/fb0a2aaa05dd219b28c6cd9c4b04fcb2">LINK TO CODE</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*3ISUAjplIDgYQB0pdPN3pw.jpeg" /></figure><p>Now, let’s get our hands <strong>actually</strong> dirty. Graph algorithms. Let me describe what I want to achieve. This exercise will serve as the foundation for alot of the things you will want to do with your grid. Having a strong foundation in graph algorithm problems will help here, because without proper exposure to such problems, it might be hard to translate your thoughts into code, or at least efficient and feasible code. So without further ado, let’s define what we want to achieve. We want the dirt tiles to only be in positions that are at least one position away from the walls. This picture clarifies what I mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*IW2BfEHnwQNARmtL_ET7ig.jpeg" /><figcaption>Zoomed out image , 2048x1216, dirt tiles with margin</figcaption></figure><p>Basically, we need to find an algorithm to do this. Graph algorithms are really challenging at first if you don’t know the basics of graph search, but become pretty simple pretty fast once you do. A good starting point is reading up on depth first search and breadth first search. There are many good tutorials out there, and tons of material on these subjects, so I won’t waste both our times explaining that here. Here are some example problems that start out simple.</p><ul><li><a href="https://leetcode.com/problemset/all/?topicSlugs=graph">Problems - LeetCode</a></li><li><a href="https://leetcode.com/problems/flood-fill/">LeetCode - The World&#39;s Leading Online Programming Learning Platform</a></li><li><a href="https://leetcode.com/problems/as-far-from-land-as-possible/">As Far from Land as Possible - LeetCode</a></li></ul><p>The last problem is very similar to what we’d like to do.</p><p>To classify each tile as dirt or not dirt, we need the <strong>distance</strong> from that tile to the <strong>closest </strong>wall. If we had that distance in some way, then we can use it to decide whether or not this tile is a dirt tile, or floor tile. For example, if this distance is greater than 2, we can classify the tile as a dirt tile. We will get a grid similar to the one shown above. To find this distance, we can perform a breadth first search from the known nodes, which are the walls. Each wall has a distance of 0, since it is closest to itself. Starting from the walls and moving outward in a breadth first manner, we can set the distance on the floor tiles surrounding that wall. Check the example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*2-bpTXK1cRf5BvK2WdBPmA.jpeg" /></figure><p>To do a BFS, we add all wall nodes into a queue, then we keep processing until the queue is empty. For every node, we check its 8 neighbor nodes, and if they are not yet visited, we set their distance to the current distance + 1. The distance set is guaranteed to be the minimum of all distances to walls since we are doing a BFS. If we were doing this with a DFS then we’d need to make sure we’re setting the minimum distance, and things would be less efficient. After processing the node we remove it from the queue while adding all its neighbors to the queue for later processing. It might take some time to wrap your head around this algorithm, specially if you’re not very comfortable working with graphs, but once you dedicate a couple of hours to graph problems this will be a breeze. Coming up with other algorithms like this one will become just as easy. Let’s take another look at the result:</p><p><a href="https://gist.github.com/RamiAwar/334420bda3cada8d2a1bd418a7ca1047">LINK TO CODE</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*TeYe_UwIL0XmC4iHjYMsEg.jpeg" /><figcaption>Breadth first search to determine dirt locations</figcaption></figure><p>One thing that’s reducing from the perfection of this map is the diagonally positioned dirt tiles. I didn’t like them much, so I made a pass over the grid to check for tiles with such positions. For example a dirt tile with a lower right dirt neighbor but no bottom dirt and no right dirt neighbors. Then we simply remove them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*gcEAslw66tPgSPEGEDY3PA.jpeg" /><figcaption>Removing diagonally positioned dirt tiles</figcaption></figure><p><a href="https://gist.github.com/RamiAwar/1acc33e2db3724ae713429f7eb4e132a">LINK TO CODE</a></p><p>We could also do this to the walls, as these diagonally placed tiles just don’t look natural.</p><p>Honestly, we could do infinitely many modifications to this to turn it into whatever our imagination whips up. I think for now, this is enough of a foundation for anyone to build upon, so we can move on to other things, like placing objects in the map. Things like trees, bushes, flowers, shrubs, etc. That will give our map some more variety and make it look much prettier up close. For that, we’ll use poisson distributions to equally spread out the randomly spawning items across the grid, making sure that they’re in positions within the walls. We will also clear the dirt tiles around some of the objects, since plants wouldn’t grow on dirt in our imaginary world! For that, stay posted for the next writeup.</p><p>Instagram: <a href="https://www.instagram.com/pumpkinboxstudio/">https://www.instagram.com/pumpkinboxstudio/</a></p><p>About Me</p><p>I’m a backend engineer working <a href="https://medium.com/u/e95d5df7af36">Proton.ai</a>, and I write about backend architecture @<a href="https://softgrade.org/">Softgrade</a> and game dev on Medium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0c57ae7c949" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pumpkinbox-blog/procedural-map-generation-with-godot-part-3-c0c57ae7c949">Procedural Map Generation with Godot — Part 3</a> was originally published in <a href="https://medium.com/pumpkinbox-blog">PumpkinBox Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>