<?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 Arjun M on Medium]]></title>
        <description><![CDATA[Stories by Arjun M on Medium]]></description>
        <link>https://medium.com/@genzarjun?source=rss-10e512a8e591------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3l2ILFSu_iv9E2u1</url>
            <title>Stories by Arjun M on Medium</title>
            <link>https://medium.com/@genzarjun?source=rss-10e512a8e591------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:47:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@genzarjun/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[“Failed to Fetch” to “Registration Success”]]></title>
            <link>https://medium.com/@genzarjun/failed-to-fetch-to-registration-success-10bf82b73a99?source=rss-10e512a8e591------2</link>
            <guid isPermaLink="false">https://medium.com/p/10bf82b73a99</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[google-app-script]]></category>
            <dc:creator><![CDATA[Arjun M]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 04:34:42 GMT</pubDate>
            <atom:updated>2026-01-02T04:34:42.854Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Populating Registrants From Your Website Into Google Sheets</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AO4nycSHrnhAasxL.png" /></figure><p>I have been starting to explore how to use Google Apps Script with Google Sheets and call its Web App URL directly from my website and man did I face some issues that kept me stuck.</p><p>It started off when a user filled out a form, they would get a beautiful success toast message: ✅ <em>“Registration Received! 🎉” </em>But when I checked the Google Sheet where all registrations were supposed to land, I couldn’t see anything. I sat there, staring at my React code, then at my Apps Script console, scratching my head. Everything <em>looked</em> correct. The fetch request was being called. The validation was working. The success message was firing. But somehow, the registration data was vanishing into the digital void like it never existed.</p><p>Here’s what I had built:</p><ul><li>Frontend: A React registration form running on Hostinger</li><li>Backend: Google Apps Script deployed as a web app</li><li>Destination: A Google Sheet to store responses</li></ul><p>The form would collect data (name, email, school, grade, team info), package it up as JSON, and send it via fetch() to my Apps Script endpoint. The script would parse the JSON and append a new row to the sheet.</p><p>Here were the two errors that was causing issues in my code:</p><ol><li><strong>The Logic Error (</strong><strong>mode: &#39;no-cors&#39;):</strong> By using no-cors, the frontend assumed success because the browser technically completed the request, but it couldn&#39;t see that the server hadn&#39;t actually processed the data or returned a valid response.</li><li><strong>The Infrastructure Error (Deployment):</strong> Even if the code was perfect, the Google Apps Script was running an old version. In Apps Script, clicking “Save” doesn’t update the live URL; you must manually create a <strong>new deployment</strong> for changes to take effect.</li></ol><p>Lets dive into the 1st issue . . .</p><h3>What is CORS Anyway?</h3><p>CORS stands for Cross-Origin Resource Sharing. It’s a browser security feature.</p><p>Here’s the scenario:</p><ul><li>Your website is at <a href="https://myapp.com/">https://mywebsite.com</a></li><li>Your backend is at <a href="https://script.google.com/macros/s/ABC123/exec">https://script.google.com/macros/s/ABC123/exec</a></li></ul><p>These are different origins (different domains). Browsers treat this as potentially dangerous. What if a malicious website tried to steal your user’s data by making requests to Google on their behalf?</p><p>So browsers implemented CORS: a way for a server to explicitly say, “Yeah, I allow this website to talk to me.” In this case, Google allowing my website to communicate with it.</p><blockquote>You don’t need to use CORS if your frontend is on mywebsite.com and your backend is also on mywebsite.com</blockquote><h3>Mode: &#39;no-cors&#39;</h3><p>I had added mode: &#39;no-cors&#39; to my fetch request—a common workaround for cross-origin issues. The reason? My React app was running on a different domain (mywebsite.com) than Google&#39;s Apps Script (script.google.com). Browsers don&#39;t like that by default.</p><p>With mode: &#39;no-cors&#39;, the browser would send the request without waiting for or reading the response. It felt like it should work. But here&#39;s the trap: the browser always resolves the fetch successfully with no-cors, even if the request never reaches the server.</p><p>So my code would always show “Registration Received! 🎉” — whether the data actually got to Google or not.</p><p>I checked my Apps Script execution logs and found nothing.</p><pre>const response = await fetch(<br>  &#39;https://script.google.com/macros/s/AKfycbw_5nCzlSSG_K_pnKuxCUuFcPvkm11eCGGWx3EV74RDjkzN9VfGa2tC55DxMOfTnjq1pg/exec&#39;,<br>  {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;text/plain;charset=utf-8&#39;,<br>    },<br>    body: JSON.stringify(payload),<br>    mode: &#39;no-cors&#39;, // The culprit?<br>  }<br>);<br><br>// This ALWAYS resolves, even if the request failed<br>toast({<br>  title: &quot;Registration Received! 🎉&quot;,<br>  description: &quot;We will send you email updates soon!&quot;,<br>});</pre><h3>The Real Issue: CORS (And Why I Didn’t Understand It)</h3><p>Once I had a clean deployment, things started working. But I wanted to understand <em>why</em> it mattered and what was actually happening with CORS.</p><p>Let me break it down for you — because it took me a while to get it.</p><h3>The CORS Handshake</h3><p>Think of it like a bouncer at an exclusive club:</p><ol><li>Your React app walks up: “Can I talk to script.google.com and read the response?”</li><li>The browser (the bouncer) thinks: “Hmm, different origin. Let me ask the server first.”</li><li>The browser sends an OPTIONS preflight request: “Hey Google, is it cool if mywebsite.com talks to you using POST?”</li><li>Google responds with CORS headers</li><li>The bouncer reads this and says: “Cool, the Google server said it’s allowed. Go ahead and send your POST request.”</li><li>My POST request from mywebsite.com goes through, and this time the browser lets you read the response.</li></ol><p>Without these headers? The server response gets blocked by the browser, and your React code never receives it.</p><p>Let me help you visualize this process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EjILlfRylledVoG2.png" /></figure><p>CORS doesn’t actually stop a request from <em>reaching</em> the Apps Script. It stops the <strong>browser</strong> from letting your website see the result. Without proper CORS headers, the data might actually reach your Google Sheet, but the browser will tell your React app “Failed to Fetch” because it doesn’t have permission to share the response with you.</p><p>In a real-world application, <strong>CORS</strong> acts as a security gateway that enables modern web integration. For instance, if you build a travel site that needs to get live flight data from an external airline API or process a payment via Stripe, the browser uses <strong>CORS</strong> to ensure those external servers explicitly trust your website before sharing sensitive data. This prevents a malicious site from “pretending” to be you to steal information, balancing the need for apps to talk to each other with the necessity of keeping user data safe.</p><blockquote>It’s easy to get tripped up by the name. In plain English, “fetch” usually means “to go get something” (like a <strong>GET</strong> request). However, in JavaScript, fetch() is the name of the entire API used to send <em>any</em> network request, including <strong>POST</strong>.</blockquote><blockquote>When you see <strong>“Failed to fetch,”</strong> the browser isn’t saying it failed to “get” a file; it’s saying the entire communication attempt was blocked or terminated — often by the CORS “bouncer” before the data even left your computer.</blockquote><h3>Apps Script: The CORS Magic</h3><p>Here’s the secret sauce in my Apps Script:</p><pre>const SPREADSHEET_ID = &#39;1M7gNsYtqoVm5MS4O13iSBqpsd1dOcodcOst5Fku6Db8&#39;;<br>const TAB_NAME = &#39;Sheet1&#39;;<br><br>function doPost(e) {<br>  try {<br>    const ss = SpreadsheetApp.openById(SPREADSHEET_ID);<br>    const sheet = ss.getSheetByName(TAB_NAME);<br>    if (!sheet) throw new Error(`Tab &#39;${TAB_NAME}&#39; not found`);<br><br>    // Parse the incoming JSON data<br>    const data = JSON.parse(e.postData.contents);<br><br>    // Append a new row with all the registration data<br>    sheet.appendRow([<br>      new Date(),<br>      data.name || &#39;&#39;,<br>      data.email || &#39;&#39;,<br>      data.school || &#39;&#39;,<br>      data.grade || &#39;&#39;,<br>      data.soloOrTeam || &#39;&#39;,<br>      data.teamSize || &#39;&#39;,<br>      data.teammate1Name || &#39;&#39;,<br>      data.teammate1Grade || &#39;&#39;,<br>      data.teammate2Name || &#39;&#39;,<br>      data.teammate2Grade || &#39;&#39;,<br>      data.teammate3Name || &#39;&#39;,<br>      data.teammate3Grade || &#39;&#39;<br>    ]);<br><br>    // Return success response with CORS headers<br>    return corsResponse_({ status: &#39;ok&#39;, message: &#39;Registration saved&#39; });<br><br>  } catch (err) {<br>    console.error(&#39;Error in doPost:&#39;, err);<br>    return corsResponse_({ status: &#39;error&#39;, message: String(err) });<br>  }<br>}<br><br>// Handle preflight requests<br>function doOptions() {<br>  return corsResponse_({ status: &#39;ok&#39; });<br>}<br><br>// The CORS magic function<br>function corsResponse_(obj) {<br>  return ContentService<br>    .createTextOutput(JSON.stringify(obj))<br>    .setMimeType(ContentService.MimeType.JSON)<br>    .setHeader(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)           // Allow any origin<br>    .setHeader(&#39;Access-Control-Allow-Methods&#39;, &#39;POST, OPTIONS&#39;) // Allow POST and OPTIONS<br>    .setHeader(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type&#39;); // Allow Content-Type header<br>}</pre><p>Key points:</p><ul><li>doPost(e): Handles the actual form submission</li><li>corsResponse_(): Wraps any response with CORS headers so the browser lets React read it</li><li>doOptions(): a specific function required by Google Apps Script to catch the browser’s “preflight” security check</li><li>Access-Control-Allow-Origin: &#39;*&#39;: Allows requests from ANY domain (you could restrict this to just your domain for extra security)</li></ul><h3>The Registration Form in React</h3><p>Here’s the form handler that works:</p><pre>import React, { useState } from &#39;react&#39;;<br>import { useToast } from &#39;@/components/ui/use-toast&#39;;<br><br>const Registration = () =&gt; {<br>  const { toast } = useToast();<br>  const [isSubmitting, setIsSubmitting] = useState(false);<br>  const [formData, setFormData] = useState({<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>    school: &#39;&#39;,<br>    grade: &#39;&#39;,<br>    participationType: &#39;solo&#39;,<br>    numberOfTeammates: 0,<br>    teammates: [],<br>  });<br><br>  const handleChange = (e) =&gt; {<br>    const { name, value } = e.target;<br>    setFormData(prev =&gt; ({<br>      ...prev,<br>      [name]: value,<br>    }));<br>  };<br><br>  const validateForm = () =&gt; {<br>    if (!formData.name.trim()) return false;<br>    if (!formData.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) return false;<br>    if (!formData.school.trim()) return false;<br>    if (!formData.grade) return false;<br>    if (!formData.participationType) return false;<br>    <br>    if (formData.participationType === &#39;team&#39;) {<br>      if (formData.numberOfTeammates &gt; 0) {<br>        for (let i = 0; i &lt; formData.numberOfTeammates; i++) {<br>          const tm = formData.teammates[i];<br>          if (!tm || !tm.name.trim() || !tm.grade) return false;<br>        }<br>      }<br>    }<br>    return true;<br>  };<br><br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br><br>    if (!validateForm()) {<br>      toast({<br>        title: &quot;Validation Error&quot;,<br>        description: &quot;Please fill in all required fields correctly.&quot;,<br>        variant: &quot;destructive&quot;<br>      });<br>      return;<br>    }<br><br>    setIsSubmitting(true);<br><br>    const payload = {<br>      name: formData.name,<br>      email: formData.email,<br>      school: formData.school,<br>      grade: formData.grade,<br>      soloOrTeam: formData.participationType,<br>      teamSize: formData.numberOfTeammates,<br>      teammate1Name: formData.teammates[0]?.name || &#39;&#39;,<br>      teammate1Grade: formData.teammates[0]?.grade || &#39;&#39;,<br>      teammate2Name: formData.teammates[1]?.name || &#39;&#39;,<br>      teammate2Grade: formData.teammates[1]?.grade || &#39;&#39;,<br>      teammate3Name: formData.teammates[2]?.name || &#39;&#39;,<br>      teammate3Grade: formData.teammates[2]?.grade || &#39;&#39;,<br>    };<br><br>    try {<br>      const response = await fetch(<br>        &#39;https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID_HERE/exec&#39;,<br>        {<br>          method: &#39;POST&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json;charset=utf-8&#39;,<br>          },<br>          body: JSON.stringify(payload),<br>          // No mode: &#39;no-cors&#39; needed when CORS headers are proper<br>        }<br>      );<br><br>      if (!response.ok) {<br>        throw new Error(`HTTP error! status: ${response.status}`);<br>      }<br><br>      const result = await response.json();<br><br>      if (result.status === &#39;ok&#39;) {<br>        toast({<br>          title: &quot;Registration Received! 🎉&quot;,<br>          description: &quot;We will send you email updates soon!&quot;,<br>          className: &quot;bg-green-600 text-white border-none&quot;<br>        });<br><br>        // Reset form<br>        setFormData({<br>          name: &#39;&#39;,<br>          email: &#39;&#39;,<br>          school: &#39;&#39;,<br>          grade: &#39;&#39;,<br>          participationType: &#39;solo&#39;,<br>          numberOfTeammates: 0,<br>          teammates: [],<br>        });<br>      } else {<br>        throw new Error(result.message || &#39;Server error&#39;);<br>      }<br><br>    } catch (error) {<br>      console.error(&#39;Submission Error:&#39;, error);<br>      toast({<br>        title: &quot;Registration Failed&quot;,<br>        description: error?.message || &quot;There was a problem submitting your registration.&quot;,<br>        variant: &quot;destructive&quot;<br>      });<br>    } finally {<br>      setIsSubmitting(false);<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      {/* Form JSX here */}<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default Registration;</pre><h3>No-CORS vs. Proper CORS: The Comparison</h3><h4>The mode: &#39;no-cors&#39; Approach</h4><pre>const response = await fetch(url, {<br>  method: &#39;POST&#39;,<br>  mode: &#39;no-cors&#39;, // Tell browser to ignore CORS errors<br>  body: JSON.stringify(data),<br>});<br><br>// Problem: The response is always opaque<br>// You can&#39;t read response.json() or check response.ok<br>// You just pray the request reached the server<br>toast({ title: &quot;Success&quot; }); // 🎲 Maybe it worked, maybe it didn&#39;t</pre><p>Pros:</p><ul><li>Requests still reach the server (usually)</li><li>No preflight overhead (sort of)</li></ul><p>Cons:</p><ul><li>You can’t see if it actually worked</li><li>Users get false success messages</li><li>Error handling is impossible</li><li>Data might be lost and you’d never know</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5paxxfJJDciaMw0Q.png" /></figure><h3>The Deployment Issue</h3><p>Through some debugging and fixing up the no-cors issue my Google Sheets were still not populatin. I discovered something strange: I had 9 versions of my Apps Script, but only one deployment was active. Every time I edited the code and saved, it created a new version. But the deployment wasn’t automatically updating to point to that new version. It was stuck pointing to old code — or worse, sometimes it wasn’t routing to any code at all.</p><p>This was the real culprit.</p><p>I had been updating my React code with the same deployment URL over and over, thinking I was getting the latest version. But the deployment itself was pointing at outdated or misconfigured Apps Script code that didn’t have proper CORS handling.</p><p>The fix was to archive the old versions and create a fresh deployment.</p><h3>Deployment Matters</h3><p>Here’s what I learned:</p><p>The biggest issue wasn’t my code. It was my deployment.</p><p>I had been editing my Apps Script dozens of times, creating Version 1, 2, 3… all the way to Version 9. But only one deployment was active at any time, and it wasn’t automatically syncing with my latest edits.</p><p>The solution was surprisingly simple:</p><ol><li>Archive the old versions</li><li>Create a fresh deployment with the latest code</li><li>Copy the new deployment URL</li><li>Update React with that URL</li></ol><p>Suddenly, everything worked.</p><h3>How You Can Use This in Your Own Project</h3><p>If you want to build a registration system that feeds directly into Google Sheets, here’s what to do:</p><h4>Step 1: Create Your Google Sheet</h4><p>Create a sheet with column headers matching your data:</p><pre>Timestamp | Name | Email | School | Grade | SoloOrTeam | TeamSize | ...</pre><h4>Step 2: Set Up Apps Script</h4><ol><li>Open your Google Sheet</li><li>Go to Extensions → Apps Script</li><li>Paste the doPost(), doOptions(), and corsResponse_() functions (shown above)</li><li>Update SPREADSHEET_ID with your actual sheet ID</li><li>Update TAB_NAME to match your sheet&#39;s tab name</li></ol><h4>Step 3: Deploy as Web App</h4><ol><li>Click Deploy → New deployment</li><li>Select Web app</li><li>Set Execute as: Your account</li><li>Set Who has access: Anyone</li><li>Click Deploy</li><li>Copy the deployment URL</li></ol><h4>Step 4: Build Your React Form</h4><p>Use the React code above, but replace:</p><pre>&#39;https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID_HERE/exec&#39;</pre><p>With your actual deployment URL.</p><h4>Step 5: Test It!</h4><p>Fill out the form and watch the data appear in your Google Sheet in real-time.</p><h3>Conclusion: What I Wish I’d Known</h3><p>If I could go back and tell past me one thing, it would be:</p><blockquote>Always double-check that your deployment is pointing to your latest code.”</blockquote><p>Building this registration system taught me that sometimes the simplest fix — archiving old deployments and starting fresh — can save hours of debugging. And understanding CORS, while initially confusing, is essential knowledge for anyone building web applications that talk to external APIs or services.</p><p>The next time someone tells you they’re getting “Failed to fetch” errors (meaning the browser blocked the interaction because the Apps Script server didn’t provide the required CORS headers to authorize the conversation), you can confidently walk them through the CORS handshake and help them see what’s really happening under the hood.</p><p>Keep coding guys 💻 — I will see you in the next blog 🫡.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10bf82b73a99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Perplexity Solved My 2 Min Problem That ChatGPT Couldn’t in 2 hours]]></title>
            <link>https://medium.com/@genzarjun/perplexity-solved-my-2-min-problem-that-chatgpt-couldnt-in-2-hours-06fa41c643a5?source=rss-10e512a8e591------2</link>
            <guid isPermaLink="false">https://medium.com/p/06fa41c643a5</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[perplexity]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Arjun M]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 01:37:55 GMT</pubDate>
            <atom:updated>2025-12-25T01:37:55.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*5s49uRz6DdCgDBYK.jpg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.analyticsvidhya.com%2Fblog%2F2024%2F03%2Fthe-comparison-perplexity-ai-vs-chatgpt%2F&amp;psig=AOvVaw3ryQwBBeIiOv6F00-Nla2f&amp;ust=1766706967019000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBYQjRxqFwoTCOC2lLu215EDFQAAAAAdAAAAABAV">Image Credit</a></figcaption></figure><p>Perplexity is really starting to perplex me.</p><p>We are out of the era of search and into the era of answers. However, sometimes you simply can’t rely on ChatGPT and other AI Chatbots to get the truthful answer you need, but — you can rely on Perplexity.</p><blockquote>Perplexity is all about looking at real sources to tell you the truth.</blockquote><p>Whether its reading documentation, looking at Youtube Videos, or other general bugs people are facing with a specific tool or tech stack, I recently learned that Perplexity is actually a great tool for Vibe Coding. You just got to know when to use it.</p><p>You see it just yesterday I was practicing some vibe coding and was trying to run some software for an old robot I had previously made with Android Studio, and was facing some Gradle issues. I took a typical developer approach, showing the error to ChatGPT and asking it what going on. It turned out a lot of things were messed up.</p><p><strong>There essentially was a Gradle sync error</strong> caused by moving the my library’s dependency, MeepMeep, from an old version to the newer version, which required <strong>Java 17</strong> and modern <strong>centralized repository management</strong>.</p><p>Perplexity guided me in fixing up my project by guiding me through the following steps:</p><ol><li><strong>Updating Java:</strong> I first updated the project to use <strong>Java 17</strong> instead of Java 8 to meet the library’s requirements.</li><li><strong>Centralizing Repositories:</strong> All repository declarations (like <a href="https://jitpack.io/">JitPack</a> and Maven Brott) were moved from individual build.gradle files into the settings.gradle file under dependencyResolutionManagement.</li><li><strong>Fixing Plugin Resolution:</strong> A pluginManagement block was added to settings.gradle, and a specific repositories block was kept inside the buildscript section of the root build.gradle to ensure the <a href="https://developer.android.com/studio/releases/gradle-plugin">Android Gradle Plugin</a> could still be found.</li></ol><p>Let me now explain what ChatGPT’s take to this same situation was. I went to ChatGPT with the problem first and after a few exchanges and following what ChatGPT told me to, it took about 2 hours, I knew something was majorly wrong and I immediately switched to Perplexity.</p><p>ChatGPT properly identified that there was a <strong>Gradle build failure</strong> (from the error that I gave to it) caused by a version incompatibility. It noticed the project was attempting to use Gradle features or plugins that were no longer supported in the environment’s version, resulting in a “Cannot use @TaskAction annotation&quot; error (from my error that I showed it). Additionally, it identified the build could not resolve the <strong>MeepMeep</strong> dependency.</p><p>Notice a difference in the way both the chatbots expressed the problem? Perplexity was able to give me a better understanding of the problem, and was ready to lead into steps on how to solve the problem. Compared to ChatGPT, it was simply identifying the problem, not leading into anything bigger and asking for more information from my side. It was recommending me to run Git commands to revert the project to a previous state, and offering diagnostics to to get more detailed logs on the situation, and was wondering which specific scripts were failing. However, Perplexity took the project to the next level, not only solving the problem but restructuring the files to create a more robust project.</p><blockquote>Temporary vs. sustainable solution?</blockquote><p>In my Perplexity conversation, below is a screenshot of part of its response that it got its sources from. Notice how all of the sources are from documentation, official Android developer pages, and previous issues people faced in Stack Overflow.</p><figure><img alt="Sources from a Perplexity Response" src="https://cdn-images-1.medium.com/max/1024/1*gmKN62NGYWbdtbqFaf_eKg.png" /></figure><h4>My Ultimate Advice on When to Use Perplexity</h4><p>There are millions of coders out there. High likely, that one of them may have faced the exact issue of problem that you may be facing and struggled in solving it. Perplexity helps bridge the gap between your problem and their solution.</p><ol><li><strong><em>Use it for fixing bugs — </em></strong>Context engineer your prompts into Perplexity with its Deep Research feature and describe your problem in detail with screenshots and important code files in your project.</li><li><strong><em>Advice — </em></strong>Before starting a project, when you want to consider what Tech Stack and tools to use Perplexity is a great place to go to. Many people ask for advice in Stack Overflow and other Tech Forums on what tools, languages, frameworks, and tech stack they should use for project ideas and features they plan to implement in their project.</li><li><strong><em>Feed its info into other Vibe Coding Tools — </em></strong>Before exploring a new framework that you want to learn about, rather than dumping your project idea into Cursor, consider asking Perplexity what are tips to implement that framework in a robust manner as well as things to keep in mind. Then have Perplexity create a .md file with instructions on important considerations for using the framework and steps on how to implement it which you can then feed into Cursor so you have a robust foundation of that framework in your project!</li></ol><p>Keep vibe coding guys 💻 — I will see you in the next blog 🫡.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06fa41c643a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizing Python to Gamify Math]]></title>
            <link>https://medium.com/@genzarjun/utilizing-python-to-gamify-math-60adb9833c09?source=rss-10e512a8e591------2</link>
            <guid isPermaLink="false">https://medium.com/p/60adb9833c09</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gamification]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Arjun M]]></dc:creator>
            <pubDate>Sun, 25 May 2025 02:13:53 GMT</pubDate>
            <atom:updated>2025-08-17T05:23:59.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Young male coding in a futuristic workspace" src="https://cdn-images-1.medium.com/max/1024/1*cfhz8OTla_IdLbNCDOPl9w.png" /></figure><blockquote>Math has a connotation of being boring</blockquote><p>When you think of applied mathematics in all aspects, it might overwhelm you. However, taking it to its most fundamental form for solving, you get the 4 operations.</p><blockquote>Adding — Subtracting — Multiplying — Dividing.</blockquote><p>I developed MathBot, a program <strong>with an intuitive and dark-themed GUI</strong>, made purely of Python. It utilizes gamification techniques, such as stopwatches, countdowns, competition against friends, and randomization to help users master those 4 operations! Let’s dive in:</p><h3>How It Works</h3><ol><li>Users are able to choose their desired operation they would like to compete in.</li><li>Choose a mode — Single Match, or Best of 3 Matches</li></ol><p>That’s it! Then each of 2 players click “start” when they are ready. They are presented with two randomized numbers, will perform the chosen operation on those two numbers, and then type their answer as fast as they can (with the stopwatch visible to them!).</p><p>Whichever player gets it correct wins. If both get it correct or both wrong, whoever inputted the answer faster wins the round. There is a rare situation of there being a tie as well!</p><p>I implemented some minor restrictions into the randomized numbers that get inputted. For example, if users are playing with the division operation, then the randomized numbers should divide to a whole number.</p><pre>test_num1 = random.randint(100,200)<br>test_num2 = random.randint(10,30)<br><br>while test_num2 == test_num1:<br>    test_num2=random.randint(10,100)<br><br>answer = test_num1/test_num2<br><br>while answer.is_integer() == False:<br>    test_num1 = random.randint(100,200)<br>    test_num2 = random.randint(10,100)<br>    answer = test_num1/test_num2<br><br>answer = test_num1/test_num2</pre><p>Additionally, for multiplication, I kept the range of random numbers from (2–20), as those are the most common factors, in simple multiplication problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MT-6ngFVNQXX835PSKwchw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqSw3cbIfw2FMYv4payx0Q.png" /><figcaption>Simple GUI, fun gameplay!</figcaption></figure><h3>Building MathBot</h3><p>I made use of the comprehensive GUI library of Tkinter, in Python in order to build this app. Tkinter’s numerous components and features, including themed widgets with pre-customized styles saved me time and kept my code organized.</p><p>Additionally, I made use of the System, Time, and Random libraries for specific parts of my program:</p><ul><li>System — Helped me manage errors with the stopwatch and countdowns</li><li>Time — Helped me implement the stopwatch and countdown features in the program</li><li>Random — Helped me generate the random numbers for each operation</li></ul><h3>Impact</h3><p>These 4 basic math operations that are foundational for success in countless fields, an essential in higher-level math courses, and math skills that <strong>anyone</strong> can continuously improve upon.</p><p>Competing against your best friend, family member, or peer, always is fun, providing a comforting way to bond, alongside improving math skills. With MathBot, the program’s impact extends beyond just improving math skills, but providing a platform for continuous improvement through competition, connection, and gamification.</p><h3>Future Scalability</h3><p>The intuitive gameplay of MathBot has the ability to be transformed into a full-fledged application accessible to users throughout the world.</p><p>Some specific gamification techniques that I plan on implementing to MathBot are:</p><ul><li>Online Competition — Once MathBot is deployed on the web or online app, I will be able to connect it to cloud servers so if a user doesn’t have a partner next to them to compete, they can compete with someone online from across the world!</li><li>Daily Streaks &amp; Personal Achievements — Similar to companies such as Duolingo, maintaining daily streaks, as well as personal achievements (e.g. best time for a each operation), helps keep users engaged and consistently improving their math skills. They should be able to share their achievements and streak with their peers. Additionally, providing statistical points (such as average time for a certain operation), and monitoring performance in the game over time, maintains user interest in the program</li><li>Adapting Learning — Whether a user gets a specific question wrong or write, and in how much time, should be recorded and used for future testing. Through my knowledge of AI/ML, I plan to implement more customized numbers vs. randomized numbers (for the users to play with), based on their skill level, accuracy, and speed.</li></ul><h3>Conclusion</h3><p>MathBot is a program that aims to improve your foundational math skills in the best way possible. Through gamified techniques. It’s fun and intuitive gameplay and potential for future scalability makes it an optimal solution for addressing the popular opinion (going back to the first line!) — math is boring.</p><p>Whether you are a student, educator, or professional, I hope you gained some value out of this project, and understand how far mastering basic math operations can take you.</p><p>Check out the full project in Github <a href="https://github.com/genzarjun/MathBot">here</a>.</p><p>Otherwise, keep coding math geeks 🤓 — and I will see you in the next blog 🫡.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60adb9833c09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizing ML For Predicting How Height Affects NBA Performance ]]></title>
            <link>https://medium.com/@genzarjun/utilizing-ml-for-predicting-how-height-affects-nba-performance-0ecba2b7aff7?source=rss-10e512a8e591------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ecba2b7aff7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Arjun M]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 01:01:45 GMT</pubDate>
            <atom:updated>2025-06-26T00:39:16.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A dark-themed computer with code" src="https://cdn-images-1.medium.com/max/1024/0*CmBLR7j67PG46F_v" /><figcaption>Photo by <a href="https://unsplash.com/@clark_fransa?utm_source=medium&amp;utm_medium=referral">Arnold Francisca</a></figcaption></figure><p>The NBA is <strong>electrifying</strong> — a league with countless fans across the country, featuring great stars right now, from Steph Curry to Luka Dončić, and of course holding pride with former G.O.A.T.s; Jordan, Kobe, Shaq, Kareem . . . dominating basketball as a whole, and arguably changing the league’s presence in the entire world.</p><p><em>How come they are some of the best?</em></p><p>Might seem like a trick question right.</p><blockquote>They worked extremely hard</blockquote><blockquote>They had a parent who was in the NBA</blockquote><p>OR what about</p><p><em>Their build?</em></p><blockquote><strong><em>Height plays a huge role in NBA</em></strong></blockquote><p><strong>~99.8%</strong> of players are<strong> 6ft or above (</strong>I could never be 6ft 😅), with the average height being at <strong>6&#39;6&quot;</strong></p><p>With my passion for basketball, love for the league, and my developing coding skills, I coded a <strong>Python Machine Learning Program</strong> to embark on answering the question:</p><blockquote>How does height influence NBA players’ stats?</blockquote><h3><strong>📊</strong> Data</h3><p>The highly helpful <a href="https://github.com/swar/nba_api"><strong>NBA API Package</strong></a>, was utilized in this project. It is an API client for NBA stats, making it quite easy to pull data straight from the NBA&#39;s official stats site. The data I used was categorized into three sections:</p><ol><li><strong>NBA Players —</strong> I imported all the NBA players (former and active). Each NBA player has a unique player ID #, I took all of the player ID #s of the active players in the NBA.</li><li><strong>Player Info — </strong>Using the player ID #s of the active players, I imported player info of each of those players, such as height, college, etc.</li><li><strong>Player Stats</strong> — Using the player ID #s of the active players, I imported player career stats — regular season, average per game — of each of those players, such as PTS, AST, etc.</li></ol><h3>💻 Program</h3><blockquote>What will our program do?</blockquote><p>The user will choose a certain NBA stat —for example — Assists, and the program will graph the relationship between heights of active NBA players, and their assists (or whatever chosen stat), per game, in the regular season. From there, the program will use machine learning to apply weights to each of the heights, depending on how many values are there for each height, and then predict the optimal height for making the most assists (or whatever chosen stat).</p><figure><img alt="ML program using LOWESS function to predict how height affects assists in the NBA" src="https://cdn-images-1.medium.com/max/1024/1*rRW36i69rRRE5zMM4IlFmA.png" /><figcaption>Output of the program, with Assists as the chosen stat</figcaption></figure><h3>🔍 <strong>Code</strong></h3><p>Let’s dive into the source code of this program.</p><ol><li><strong>Installations</strong></li></ol><p>The <a href="https://github.com/swar/nba_api"><strong>NBA API Package</strong></a><strong> </strong>will need to be installed in this project to get the data, since it isn’t a standard library. Same for Pandas, Matplotlib, Numpy, and StatsModels.</p><p>Typically, in most code editors, these libraries can be installed in your code editor’s terminal using:</p><pre>pip install nba_api<br>pip install pandas<br>pip install numpy<br>pip install matplotlib<br>pip install statsmodels</pre><p>2. <strong>Imports</strong></p><p>Now we will start writing the program.</p><p>We can import the 3 specific parts of the data we need from the NBA_API Package. We will also import our installed libraries, a few standard libraries, and specifically the LOWESS function from the StatsModels library, which will be explained later.</p><pre>from nba_api.stats.static import players #importing players<br>from nba_api.stats.endpoints import commonplayerinfo #importing player info<br>from nba_api.stats.endpoints import playercareerstats #importing player stats<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import time<br>import random<br>import math<br>from statsmodels.nonparametric.smoothers_lowess import lowess</pre><p>3. <strong>Headers</strong></p><p>When using the NBA_API package to make requests for data, nba.com may end up throwing some errors. To work around these errors, we need to use custom headers to make the process of retrieving the data run smoothly.</p><pre>headers  = {<br>    &#39;Connection&#39;: &#39;keep-alive&#39;,<br>    &#39;Accept&#39;: &#39;application/json, text/plain, */*&#39;,<br>    &#39;x-nba-stats-token&#39;: &#39;true&#39;,<br>    &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36&#39;,<br>    &#39;x-nba-stats-origin&#39;: &#39;stats&#39;,<br>    &#39;Sec-Fetch-Site&#39;: &#39;same-origin&#39;,<br>    &#39;Sec-Fetch-Mode&#39;: &#39;cors&#39;,<br>    &#39;Referer&#39;: &#39;https://stats.nba.com/&#39;,<br>    &#39;Accept-Encoding&#39;: &#39;gzip, deflate, br&#39;,<br>    &#39;Accept-Language&#39;: &#39;en-US,en;q=0.9&#39;,<br>}</pre><blockquote><em>Now the fun part! 🔥</em></blockquote><p>4. <strong>Getting the Data (Part 1)</strong></p><p>Looking at the code below, we are getting info of all the current NBA players. The data will come in the form of a list (with a dictionary for each player inside of it). We will convert this list into a Pandas DataFrame to make it easy to work with. From there we will filter out their player ID #s, and then convert those ID #s into a list.</p><pre>nba_players = players.get_active_players()<br>df = pd.DataFrame(nba_players) #converting all the active player info into a dataframe<br>active_players_ids = df.loc[:, &#39;id&#39;].to_list()</pre><p>5. <strong>Creating Request Functions</strong></p><p>We are now going to two functions to get the other two pieces of our data:</p><p><strong>Player Info</strong> → Gives me the heights of the players<br><strong>Player Stats</strong> → Gives me the stats of the players</p><pre>def get_player_info(nba_player_id):<br>  player_info = commonplayerinfo.CommonPlayerInfo(player_id=nba_player_id, headers=headers,timeout=100)<br>  df = player_info.common_player_info.get_data_frame()<br>  return df<br>def get_player_game_stats(nba_player_id):<br>  player_stats = playercareerstats.PlayerCareerStats(player_id=nba_player_id, per_mode36=&#39;PerGame&#39;)<br>  df = player_stats.get_data_frames()[0] #the index [0] signifies the stats are going to be from regular season<br>  return df</pre><p>6. <strong>Getting the Data (Part 2)</strong></p><p>Time to put the first function (<strong>get_player_info</strong>) we made, to use!</p><p>We are going to get the player info for each active NBA player, using the list of player IDs we made in Step 4, by calling the function each time it iterates through the list. The function will return a <strong>Pandas</strong> <strong>DataFrame</strong> with each player’s info and it will add each of these DataFrames into a list, then convert that list of DataFrame into one large data-frame (so it is easier to manipulate). This process can take about 10–11 minutes (there so much data!).</p><pre>list_of_player_info = []<br><br>for nba_player_id in active_players_ids:<br>  player_info = get_player_info(nba_player_id)<br>  list_of_player_info.append(player_info) #adding the data frame to the list, list_of_player_info<br>  time.sleep(1.0) #we are adding a mini-sleep here so it doesn&#39;t overwhelm nba.com with so many calls and throw an error<br><br>final_df_player_info = pd.concat(list_of_player_info, ignore_index = True)</pre><p>7. <strong>Filtering</strong></p><p>We have a whole lot of info for each player. This info can be utilized to decide which players <strong>can cause errors in the program.</strong></p><ul><li>Un-drafted players lack certain statistics, which can cause errors later in the program, so we remove any un-drafted players.</li></ul><p>We will now re-define the list, active_player_ids, to have the players in the DataFrame right now, without un-drafted players. Finally, we are going to get just the heights from the DataFrame, and leave out the rest of the info.</p><pre>final_df_player_info_cleaned = final_df_player_info.loc[(final_df_player_info[&#39;DRAFT_YEAR&#39;] != &#39;Undrafted&#39;), :]<br>reseted_player_info = final_df_player_info_cleaned.reset_index(drop=True)<br>active_players_ids = reseted_player_info[&#39;PERSON_ID&#39;] #taking the player ids from the dataframe, and setting them to the active_player_ids, so that it is easy to get the right game stats now, with removed duplicated and undrafted players!<br>heights_df = reseted_player_info.loc[:,&quot;HEIGHT&quot;] #getting the heights</pre><p>8.<strong> Getting the Data (Part 3)</strong></p><p>Now using the second function we made! We are using the same process for getting the stats as we did for getting the info.</p><pre>#getting the player STATS<br>list_of_player_game_stats = []<br>for nba_player_id in active_players_ids:<br>  player_game_stats = get_player_game_stats(nba_player_id)<br>  list_of_player_game_stats.append(player_game_stats)<br>  time.sleep(1.0) #we are adding a mini-sleep here so it doesn&#39;t overwhelm nba.com with so many calls and throw an error<br>#organizing the PLAYER STATS list into a full pandas dataframe<br>uncleaned_final_df_player_game_stats = pd.concat(list_of_player_game_stats, ignore_index = True)</pre><p>9. <strong>Filtering . . . Again!</strong></p><p>Woah! We have a lot of stats! We need to filter some of this data.</p><ul><li>We receive stats for all the seasons a player was in the NBA. To keep the program current, we will keep only the stats for <strong>the current season.</strong></li><li>If a player played for multiple teams in the same season, then they will have multiple rows of stats. We will keep only one of these rows to minimize confusion when comparing the heights to the stats.</li><li>In a rare occasion, if some player has been out the entire season (for an injury or some sort), then they are removed from the DataFrame.</li></ul><p>Finally, we will remove stats that don’t accurately relate to heights and apply to our program (such as minutes per game).</p><pre>final_df_player_game_stats = uncleaned_final_df_player_game_stats.loc[((uncleaned_final_df_player_game_stats[&#39;SEASON_ID&#39;]) ==&#39;2024-25&#39;),:] #change the season to whatever is the current season<br>no_duplicates = final_df_player_game_stats.drop_duplicates(&#39;PLAYER_ID&#39;, keep=&#39;last&#39;)<br>game_stats_reseted_index = no_duplicates.reset_index(drop=True) #we are resetting the indices, so they can accurately match the heights<br><br>#this chunk checks if a player hasn&#39;t had a 24-25 season (for an injury or some sort), then they are removed from the heights dataframe<br>not_having_24_25_season = []<br>temporary_index = 0<br>increment = 0<br>for x in active_players_ids:<br>  try:<br>    if x == ((list(game_stats_reseted_index[&#39;PLAYER_ID&#39;]))[temporary_index]):<br>      temporary_index += 1<br>    elif (x != (list(game_stats_reseted_index[&#39;PLAYER_ID&#39;]))[temporary_index]):<br>      not_having_24_25_season.append((temporary_index)+(increment))<br>      increment += 1<br>  except IndexError:<br>    not_having_24_25_season.append(temporary_index)<br>    temporary_index += 1<br>if len(not_having_24_25_season) &gt; 0:<br>  heights_df.drop(heights_df.index[not_having_24_25_season], axis=0, inplace=True) #axis=0 says we are dropping rows<br>  reseted_heights_df = heights_df.reset_index(drop=True) #Drop=False says that the index data is added to a new column&#39;&#39;&#39;<br>condensed_final_df_player_game_stats=game_stats_reseted_index.loc[:, &#39;GP&#39;:&#39;PTS&#39;]<br>condensed_final_df_player_game_stats.drop([&#39;GP&#39;,&#39;MIN&#39;,&#39;GS&#39;, &#39;FGA&#39;, &#39;FG_PCT&#39;, &#39;FG3A&#39;, &#39;FG3_PCT&#39;, &#39;FTM&#39;, &#39;FTA&#39;, &#39;FT_PCT&#39;],axis=1,inplace=True) #taking out non-worthy stats</pre><p>10. <strong>Combining Heights and Stats</strong></p><p>Alright!! Let’s combine the Heights DataFrame and Stats DataFrame!</p><pre>#combining the TWO dataframes<br>full_pd_cleaned = pd.concat([reseted_heights_df, condensed_final_df_player_game_stats], axis=1) #axis=1 combines the columns side-by-side, compared to axis=0 combining the columns vertically</pre><h3>👀 Visualize</h3><p>We have our necessary Data! All about visualizing and interacting with the program now! We can start off by welcoming the user to the program, and asking for them to choose a statistic.</p><pre>print(&quot;Welcome to this NBA Height-Performance Analyzer!&quot;)<br>stats = [&#39;FGM&#39;, &#39;FG3M&#39;, &#39;OREB&#39;, &#39;DREB&#39;, &#39;REB&#39;, &#39;AST&#39;, &#39;STL&#39;, &#39;BLK&#39;, &#39;TOV&#39;, &#39;PF&#39;, &#39;PTS&#39;]<br>stat = 0<br>def ask():<br>  global stat<br>  stat = input(&quot;\n\nChoose a stat that you would like to see the optimal height for and enter\nthe stat name exactly, each stat account for all the active players&#39; stats per game in the regular season:\nFGM, FG3M, OREB, DREB, REB, AST, STL, BLK, TOV, PF, PTS\n\nFor example, enter, &#39;AST&#39;, (without quotes)  &quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0jtGb4LMJE1OdGzd2-nLQ.png" /></figure><p>After that, we can create a function, testing if the user’s input was actually one of the given stats, or if they made a typo error. If they did, the function can detect it. If they the input is valid, then the function moves on to:</p><ol><li><strong>Converting the Heights into Feet<br></strong>We received the heights in the form of “feet-inch”, for example “6–6”. We will need to convert each of the heights into pure feet (6–6 would become 6.5), in order for the LOWESS function to work.</li><li><strong>Ordering Heights<br></strong>We will order the heights from shortest to tallest so it looks neat in our graph.</li><li><strong>ML 🔥<br></strong>We<strong> </strong>are now using the LOWESS function to identify how our heights are changing the stats. It will weight each height differently depending on how many stat numbers are there for each height and its neighboring heights, and provide a smoothing of the stats progressing through the heights. It will then, identify the highest point on the curve, and the height that matches that point, will be the optimal height for the chosen statistic.</li><li><strong>Graphing</strong><br>Last but not least — we will graph all of it using MatPlotLib! The heights will still remain in their labeled “feet-inch” form.</li></ol><figure><img alt="LOWESS Curve" src="https://cdn-images-1.medium.com/max/1024/1*UfPRKlXV8e8URT5A7JSsXA.png" /></figure><pre>def loop():<br><br>  if stat in stats:<br>    def convert_height_to_feet(height_str):<br>        feet, inches = height_str.split(&#39;-&#39;)<br>        return (int(feet) + (int(inches) / 12))<br>    # Add a new hidden column (NEW_HEIGHTS_FOR_SORTING) for sorting<br>    full_pd_cleaned[&#39;NEW_HEIGHTS_FOR_SORTING&#39;] = full_pd_cleaned[&#39;HEIGHT&#39;].apply(convert_height_to_feet)<br>    # Sort by actual height (feet), using the new column for heights that we just made<br>    df_sorted = full_pd_cleaned.sort_values(by=&#39;NEW_HEIGHTS_FOR_SORTING&#39;)<br>    smoothed = lowess(df_sorted[stat], df_sorted[&#39;NEW_HEIGHTS_FOR_SORTING&#39;], frac=0.2)<br>    max_idx = np.argmax(smoothed[:, 1]) #returns the index of the highest value in the second column (the y-values) of the 2D Numpy Array that smoothed returns<br>    best_height = smoothed[max_idx, 0]<br>    best_height_formatted_without_decimal = f&quot;{int(best_height)}-{round((((best_height) - (math.floor(best_height)))*12))}&quot;<br>    best_stat = smoothed[max_idx, 1]<br>    plt.figure(figsize=(10, 6))<br>    plt.scatter(df_sorted[&#39;NEW_HEIGHTS_FOR_SORTING&#39;], df_sorted[stat], label=f&#39;Average {stat}&#39;, color=&#39;black&#39;)<br>    plt.plot(smoothed[:, 0], smoothed[:, 1], color=&#39;blue&#39;, linewidth=2, label=&#39;LOWESS Curve&#39;) #smoothed returns a 2D Numpy array in the format [x_value, smoothed_y_value] for each row<br><br> # Annotate the peak<br>    plt.scatter(best_height, best_stat, color=&#39;red&#39;, zorder=5, label=f&#39;Peak: {best_stat:.2f} {stat} @ {best_height_formatted_without_decimal} ft&#39;)<br>    plt.text(<br>        best_height, best_stat + 0.3,<br>        f&#39;{best_stat:.2f} {stat}\nat {best_height_formatted_without_decimal}&#39;,<br>        ha=&#39;center&#39;, color=&#39;red&#39;<br>    )<br>    plt.xlabel(&#39;Height (feet)&#39;)<br>    plt.ylabel(f&#39;{stat} per Game&#39;)<br>    plt.title(f&#39;Height vs {stat} per Game&#39;)<br>    plt.xticks(df_sorted[&#39;NEW_HEIGHTS_FOR_SORTING&#39;], df_sorted[&#39;HEIGHT&#39;], rotation=25)<br>    plt.legend()<br>    plt.grid(True)<br>    plt.show()<br>    print(f&quot;\n\nTHE OPTIMAL HEIGHT FOR {stat} IS {best_height_formatted_without_decimal}&quot;)<br>  elif stat not in stats:<br>    print(&quot;\n\nYou entered an invalid input:&quot;)<br>    print(stat)<br>    ask()<br>    loop()<br>ask()<br>loop()</pre><h3>Conclusion &amp; Results</h3><p>Wow! You made it to the end —here are the results from the program on the optimal height of each stat (based on average data per game):</p><blockquote>Making the most field goals (FGM) — 7&#39;4&quot;<br>Making the most 3-pt field goals (FG3M) — 6&#39;5&quot;<br>Getting the most offensive rebounds (OREB) — 7&#39;4&quot;<br>Getting the most defensive rebounds (DREB) — 7&#39;4&quot;<br>Getting the most rebounds (REB) — 7&#39;4&quot;<br>Making the most assists (AST) — 6&#39;0&quot;<br>Making the most steals (STL) — 6&#39;0&quot;<br>Making the most blocks (BLK) — 7&#39;4&quot;<br>Making the most turnovers (TOV) — 6&#39;3&quot;<br>Making the most personal fouls (PF) — 7&#39;4&quot;<br>Making the most points (PTS) — 7&#39;4&quot;</blockquote><p>This program really helped provide me some clarity on the ways that heights in our current NBA affect the performance we see in the players, and I hope it provided you some clarity to you too as well!</p><p>Check out the GitHub link for this project <a href="https://github.com/genzarjun/nba_ML">here</a>.</p><p>Otherwise, keep coding basketball fans 🏀 — and I will see you in the next blog 🫡.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ecba2b7aff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>