<?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 Richard Chung on Medium]]></title>
        <description><![CDATA[Stories by Richard Chung on Medium]]></description>
        <link>https://medium.com/@richardchung?source=rss-321ba8f10b5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PcMSGp8TR8y9QVvIQBSJfg.jpeg</url>
            <title>Stories by Richard Chung on Medium</title>
            <link>https://medium.com/@richardchung?source=rss-321ba8f10b5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:07:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@richardchung/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[My Neo-Retro Solution to Streaming Music]]></title>
            <link>https://medium.com/swlh/my-neo-retro-solution-to-hoarding-physical-media-0a4a46c7fb5a?source=rss-321ba8f10b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a4a46c7fb5a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Richard Chung]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 07:21:53 GMT</pubDate>
            <atom:updated>2026-07-24T17:55:26.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LIdVOtjOIIdaJ6-gA3nHw.jpeg" /></figure><p>Using NFC cards, I built a portable solution that allows my phone to connect to a personal home server to stream music. Each stylized card redirects to an album that opens in a customized music player on my phone. For me, this is the perfect definition of “Neo-Retro” tech: a marriage concept between an era where we used to carry around our music but with modern convenience and integration. In this article, I want to articulate not only how this project was designed, but also how it has changed my perspective and listening habits.</p><p><em>Disclaimer: the music in my library is stored on a privately secured home server, and has been legally obtained through online digital purchases and CDs. The project files shared in this article are meant as an educational overview of the architecture and approach.</em></p><h3>Background</h3><p>I’ve been a Spotify Premium member for almost a decade now, and like many others I have felt trapped in an ecosystem that can whimsically raise subscription prices or terminate its service. I didn’t grow up with a sense of music ownership instilled into me, so as an adult I didn’t have a strong connection to existing forms of musical media and only saw them for their surface level strengths and weaknesses.</p><p>CDs are high fidelity and lossless. I recognize that they’re the greatest for home listening but they’re a handful to lug around even with portable players and anti-skip protection.</p><p>Cassettes have a huge culture behind them from media representation capitalizing on nostalgia, but they have always felt like more of an impractical statement piece to me. The audio quality through the player and inability to skip tracks leaves me wanting more, but die-hard purists will say it’s part of the experience. Still, I will concede that the form factor of a cassette and cassette player is unbeatable. Nothing feels better than slamming clunky buttons on a Sony Walkman.</p><p>That’s my biggest problem with Digital Audio Players or DAPs. It seems the audiophile community has rallied around new devices that look like smartphones running a watered-down Android OS. And while vintage looking “mp3-players” exist, they all lack that romanticized and satisfying tactile feel. There’s something sacred and rewarding about spinning a CD, ejecting or flipping a cassette, setting a needle on a record player...</p><h4>At a glance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_PGUlFEcVXt4dmh_01AKA.png" /></figure><p>Introduce NFC cards: these can be highly stylized reminiscent of CD covers and fit in a wallet or dedicated card holder. Tap these to a phone to launch a URL to a personal home webserver that serves music with high quality audio available in a variety of formats. Tapping integrates some haptic feedback that is less satisfying than a cassette for sure, but I’ve tried to bridge the gap using software.</p><h4>How it works</h4><p><strong>From mobile</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8x2k0L8l66XC35VCQpitlw.png" /><figcaption>Tap the NFC card to phone to launch dedicated album URL.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QWY182IJVguc3mZTJFeAw.gif" /><figcaption>On the launch screen, hold to power on retro arcade machine.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tIykfVBDIO4XAuqc9vrSA.gif" /><figcaption>Follow prompts to [INSERT COIN] by tapping unique coin NFC. Web audio player containing album launches.</figcaption></figure><p><strong>From web</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOEIE-D5AU78S8PEJmSzvg.gif" /><figcaption>Visit homepage and unlock jukebox by tuning frequency.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lgjW8mOASeZ0S9J6F8tfw.gif" /><figcaption>Browse by scroll, search, or filter by genre. Shuffle to choose random track from a genre.</figcaption></figure><h3><strong>Code Highlights</strong></h3><h4>Routes</h4><p>This application was designed using Node.js with no front-end libraries like React. Server side is express routes. “retrochung.html” contains all audio player side scripts and styles. “library.html” contains all jukebox scripts and styles. “uploader.html” contains a GUI for any user on the network to upload albums.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdn96dZawNxwC4AF9HsVzw.png" /></figure><p>While each screen is dense with several animations and transitions, there are only a few routes. Each page is organized by compartmentalizing scripting and styling components into separate files, allowing for manageable oversight. The build.js script refactors all the code into singular pages every server restart. I have noticed that uploading a single file to an LLM like Claude helps it diagnose any bugs easier, especially if you don’t have Cowork or Claude installed in your IDE like me.</p><h3>Three.js</h3><p>This was my first experience using Three.js to render 3D elements in browser. The most notable 3D element is the arcade machine that displays after an NFC launches an album URL. All 3D elements were designed by myself in blender. I want to share a few lessons and challenges in hopes that it helps other aspiring developers.</p><h4>Emissivity and Bloom</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjHKka6lqv_vfXCxHhbz_w.png" /><figcaption>Initial 3D Blender model and render.</figcaption></figure><p>The arcade machine model was designed in Blender and my initial renders capture the light of the scene dynamically. The challenge was replicating the render in Three.js, which cannot interpret Blender’s path tracing or global illumination. I experimented with several different light sources, but all of them had noticeably sharp edges and defined shadows. The final solution was derived from game engines practices, using post-processing bloom to bleed bright areas outwards and using emissive materials on side panel LEDs and the coin slot object to animate their intensity in a staggered power-on sequence for the illusion of “warming up”.</p><pre>// Bloom object (post-processing pipeline)<br>import { EffectComposer }  from &#39;three/addons/postprocessing/EffectComposer.js&#39;;<br>import { RenderPass }      from &#39;three/addons/postprocessing/RenderPass.js&#39;;<br>import { UnrealBloomPass } from &#39;three/addons/postprocessing/UnrealBloomPass.js&#39;;<br><br>const composer = new EffectComposer(renderer);<br>composer.addPass(new RenderPass(scene, camera));<br>composer.addPass(new UnrealBloomPass(<br>  new THREE.Vector2(window.innerWidth, window.innerHeight),<br>  0.25,  // strength<br>  0.4,   // radius<br>  0.5    // threshold<br>));</pre><pre>// On model load — clone materials so each mesh has independent control<br>if (name === &#39;Border Lights&#39;) {<br>  child.material = child.material.clone();<br>  child.material.emissive.setRGB(0.3488, 0.9743, 1.0); // cyan-teal<br>  child.material.emissiveIntensity = 0;<br>  borderLightsMat = child.material;<br>}<br>if (name === &#39;Coin Slot&#39;) {<br>  child.material = child.material.clone();<br>  child.material.emissive.setRGB(1.0, 0.0004, 0.0059); // red<br>  child.material.emissiveIntensity = 0;<br>  coinSlotMat = child.material;<br>}<br><br>// Target intensities per element<br>const LIGHT_TARGETS = {<br>  coinSlotEmissive:     2.0,<br>  coinGlowIntensity:    1.0,<br>  borderLightsEmissive: 1.5,<br>  borderGlowIntensity:  1.5,<br>  screenGlowIntensity:  1.5,<br>  titleGlowIntensity:   1.5,<br>};<br><br>// Power-on sequence — each element fades in on a staggered timeline (t = 0 to 1)<br>function updatePowerLights(t) {<br>  const tCoin   = Math.min(Math.max((t - 0.15) / 0.3,  0), 1);<br>  const tBorder = Math.min(Math.max((t - 0.35) / 0.35, 0), 1);<br>  const tTitle  = Math.min(Math.max((t - 0.65) / 0.35, 0), 1);<br><br>  if (coinSlotMat)    coinSlotMat.emissiveIntensity    = tCoin   * LIGHT_TARGETS.coinSlotEmissive;<br>  if (borderLightsMat) borderLightsMat.emissiveIntensity = tBorder * LIGHT_TARGETS.borderLightsEmissive;<br><br>  coinGlow.intensity   = tCoin   * LIGHT_TARGETS.coinGlowIntensity;<br>  borderGlow.intensity = tBorder * LIGHT_TARGETS.borderGlowIntensity;<br>  titleGlow.intensity  = tTitle  * LIGHT_TARGETS.titleGlowIntensity;<br>}</pre><h4>Jukebox Text Animations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CntR2TEW-FYDhNbu9_21DA.gif" /></figure><p>The screen element has a canvas texture that constantly rewrites itself each frame with animations. This was the most consistently effective method I found to track the screen and lock animations while the camera moves and pans.</p><pre>// Tetris Fall Effect<br>JUKEBOX_WORD.split(&#39;&#39;).forEach((l, i) =&gt; {<br>  const delay = i * 0.07 / inDur;<br>  const p     = Math.max(0, Math.min(1, (tp - delay) / (1 - delay)));<br>  const ease  = p &lt; 1 ? 1 - Math.pow(1 - p, 3) : 1; // cubic ease out<br><br>  let y = by;<br>  if (jkPhase === &#39;in&#39;)<br>    y = by - 120 * (1 - ease); // drop from 120px above<br>  else if (jkPhase === &#39;out&#39;) {<br>    const op = Math.max(0, Math.min(1, (tp - (JUKEBOX_WORD.length - 1 - i) * 0.06 / outDur)));<br>    y = by + 120 * op * op; // fall away downward, right-to-left<br>  }<br>  const alpha = jkPhase === &#39;out&#39;<br>    ? 1 - Math.pow(Math.max(0, (tp - (JUKEBOX_WORD.length - 1 - i) * 0.06 / outDur)), 0.5)<br>    : (jkPhase === &#39;in&#39; ? ease : 1);<br><br>  jkDrawLetter(l, bx + i * lw, y, jkPalette[i % jkPalette.length], alpha, 1, 1, 0, fs);<br>});<br><br>// Rotating Mirrors Effect<br>JUKEBOX_WORD.split(&#39;&#39;).forEach((l, i) =&gt; {<br>  let sx = 1, alpha = 1;<br>  if (jkPhase === &#39;in&#39;) {<br>    const p    = Math.max(0, Math.min(1, (tp - i * 0.06 / inDur) / (1 - i * 0.06 / inDur)));<br>    const ease = 1 - Math.pow(1 - p, 3);<br>    sx = ease; alpha = ease;<br>  } else if (jkPhase === &#39;out&#39;) {<br>    const p    = Math.max(0, Math.min(1, (tp - (JUKEBOX_WORD.length - 1 - i) * 0.04 / outDur) / (1 - (JUKEBOX_WORD.length - 1 - i) * 0.04 / outDur)));<br>    const ease = p * p; // quadratic ease in<br>    sx = 1 - ease; alpha = 1 - ease;<br>  }<br>  jkDrawLetter(l, bx + i * lw, by, jkPalette[i % jkPalette.length], alpha, sx, 1, 0, fs);<br>});<br><br>// Slot Machine Effect<br>JUKEBOX_WORD.split(&#39;&#39;).forEach((l, i) =&gt; {<br>  const s = jkLetterState[i]; // each letter has its own stopTime<br>  let ch = l, alpha = 1, sy = 1;<br><br>  if (jkPhase === &#39;in&#39;) {<br>    if (t &lt; s.stopTime) {<br>      // Still spinning — show random drum character with vertical wobble<br>      ch    = JK_DRUM[Math.floor(Math.random() * JK_DRUM.length)];<br>      alpha = Math.min(t / 0.2, 1);<br>      sy    = 1 + 0.15 * Math.sin(t * 20 + i);<br>    } else if (!s.locked) {<br>      // Just locked — brief scale pop<br>      s.locked = true; sy = 1.3;<br>      setTimeout(() =&gt; { if (jkLetterState[i]) jkLetterState[i].locked = &#39;settled&#39;; }, 100);<br>    } else {<br>      sy = s.locked === &#39;settled&#39; ? 1 : 1.3;<br>    }<br>  } else if (jkPhase === &#39;out&#39;) {<br>    const delay = (JUKEBOX_WORD.length - 1 - i) * 0.06 / outDur;<br>    const p     = Math.max(0, Math.min(1, (tp - delay) / (1 - delay)));<br>    sy    = 1 + p * 2;<br>    alpha = 1 - p;<br>    ch    = p &gt; 0.3 ? JK_DRUM[Math.floor(Math.random() * JK_DRUM.length)] : l;<br>  }<br>  jkDrawLetter(ch, bx + i * lw, by, jkPalette[i % jkPalette.length], alpha, 1, sy, 0, fs);<br>});<br><br>// Glitch Scatter Effect<br>const JK_GLITCH = &#39;!@#$%^&amp;*&lt;&gt;?/\\|~&#39;;<br><br>JUKEBOX_WORD.split(&#39;&#39;).forEach((l, i) =&gt; {<br>  let ch = l, alpha = 1, dx = 0, dy = 0;<br><br>  if (jkPhase === &#39;in&#39;) {<br>    const g = 1 - tp; // glitch decreases as t increases<br>    if (Math.random() &lt; g * 0.5) ch = JK_GLITCH[Math.floor(Math.random() * JK_GLITCH.length)];<br>    dx    = (Math.random() - 0.5) * 18 * g;<br>    dy    = (Math.random() - 0.5) * 14 * g;<br>    alpha = Math.min(tp * 3, 1);<br>  } else if (jkPhase === &#39;hold&#39;) {<br>    // Occasional glitch pulse during hold<br>    const g = Math.sin(t * 3) * 0.2;<br>    if (Math.random() &lt; g) {<br>      ch = JK_GLITCH[Math.floor(Math.random() * JK_GLITCH.length)];<br>      dx = (Math.random() - 0.5) * 8;<br>      dy = (Math.random() - 0.5) * 6;<br>    }<br>  } else if (jkPhase === &#39;out&#39;) {<br>    const g = tp;<br>    if (Math.random() &lt; g * 0.7) ch = JK_GLITCH[Math.floor(Math.random() * JK_GLITCH.length)];<br>    dx    = (Math.random() - 0.5) * 60 * g * g; // quadratic scatter<br>    dy    = (Math.random() - 0.5) * 50 * g * g;<br>    alpha = 1 - Math.pow(tp, 1.5);<br>  }<br>  jkDrawLetter(ch, bx + i * lw + dx, by + dy, jkPalette[i % jkPalette.length], alpha, 1, 1, 0, fs);<br>});<br><br>// Typewriter Static Effect<br>const JK_STATIC = &#39;░▒█▓&#39;;<br><br>const charDelay = inDur / JUKEBOX_WORD.length;<br>JUKEBOX_WORD.split(&#39;&#39;).forEach((l, i) =&gt; {<br>  let ch = &#39; &#39;, alpha = 0;<br><br>  if (jkPhase === &#39;in&#39;) {<br>    const elapsed = t - i * charDelay;<br>    if (elapsed &gt; 0) {<br>      alpha = 1;<br>      // Show static briefly before the real letter resolves<br>      ch = elapsed &lt; 0.24<br>        ? JK_STATIC[Math.floor(Math.random() * JK_STATIC.length)]<br>        : l;<br>    }<br>  } else if (jkPhase === &#39;hold&#39;) {<br>    ch = l; alpha = 1;<br>  } else if (jkPhase === &#39;out&#39;) {<br>    const delay = i * 0.05 / outDur;<br>    const p     = Math.max(0, Math.min(1, (tp - delay) / (1 - delay)));<br>    ch    = p &gt; 0.3 ? JK_STATIC[Math.floor(Math.random() * JK_STATIC.length)] : l;<br>    alpha = 1 - p;<br>  }<br>  if (ch !== &#39; &#39;) jkDrawLetter(ch, bx + i * lw, by, jkPalette[i % jkPalette.length], alpha, 1, 1, 0, fs);<br>});<br><br>// Spin In Effect<br>JUKEBOX_WORD.split(&#39;&#39;).forEach((l, i) =&gt; {<br>  const delay = i * 0.07 / inDur;<br>  const p     = Math.max(0, Math.min(1, (tp - delay) / (1 - delay)));<br>  const dir   = i % 2 === 0 ? 1 : -1; // alternate rotation direction<br>  let rot = 0, sc = 1, alpha = 1;<br><br>  if (jkPhase === &#39;in&#39;) {<br>    const ease = 1 - Math.pow(1 - p, 3);<br>    rot   = dir * Math.PI * 2 * (1 - ease); // full rotation on the way in<br>    sc    = ease;<br>    alpha = ease;<br>  } else if (jkPhase === &#39;hold&#39;) {<br>    sc = 1 + 0.04 * Math.sin(t * 3 + i * 0.5); // gentle breathing<br>  } else if (jkPhase === &#39;out&#39;) {<br>    const op   = Math.max(0, Math.min(1, (tp - i * 0.05 / outDur) / (1 - i * 0.05 / outDur)));<br>    const ease = op * op;<br>    rot   = -dir * Math.PI * 2 * ease; // spin out in opposite direction<br>    sc    = 1 - ease;<br>    alpha = 1 - ease;<br>  }<br>  jkDrawLetter(l, bx + i * lw, by, jkPalette[i % jkPalette.length], alpha, sc, sc, rot, fs);<br>});<br><br>// Matrix Rain Effect<br>JUKEBOX_WORD.split(&#39;&#39;).forEach((l, i) =&gt; {<br>  const s  = jkLetterState[i]; // s.startDelay = i * 0.12<br>  let ch = l, alpha = 1, sc = 1;<br><br>  if (jkPhase === &#39;in&#39;) {<br>    const elapsed  = t - s.startDelay;<br>    if (elapsed &lt; 0) return; // not started yet<br>    const lockTime = 0.6;<br>    if (elapsed &lt; lockTime) {<br>      // Cycling through random chars, partially transparent<br>      ch    = JK_CHARS_POOL[Math.floor(Math.random() * JK_CHARS_POOL.length)];<br>      alpha = Math.min(elapsed / 0.2, 0.7);<br>    } else {<br>      // Locked to correct letter — brief scale flash<br>      ch = l; alpha = 1;<br>      if (!s.locked) {<br>        s.locked = true; sc = 1.2;<br>        setTimeout(() =&gt; { if (jkLetterState[i]) jkLetterState[i].sc = 1; }, 150);<br>      }<br>      sc = s.sc || 1;<br>    }<br>  } else if (jkPhase === &#39;hold&#39;) {<br>    ch = l; alpha = 1;<br>  } else if (jkPhase === &#39;out&#39;) {<br>    const delay = i * 0.09 / outDur;<br>    const p     = Math.max(0, Math.min(1, (tp - delay) / (1 - delay)));<br>    if (p &gt; 0) {<br>      ch    = p &gt; 0.5 ? JK_CHARS_POOL[Math.floor(Math.random() * JK_CHARS_POOL.length)] : l;<br>      alpha = 1 - p;<br>    }<br>  }<br>  jkDrawLetter(ch, bx + i * lw, by, jkPalette[i % jkPalette.length], sc || 1, 1, 0, fs);<br>});</pre><p>I designed 7 distinct entrances and exit effects that cycle randomly, as shown above. Each effect has a three phase lifecycle with letters animating independently using staggered delays and timing offsets. Color palettes are also cycled randomly.</p><pre>// Stagger each letter&#39;s animation by offsetting its normalized progress<br>const delay = i * 0.07 / inDur;<br>const p = Math.max(0, Math.min(1, (tp - delay) / (1 - delay)));<br>const ease = 1 - Math.pow(1 - p, 3); // cubic ease out</pre><h4>Autoplay and Suspension</h4><p>One of the biggest constraints was working around media autoplay settings. By default, user gesture is required to enable media which were necessary for sound effects and auto-playing the album. Surprisingly, NFC scans do not count as a user gesture. Several of the design features were incorporated to make this a natural integration. These include tapping and holding to power on the arcade machine and tuning the radio frequency to unlock the jukebox library.</p><p>Another obstacle was the automatic suspension of media whenever the phone screen turned off or locked. I resolved this with a three-tiered scheduler that calculates the remaining time of a track after playing and decides to fire immediately, set a precise final timer, or set an adaptive heartbeat that re-checks at intervals of remaining time/3 (capped at 8 seconds). Further testing showed that when a screen locks, iOS/Android fires a pause event that the code will now ignore entirely so that the player doesn’t think the user manually paused.</p><pre>const MAX_HEARTBEAT_MS = 8000; // never wait more than 8s between checks<br><br>function _scheduleAdvance(remaining) {<br>  if (remaining &lt;= 0.5) {<br>    // At or past end — advance immediately<br>    loadTrack(_getNextIndex(), true);<br><br>  } else if (remaining &lt;= 8.5) {<br>    // Close to end — set a precise final timer<br>    const delay = Math.max(0, (remaining - 0.5) * 1000);<br>    _advanceTimer = setTimeout(() =&gt; loadTrack(_getNextIndex(), true), delay);<br><br>  } else {<br>    // Far from end — set a heartbeat that re-checks at remaining/3, max 8s<br>    const hbMs = Math.min(MAX_HEARTBEAT_MS, Math.floor(remaining / 3 * 1000));<br>    _heartbeatTimer = setTimeout(() =&gt; {<br>      const newRemaining = audio.duration - audio.currentTime;<br>      _scheduleAdvance(newRemaining); // recurse with updated remaining time<br>    }, hbMs);<br>  }<br>}<br><br>// Ignore OS-forced pauses while screen is locked<br>audio.addEventListener(&#39;pause&#39;, () =&gt; {<br>  if (document.visibilityState !== &#39;visible&#39;) return; // screen locked — ignore<br>  setPlaying(false);<br>});</pre><h4>Uploading and Tagging</h4><pre>def analyze_track(filepath):<br>    y, sr = librosa.load(filepath, sr=22050, mono=True)<br><br>    # BPM — beat tracking<br>    tempo, beats = librosa.beat.beat_track(y=y, sr=sr)<br>    bpm = round(float(np.atleast_1d(tempo)[0]), 1)<br><br>    # Energy — RMS loudness normalized to a -30dB to -3dB range<br>    rms      = librosa.feature.rms(y=y)[0]<br>    rms_mean = float(np.mean(rms))<br>    db       = 20 * np.log10(rms_mean) if rms_mean &gt; 0 else -60.0<br>    energy   = round(float(np.clip((db - (-30.0)) / ((-3.0) - (-30.0)), 0.0, 1.0)), 3)<br><br>    # Brightness — spectral centroid normalized to 500Hz–4000Hz<br>    # High = airy/cymbal-heavy. Low = bass-heavy/dark/muffled.<br>    centroid      = librosa.feature.spectral_centroid(y=y, sr=sr)[0]<br>    centroid_mean = float(np.mean(centroid))<br>    brightness    = round(float(np.clip(<br>        (centroid_mean - 500.0) / (4000.0 - 500.0), 0.0, 1.0<br>    )), 3)<br><br>    # Danceability — onset strength consistency (low variance = steady beat = high danceability)<br>    onset_env  = librosa.onset.onset_strength(y=y, sr=sr)<br>    onset_norm = onset_env / (np.max(onset_env) + 1e-6)<br>    danceability = round(float(np.clip(<br>        float(np.mean(onset_norm)) / (float(np.std(onset_norm)) + 0.1), 0.0, 1.0<br>    )), 3)<br><br>    # Valence — approximated from mode, brightness, and tempo<br>    # Spotify&#39;s valence is proprietary; this is a weighted approximation.<br>    mode_score  = 0.7 if mode == &#39;major&#39; else 0.3<br>    bpm_norm    = float(np.clip((bpm - 40.0) / (200.0 - 40.0), 0.0, 1.0))<br>    bpm_score   = 1.0 - abs(bpm_norm - 0.5) * 2  # peaks at ~120 BPM, falls at extremes<br>    valence     = round(float(np.clip(<br>        0.5 * mode_score + 0.3 * brightness + 0.2 * bpm_score, 0.0, 1.0<br>    )), 3)</pre><p>“analyze-albums.py” uses librosa to algorithmically retrieve bpm, energy, brightness, valence, and danceability to add to album.json.</p><ol><li>BPM is defined as Beats Per Minute or the tempo of the track, measured by detecting rhythmic pulse in the audio signal and calculating how frequently they occur.</li><li>Energy is defined as a measure of loudness, calculated from the Root Mean Square (RMS) of the amplitude of the audio signal. Normalized to a 0–1 scale anchored between -30 dB to -3 dB.</li><li>Brightness is defined as the “timbre” of the track, or more formally the spectral center of the audio on the frequency spectrum. Normalized to a range of 500 Hz — 4000 Hz.</li><li>Danceability is defined as the steadiness and consistency of the beat. It’s determined from detecting signal spikes whenever a new note or transient occurs. Calculated as a mean divided by standard deviation to capture both the strength and consistency of the beat.</li><li>Valence is defined as the positivity of a track. Highly subjective, but I chose to weigh a combination of the key mode (major or minor), brightness, and tempo.</li></ol><pre>def genius_search(artist, title):<br>    params = urllib.parse.urlencode({&quot;q&quot;: f&quot;{title} {artist}&quot;})<br>    req    = urllib.request.Request(<br>        f&quot;https://api.genius.com/search?{params}&quot;,<br>        headers={&quot;Authorization&quot;: f&quot;Bearer {GENIUS_TOKEN}&quot;}<br>    )<br>    with urllib.request.urlopen(req, timeout=10) as r:<br>        data = json.loads(r.read())<br>    hits = data.get(&quot;response&quot;, {}).get(&quot;hits&quot;, [])<br>    # Reject false positives — only return a match if the artist name actually matches<br>    for hit in hits:<br>        h        = hit.get(&quot;result&quot;, {})<br>        h_artist = h.get(&quot;primary_artist&quot;, {}).get(&quot;name&quot;, &quot;&quot;).lower()<br>        if artist.lower() in h_artist or h_artist in artist.lower():<br>            return h<br>    return None<br><br>def scrape_genius_tags(page_url):<br>    req  = urllib.request.Request(page_url, headers={&quot;User-Agent&quot;: &quot;Mozilla/5.0&quot;})<br>    html = urllib.request.urlopen(req, timeout=10).read().decode(&quot;utf-8&quot;, errors=&quot;replace&quot;)<br>    # Scrape SongTags elements from the rendered HTML<br>    names = re.findall(r&quot;SongTags[^\&quot;]*\&quot;[^&gt;]*&gt;\s*([A-Za-z][^&lt;]{1,40}?)\s*&lt;&quot;, html)<br>    # Filter out non-genre metadata tags (language, region, demographic labels)<br>    SKIP = {&quot;in english&quot;, &quot;usa&quot;, &quot;uk&quot;, &quot;soundtrack&quot;, &quot;boy band&quot;, &quot;girl group&quot;, ...}<br>    return [n.strip() for n in names if n.lower() not in SKIP]</pre><p>I use Genius API to retrieve song URLs based on track titles and from each URL, I scrape the webpage to get a list of track tags stored as an array of the track’s relevant genres.</p><h3>Gacha Playlist Creation and Curation</h3><p>Unlike other music players, my version of the player has no playlist function to allow users to group together single songs across different albums. This was an intentional design choice to reorient my listening habits to consume full albums. But, I still wanted a feature that combined the two concepts where I could have more diverse taste for a specific mood or setting, but limit how often it was available.<br><br>Traditional streaming services have this feature too, in the form of algorithmically generated playlists based on listening habits. These relevant playlists are usually created by utilizing their large user base, making it possible to see connections between what people like. My home server only has a few people connected to it (friends/family limited under 5 users total). Each person can upload albums, but getting into a full album someone else uploaded is a commitment. Natural music discovery to me is finding one track you like then deciding to explore more.</p><h4>How it works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVbggNcuU3EeoB1HOFezoQ.gif" /></figure><ol><li>From the library home page, tap the arrow indicator to open the Gacha screen to the right.</li><li>Up to 5 spins are rewarded to a device. Spin to generate playlist.</li><li>Each slot corresponds to a characteristic of a track, such as: mood, speed, and setting.</li><li>User can decide to save a playlist if they liked the generation.</li><li>Unsaved playlists are deleted and refreshed every 30 minutes.</li></ol><h4>Slot Categories</h4><p>Playlists are defined by 3 characteristics: Mood, Speed, and Setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRNjtrRTnkAAQQ-JGsIyNw.png" /></figure><p>These combinations help create 5 playlists that are predetermined and shared between users, although each device might receive the playlists in a different order.</p><h4>Playlist Generation AI</h4><p>Even with a small user base, our constantly expanding library has over 50 albums averaging 10–20 songs per album (with more than one album containing OSTs and soundtracks over 100 songs). Several stages of filtering and curation are necessary to provide enough diversity to generate adequate playlists. First, a limit of 20 songs are randomly selected per album to join a larger pool. This helps reduce the concentration of oversaturated albums.</p><p>Next, each track is prefiltered into a smaller set containing 80 songs based on two affinity scores: one for mood and one for setting. Affinity scores are calculated based on an initial mood/setting calculated from song meta data by “analyze-albums.py”. A track’s base affinity is computed from the Euclidean distance across 4 features (valence, energy, brightness, danceability):</p><pre>base_affinity(track, node) = 1 - dist(track_features, node_vector) / √4</pre><p>Based on the starting mood and setting, subsequent affinity scores are calculated by edge distance on a weighted graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDkLpAGx1Mpym0IIU5repg.png" /></figure><p>In a weighted graph, nodes (or vertices) are connected by lines (or edges) with weights based on shared relation. For my use case, each node represent a slot category (such as sunny for mood, or bedroom for setting) and edge weights are normalized to a value between 0 and 1 (with 1 representing a close relationship). As an example, sunny is closely related to cloudy while stormy has no direct edge to sunny. The gym setting is highly isolated with only one asymmetric edge connecting to drive. The affinity for another category from a starting node can be calculated by:</p><pre>A&#39;(node) = A(node) + ( Σ A(neighbor) × weight(neighbor→node) ) × 0.15 / num_neighbors</pre><p>where 0.15 is the propagation factor.</p><p>The process of calculating affinity scores for adjacent nodes is an important part of the prefiltering step to help recharacterize certain tracks in different contexts. Suppose a track like Espresso by Sabrina Carpenter (high valence ~0.85, high energy ~0.7, high brightness ~0.75, high danceability ~0.75) is originally labeled as “Sunny” with a base affinity of ~0.88. Its base affinity for cloudy would be lower (~0.55), but because sunny and cloudy share an edge weight of 0.883, the propagation step adds a correction of roughly:</p><pre>0.88 × 0.883 × 0.15 / 1 ≈ +0.12</pre><p>with a final cloudy affinity of ~0.67. In the right playlist in conjunction with a certain setting, it could still appear in a cloudy playlist. Notice that a sample calculation for stormy would produce a very low base affinity (close to 0). Since sunny has no direct edge to stormy in the graph, no propogation correction applies either, effectively eliminating it from all stormy playlists.</p><p>After the prefiltering step, a playlist of 12 tracks is further curated through local LLM models via ollama. “qwen” is the model chosen for playlist generation and “gemma” is chosen for naming. qwen is given the following prompt:</p><blockquote>You are curating a music playlist for a home jukebox.<br>Here is the feeling you are going for:</blockquote><blockquote>Mood: [combo description]<br>Pace: [speed description]<br>Setting: [setting description]</blockquote><blockquote>Target BPM range: [lo]–[hi]<br>Target valence: [high/mid/low]</blockquote><blockquote>Pick 12 tracks from the numbered library below that best match this feeling.</blockquote><blockquote>When scoring each track, weight these factors in order of importance:<br>1. BPM (40%) — primary guide for pace<br>2. Valence (35%) — emotional positivity<br>3. Energy (25%) — intensity level<br>4. Genre tags — soft signal for character</blockquote><blockquote>Key and mode are additional mood signals: minor keys tend darker, major keys brighter.<br>Spread picks across at least 3 different artists.</blockquote><blockquote>Respond with ONLY this JSON — trackIndices MUST contain exactly 12 numbers:<br>{“trackIndices”:[0,1,2,…],”reasoning”:”brief note on curation”}</blockquote><p>gemma names each playlist and provides a description.</p><blockquote>Name these 5 playlists based on their track listings.</blockquote><blockquote>Playlist 1 (sunny/quick/cafe):<br> — Artist — “Track Title” (Genre, Genre)<br> …</blockquote><blockquote>Write each name like a note you typed in your phone at 1am, or a thought <br>you had in the shower.<br>Do not use artist names, genre names, underscores, hyphens, or describe <br>what the music sounds like.<br>All 5 must be structurally different. One must be unexpected.<br>Mostly lowercase, 2–8 words. ALL CAPS for one or two words MAX.</blockquote><blockquote>For the description: look only at the NAME you just wrote. One dry offhand <br>sentence extending the joke. Not poetic. Not about the music.</blockquote><blockquote>Respond with ONLY this JSON:<br>{“playlists”:[{“name”:”string”,”description”:”string”}]}</blockquote><h4>User Feedback Loop</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*icrVjUTjtT6QFOKdrDBl7A.png" /></figure><p>Each playlist opens in a player identical to a normal album player, but with an additional feature that allows each user to rate the fit of the track for mood and setting on a scale of 1–5. Depending on the magnitude of the rating, the affinity is nudged in that direction based on the average rating across users, which makes meaningful improvements over time. The nudge magnitude is defined as:</p><pre>magnitude = (rating - 3) x 0.08<br>// 5 star rating shifts affinity by +0.16<br>// 1 star rating shifts affinity by -0.16</pre><p>Ratings are not written to the server immediately and are instead stored in the device’s localStorage and flushed to the server once the next gacha batch is detected.</p><h4>Mosaic Cover Art</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*0vgtVMm57_ILLD4i3d3OIw.png" /></figure><p>Each playlist album is generated with a technique known as <a href="https://en.wikipedia.org/wiki/Voronoi_diagram">Voronoi Mosaic</a>. A set of random seed points are scattered across a predefined square, where each point possesses ownership of a specific region and creates edge boundaries that form Voronoi cells.</p><pre>function _mosaicRand(seed) {<br>  let s = typeof seed === &#39;string&#39; ? _mosaicHash(seed) : (seed | 0);<br>  return () =&gt; {<br>    s = Math.imul(s ^ (s &gt;&gt;&gt; 16), 0x45d9f3b);<br>    s = Math.imul(s ^ (s &gt;&gt;&gt; 16), 0x45d9f3b);<br>    return ((s ^ (s &gt;&gt;&gt; 16)) &gt;&gt;&gt; 0) / 0xffffffff;<br>  };<br>}</pre><p>The geometry is deterministic. Playlist ID is hashed into a seed value via mosaicHash which creates a pseudo-random number generator. This process ensures that the same layout is identical for an individual playlist across several page loads and devices.</p><pre>function _mosaicHash(str) {<br>  let h = 0x811c9dc5; // FNV offset basis<br>  for (let i = 0; i &lt; str.length; i++) {<br>    h ^= str.charCodeAt(i);<br>    h = Math.imul(h, 0x01000193); // FNV prime<br>  }<br>  return h &gt;&gt;&gt; 0;<br>}</pre><p>Cell polygons are computed using the <a href="https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm">Sutherland-Hodgman</a> clipping algorithm where each polygons starts as the full canvas square and is iteratively clipped against the perpendicular bisector between its seed point and every other seed point (with an additional safeguard to discard slivers that are too small and would show too little of the album cover to be meaningful). Each cell is assigned one of 12 album covers from the playlist, creating a composite image that is literally fragments of the real album covers.</p><pre>function _clipPolygon(poly, nx, ny, d) {<br>  const out = [];<br>  for (let i = 0; i &lt; poly.length; i++) {<br>    const a = poly[i], b = poly[(i + 1) % poly.length];<br>    const da = nx * a[0] + ny * a[1] - d; // signed distance from edge<br>    const db = nx * b[0] + ny * b[1] - d;<br>    if (da &lt;= 0) out.push(a);             // a is inside — keep it<br>    if ((da &lt; 0 &amp;&amp; db &gt; 0) || (da &gt; 0 &amp;&amp; db &lt; 0)) {<br>      // Edge crosses the clip boundary — compute intersection<br>      const t = da / (da - db);<br>      out.push([a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]);<br>    }<br>  }<br>  return out;<br>}<br><br>function _buildVoronoiPolygons(n, seedStr, size) {<br>  const r    = _mosaicRand(seedStr);<br>  const pts  = Array.from({ length: n * 2 }, () =&gt; [r() * size, r() * size]);<br>  const rect = [[0,0],[size,0],[size,size],[0,size]];<br><br>  return pts.map((p, i) =&gt; {<br>    let poly = [...rect]; // start with full canvas<br>    for (let j = 0; j &lt; pts.length; j++) {<br>      if (i === j || !poly.length) continue;<br>      const q  = pts[j];<br>      const mx = (p[0] + q[0]) / 2;<br>      const my = (p[1] + q[1]) / 2;<br>      const nx = p[0] - q[0];<br>      const ny = p[1] - q[1];<br>      // Clip against the perpendicular bisector between p and q<br>      poly = _clipPolygon(poly, nx, ny, nx * mx + ny * my);<br>    }<br>    return poly;<br>  }).filter(poly =&gt; poly.length &gt;= 3);<br>}</pre><h3>Discovery</h3><p>Although it’s a step towards the right direction, the gacha playlist is only as good as the evolving library it draws from. The deliberately slow and organic expansion of the library is intentional, eliciting the same excitement of actually growing a physical collection. The obvious drawback is that the same albums keep resurfacing. How do we introduce new albums without forcing a commitment or automating something that should feel personal?</p><p>My solution was creating a scheduled discovery feed. Twice a day (at 9AM and 9PM), the server queries Last.fm for artists similar to a random selection from the existing library.</p><pre>async function getSimilarArtists(artist) {<br>  const url = `https://ws.audioscrobbler.com/2.0/?method=artist.getSimilar<br>    &amp;artist=${encodeURIComponent(artist)}<br>    &amp;api_key=${LASTFM_KEY}&amp;format=json&amp;limit=20`;<br>  const data = await fetchJSON(url);<br>  return (data.similarartists?.artist || []).map(a =&gt; ({<br>    name:  a.name,<br>    match: parseFloat(a.match),<br>  }));<br>}<br><br>async function getTopTrack(artist) {<br>  const tracks = (await fetchJSON(<br>    `https://ws.audioscrobbler.com/2.0/?method=artist.getTopTracks<br>      &amp;artist=${encodeURIComponent(artist)}<br>      &amp;api_key=${LASTFM_KEY}&amp;format=json&amp;limit=10`<br>  )).toptracks?.track || [];<br>  if (!tracks.length) return null;<br><br>  // Pick randomly from top 5 rather than always taking #1<br>  const pool = tracks.slice(0, 5);<br>  const t    = pool[Math.floor(Math.random() * pool.length)];<br><br>  // getTopTracks doesn&#39;t include album - requires a second call<br>  let album = null;<br>  try {<br>    const info = await fetchJSON(<br>      `https://ws.audioscrobbler.com/2.0/?method=track.getInfo<br>        &amp;artist=${encodeURIComponent(artist)}<br>        &amp;track=${encodeURIComponent(t.name)}<br>        &amp;api_key=${LASTFM_KEY}&amp;format=json`<br>    );<br>    album = info.track?.album?.title || null;<br>  } catch(e) {}<br><br>  return { title: t.name, album };<br>}</pre><p>For each similar artist, it finds a representative track and queries Deezer for a 30 second preview.</p><pre>async function getDeezerPreview(artist, track) {<br>  const q    = encodeURIComponent(`artist:&quot;${artist}&quot; track:&quot;${track}&quot;`);<br>  const data = await fetchJSON(`https://api.deezer.com/search?q=${q}&amp;limit=3`);<br>  for (const r of (data.data || [])) {<br>    if (r.preview?.length &gt; 0) {<br>      return {<br>        previewUrl: r.preview,<br>        albumTitle: r.album?.title  || null,<br>        albumCover: r.album?.cover_medium || null,<br>      };<br>    }<br>  }<br>  return null; // no preview available — skip this track<br>}</pre><p>The feed is limited to 3 tracks per session — realistically, most people don’t need to find more than 6 new songs per day. This design implementation is purposefully lightweight and restrictive. No rating, short previews, no automatic downloads. I wanted to keep friction to incentivize exploration outside the platform, making finding and downloading the album a conscious effort. Each album in the system was truly added by a person who actually wanted it there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*crBCP2IOIy3-MWHkt-rJWw.png" /></figure><h3>Conclusion</h3><p>I find it overwhelmingly easy to surrender to the convenience of the status quo that promotes shelf-stable products with a legacy in a market that rewards dynasties by suffocating innovation. This project is my first step in a long process of recognizing the importance of agency and taking ownership. Designing the web app, library, and player exactly how I envisioned them was an incredibly therapeutic and rewarding journey. It has also elevated the importance to me of “doing things the old-fashioned way”. I’m still collecting CDs to rip them to my collection, reanimating third spaces in my routine. I imagine that the eye-catching designs on my custom NFC cards are topics of discussion, a nod to how music might have been shared just a few short decades ago.</p><p>These project files are available on my <a href="https://github.com/richung99/nfc-music-server">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a4a46c7fb5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/my-neo-retro-solution-to-hoarding-physical-media-0a4a46c7fb5a">My Neo-Retro Solution to Streaming Music</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open Source Monopoly Heatmap]]></title>
            <link>https://medium.com/swlh/open-source-monopoly-heatmap-55766377e99f?source=rss-321ba8f10b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/55766377e99f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[board-games]]></category>
            <category><![CDATA[monopoly]]></category>
            <category><![CDATA[game-theory]]></category>
            <dc:creator><![CDATA[Richard Chung]]></dc:creator>
            <pubDate>Fri, 01 Jan 2021 06:46:46 GMT</pubDate>
            <atom:updated>2021-06-23T02:38:57.461Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Visualization of the Value of Properties using Java and MATLAB</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcgmS3Ud2CxP_d0t5F613w.png" /></figure><p>Whether you love or hate it, Monopoly has cemented itself as a classic tabletop board game and iconic household staple. Its immense popularity throughout the years has garnered dissenting opinions in regards to how the game would best be won. My motivation behind this project is to contribute to this discussion and add to the existing wealth of knowledge.</p><p>This project generates heatmaps of properties visited. The data is obtained from simulations with the number of players, turns, and games provided as input parameters. I hope that this can become a useful resource to the community and help to further develop the metagame. You can find the GitHub repository for this project <a href="https://github.com/richung99/monopoly">here</a>.</p><h3>Background and Assumptions</h3><p>Monopoly is a 2 to 6 player board game where players with an initial game currency move around the edge of an 11x11 gameboard to collect properties and avoid bankruptcy. For brevity, I’ve linked a PDF of the <a href="https://www.hasbro.com/common/instruct/monins.pdf">rules</a> from Hasbro, rather than explaining them here.</p><p>In this section, I also want to highlight some of the necessary background information and clarify five assumptions I made in this project.</p><p>1 There are 3 Chance cards that move players to Railroad spaces. Of these cards, 2 have instructions labeled as <strong>ADVANCE TO THE NEXT RAILROAD</strong> and <strong>ADVANCE TO THE NEAREST RAILROAD</strong>. In my interpretation, “NEXT” Railroad implies that a player token must move forward. “NEAREST” Railroad implies that a player token can move backwards to the Railroad the fewest spaces away. This has been a topic of controversy on several forums, but I want to be transparent about the results presented in the rest of this article. For hardcore enthusiasts, the code can be modified relatively easily to incorporate a different interpretation.</p><p>2 The <strong>MONEY GRAB</strong> Chance card has been removed because it’s garbage. This reduces the total number of Chance cards from 16 to 15.</p><p>3 There are 3 other ways to land in the Jail space apart from “Just Visiting”. A player can roll doubles three times consecutively, receive a Chance or Community Chest card that sends them to Jail, or land on the Go to Jail space. Coincidentally, there are also 3 ways to leave Jail. These methods include paying a $50 fine, using a “Get out of Jail Free” card, or spending 3 turns trying to roll doubles. For simplicity, this simulation assumes that players leave Jail on their first available turn. This means that they never wait to roll doubles for 3 turns.</p><p>4 This simulation does not consider player balance. Therefore, players are never bankrupted and eliminated from the game.</p><p>5 Chance and Community Chest card are shuffled, but “Get out of Jail Free” cards are never removed from the deck and awarded to players. This is implemented for simplicity because player balances are not tracked from assumption #3. There would need to be significant (but potentially worthwhile) revision to the code to check if a player could leave Jail on their first turn from a “Get out of Jail Free” card or by paying the fine.</p><h3>Running the Code</h3><p>This project uses both Java and MATLAB. After downloading from GitHub, start by running MonopolyDriver.java, which will generate all the necessary CSV files for MATLAB to process and plot. The number of players, turns, and games can be edited directly in lines 10–12 of this script. After the relevant CSV files are generated, the MATLAB script will generate and save figures as PNG files in the directory.</p><p>In the following sections, I’ll be providing an overview of the different Java classes developed for this project, as well as a brief summary of the contents of each CSV. The intention of these sections is to provide insight into how the code was developed but is not necessary for understanding the takeaways at the end of this article. For those more interested in reading about the findings and applications, feel free to skip to the Takeaways and Discussion section.</p><h3>Gameboard Java Class</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmoLBcDFngxxsv7bOgc0YQ.png" /><figcaption>Figure 1. Gameboard Java Class summary.</figcaption></figure><p>The Gameboard class keeps track of the properties using a HashMap, where keys are the property indices and values are the number of visits. Property indices are numbered 0 to 39 clockwise around the board starting from GO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*JUIWx-BmmpzGgHyRumQXzg.png" /><figcaption>Figure 2. Property indices and corresponding spaces.</figcaption></figure><p>The Gameboard class also contains the Chance and Community Chest card decks. These decks are implemented as lists of integers and have methods to shuffle the top card and place it at the bottom of the deck. Each deck can be divided into “action” and “stationary” cards. Action cards are defined as cards that move the player token to another square, whereas stationary cards do not. 10 out of 15 Chance cards and 2 out of 18 Community Chest cards are action cards. In the list representation of the card deck, stationary cards are represented by -1 and action cards are indexed starting from 0. Indices and their corresponding meaning for both Chance and Community Cards are shown in the Figures 3 and 4 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Kygfs69xKUoVxcp9Q_UMg.png" /><figcaption>Figure 3. Chance card indices and meanings.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPmCISJX--zoBKPaLOMPDg.png" /><figcaption>Figure 4. Community Chest card indices and meanings.</figcaption></figure><p>Finally, the Gameboard class also has private variables that keep track of the number of visits to the Jail space by method (i.e. from rolling doubles, drawing Chance or Community Chest cards, or landing on the Go to Jail space).</p><h3>Player Java Class</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4G5WXLGx-JHz-N3BLea5VA.png" /><figcaption>Figure 5. Player Java Class summary.</figcaption></figure><p>The Player class keeps track of the index of the Player’s current space. The method move(Gameboard g) changes the Player’s space and updates the gameboard through one of three ways: (1) updating the number of visits to a property, (2) shuffling Chance/Community Chest cards, or (3) updating the frequency of visiting Jail by method. Players only record the final space that they land on. Therefore, a Player landing on property index 30 (or the Go to Jail space) does not actually increment the number of visits for property 30 in the Gameboard object, but actually increments space 10 (the Jail space). Similarly, a Player drawing an action Chance card does not increment the Chance space, but rather increments the destination space.</p><h3>CSV Files Generated</h3><p>sampleGame.csv is a table where rows refer to property indices and columns refer to turn number. Each cell refers to the total number of visits up to that turn for the property of that row. The data in sampleGame is populated by the average of all games played in the simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*L_NLNZ2DxcPNndSi5pyISQ.png" /><figcaption>Figure 6. Partial screenshot of sampleGame.csv. The first column containing property indices is frozen from View &gt;&gt; Freeze First Column in Excel, and conditional formatting is applied for easier visualization of the data.</figcaption></figure><p>allGames.csv is a table where rows refer to property indices and columns refer to game number. Each cell refers to the total number of visits in that game for the property of that row. The last two columns are reserved for the sum of that row, and the average of that row respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*ZHni-4-11mZQmRbImQhMfg.png" /><figcaption>Figure 7. Partial screenshot of allGames.csv. The first column containing property indices is frozen from View &gt;&gt; Freeze First Column in Excel, and conditional formatting is applied on the last two columns for easier visualization of the data.</figcaption></figure><p>heatmapSum.csv processes the data from allGames.csv and stores it in a 11x11 matrix, the borders of which represent the spaces on a Monopoly gameboard. The total number of visits to each property, stored in the second to last column of allGames.csv, is placed into its relevant cell in the matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*VrBfPLygKHqxd-GNrXkZGw.png" /><figcaption>Figure 8. Screenshot of heatmapSum.csv. Border represents property indices referenced in Figure 3.</figcaption></figure><p>Similarly to heatmapSum, heatmapAvg.csv stores the last column of allGames.csv containing the average visits per property in an 11x11 matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*FBF8fUhu8x3zf8EP4JXOyQ.png" /><figcaption>Figure 9. Screenshot of heatmapAvg.csv. Border represents property indices referenced in Figure 3.</figcaption></figure><p>propertyStats.csv is a table where rows refer to turn numbers and columns refer to property colors. propertyStats uses the output of sampleGame.csv to sum the total number of visits to properties of a certain color by turn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*G1BedpVLQK5TUFt4LC3wUg.png" /><figcaption>Figure 10. Partial Screenshot of propertyStats.csv.</figcaption></figure><h3>Takeaways and Discussion</h3><p>Trends may start to appear after high turn counts. At 500 turns per game over 1000 games (Figure 11), “warm color” (orange, red, and yellow) properties tend to receive more visits than any other property. But, it’s not uncommon for there to be variation for lower turn count games. For 100 turns per game over 1000 games (Figure 12), there can be disparity between the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*DdQNaUnv9vht4x6vhRE9CQ.png" /><figcaption>Figure 11. 4 sample trials of 4 players, 500 turns, 1000 games. Railroads and warm colors tend to perform best.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*ckinPitavugXR5orRXlYwA.png" /><figcaption>Figure 12. 4 sample trials of 4 players, 100 turns, 1000 games. Railroads still take the lead, but there is less consistency for warm colors compared to simulations at 500 turns.</figcaption></figure><p>Regardless of turn count, Utilities, Brown, and Dark Blue properties consistently underperform. By contrast, Railroads have the highest long term payoff by a wide margin.</p><p>Figure 13 shows heatmaps generated from 4 players, 100 turns, 500 games. These heatmaps show that Jail is by far the most visited space. Tokens classified as Just Visiting are shown in cell (11,1). The remaining instances of going to Jail are stored in cell (10,2) and are easily the brightest spot on the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZbLZUtqJVNw9bCjWdoTXA.png" /><figcaption>Figure 13. Average (left) and Total (right) visits generated from 4 players, 100 turns, 500 games. Spaces closer to white are “brighter” and visited more.</figcaption></figure><p>Figure 13 also shows that Chance cards are much more likely to send a player to a different spot than keep the player stationary. This is expected, since 10 out of 15 Chance cards are action cards.</p><h3>Comparison to Existing Research</h3><p>One popular heatmap floating around the internet is one created by former world champion Bjørn Halvard Knappskog. I compared this heatmap to the ones generated from my simulation. The Knappskog heatmap analyzed 9450 rolls across 330 games. For my simulation, I decided to use a 5-player game for cleaner calculations. I also employed a basic assumption that 1 turn equates to 5 rolls (1 roll per player, discounting chances for doubles). The number of turns used for simulation is then calculated by dividing 5 from 9450 to get 1890 turns. Like Knappskog, I simulated across 330 games and calculated the average number of visits per game square. Both the Knappskog heatmap and my heatmap are shown side by side in Figure 14.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3hgV_Dw7l2QwjGfQ_UhmQ.png" /><figcaption>Figure 14. Heatmap generated from this project (left) vs. Knappskog heatmap (right).</figcaption></figure><p>For the most part, the numbers between both maps are similar. One distinction is that my simulation only records the destination square of the Player (read the Player Java Class section for more details regarding this). It’s not immediately clear how spaces are counted in the Knappskog heatmap. For action spaces that send the player to another space on the gameboard, both the initial and final spaces may be counted in Knappskog’s version. The way that the data is obtained in the original heatmap is also unclear. Throughout my research, I could not find a scholarly article that sourced where the data originated from. It is unknown whether the original heatmap was populated from a computer simulation, or if it was physically recorded from actual games being played.</p><h3>Recommendation for Further Reading</h3><p>There are a few sources I came across while conducting background research that I thought were worth sharing. First, a 2009 research paper titled <em>Estimating the Probability that the Game of Monopoly Never Ends </em>by Friedman et al. is a notable mention. This paper estimates that roughly 40% of games never make it past 100 turns. Past 500 turns, the number of games remaining is less than 20%. This is one of the influences for why I only chose 100 and 500 turn games to analyze in the Takeaways and Discussion section. For readers with a mathematical background and access to libraries or databases, this is a worthwhile read as the paper goes in depth into the use of different estimators.</p><p>Although only moderately related to the topic of this article, <em>Negotiation Strategy of Agents in the MONOPOLY Game</em> by Yasumura, Oguchi, and Nitta in 2001 is a great resource for a better understanding of the game. This paper introduces a case-by-case Card Evaluation function for assessing the value of properties. Although the likelihood of landing on a space is not taken into consideration, this article gives a great holistic view of modelling the decision making process. I think it’s worth investigating if the probability distribution of landing on certain spaces has a place in the Evaluation Function proposed in this paper.</p><p>Finally, I found a project similar to mine <a href="http://www.tkcs-collins.com/truman/monopoly/monopoly.shtml">here</a>. I don’t have a linear algebra background, but I thought it was interesting how a Markov matrix could be applied.</p><h3>Conclusion</h3><p>To begin, I would like to introduce some recommendations for anyone who might be interested in continuing this project. Because I don’t have a statistics or mathematical background, I wasn’t sure if using one player to move around the board was better than using multiple players to move per turn. I also didn’t know how many trials to conduct to come to a statistically sound conclusion. Finally, I’m sure that there are some sources of bias that could be limited. For example, I’ve been told that using Math.random() to control dice rolls might carry some bias with it.</p><p>I want to give a huge shoutout to my sister for helping me with the design and implementation of the Java classes for this project. She’s an AP Computer Science student in high school, and while we both agree that no parts of this project were immensely difficult, it was still worthwhile to pursue to get more exposure to class design and application of data structures. If you discover any bugs in the code, it was most likely her fault (kidding)! In all seriousness, I constantly find myself enjoying computer science more as I combine this skill with my other hobbies. For those struggling to find the motivation to start a new project, I’d recommend taking a step back and trying to find an intersection between two seemingly unrelated interests. As always, thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55766377e99f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/open-source-monopoly-heatmap-55766377e99f">Open Source Monopoly Heatmap</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Paper Mario Ring Puzzles with Tree Traversal in Python]]></title>
            <link>https://python.plainenglish.io/solving-paper-mario-ring-puzzles-with-tree-traversal-f34f5f3680ea?source=rss-321ba8f10b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f34f5f3680ea</guid>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[nintendo]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Richard Chung]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 06:04:22 GMT</pubDate>
            <atom:updated>2021-01-18T17:04:38.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOpvLM0dq-CI0X1IpJO1JA.png" /></figure><p>Paper Mario has always been one of my favorite series and I’ve had a blast playing through and beating the newest installment for Nintendo Switch, Paper Mario: The Origami King. While I thought the story, riddles, and hidden secrets were great, I found the main combat mechanic to be one of the bleakest parts of the game.</p><p>Part of my frustration definitely came from my belief that some of these ring puzzles were unsolvable, so part of the intent of this mini-project was to validate whether or not that was true. The result was a Python script that produces the necessary steps to get a matching lineup every time. I explain the algorithm in detail throughout this article, but it can get technical.</p><p>If you’re just interested in using the script, I’d recommend you first read the ‘Matrix Representation’ section first before skipping to the ‘Using this Script’ section. For reference, the GitHub repository is also linked <a href="https://github.com/richung99/ringpuzzle">here</a>.</p><h3>Background</h3><p>The main combat mechanic of Origami King is arranging enemies in groups of 4 on a ring puzzle board. The ring puzzle board consists of 5 concentric circles. 4 of these circles create <em>rings</em> that are rotatable clockwise or counterclockwise. Each of these circles is also divided into 12 <em>slices </em>that can be shifted back and forth.</p><p>Slices that are directly opposite from one another are connected (like a circular doubly linked list in CS). I’ve attached a GIF below that illustrates this better than I can explain it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*myWUXWQ-qawJVfK76oIPMA.gif" /><figcaption>source: <a href="https://www.youtube.com/watch?v=h3fEELugRVk">https://www.youtube.com/watch?v=h3fEELugRVk</a></figcaption></figure><p>Enemies should be arranged in one of two ways. The first pattern is when all 4 enemies occupy the same slice. The second pattern is when enemies occupy a 2x2 grid directly in front of Mario. The figure below displays these two patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ASkGCzGd_MW-xmPTiE0pg.png" /><figcaption>Two types of attack patterns to arrange enemies highlighted in red.</figcaption></figure><p>Each puzzle has a certain number of “ring moves” that these patterns need to be achieved in. In my play through, I have never observed a puzzle that needed more than 3 ring moves.</p><h3>Summary of Algorithm</h3><p>I use a tree data structure to solve each puzzle. Starting from the initial state of the puzzle board, I generate a list of valid moves. Each move is added as a child node to the current board state. For each child, I will generate more valid moves and continue adding them as children for the number of ring moves that there are in the game. This process is illustrated in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOpvLM0dq-CI0X1IpJO1JA.png" /></figure><p>At the end, I’ll validate all the children of the tree at the depth of the ring move, and return the first one that has a winning game state.</p><h3>Matrix Representation</h3><p>I represent the game state as a matrix. Each ring becomes a row and each slice of that ring acts as a column, creating a 4x12 matrix. The figure below shows how I numbered each of the rings and slices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKkajBtzspdy3KRsFho5RA.png" /><figcaption>Rings are numbered from out to in; indexing starts at 0. Slices are numbered clockwise starting from the left most side (sorry if I triggered you by not numbering them like polar coordinates).</figcaption></figure><p>Each cell of the matrix receives a value of 0 or 1. A value of 0 means that the cell does not contain an enemy, while a value of 1 means that the cell does. In the following figures, I walk through an example containing actual gameplay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGJ01WDcggVjOFE09eAiFw.png" /><figcaption>Real gameplay example. Coordinates for each enemy are provided for reference.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4Ea1UltCKeB7Sls0Z8YJg.png" /><figcaption>Graphical representation of the enemies as 1’s in the matrix.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccW6ah__gnaKG2zArmAvtQ.png" /><figcaption>Matrix representation of the previous figure. Note that rings are the rows and slices are the columns.</figcaption></figure><h3>Spinning and Shifting Methods</h3><p>Spinning modifies the rows of the matrix by moving each cell a certain number of spaces to the right. In the graphical representation, this means that the rings spin clockwise. For simplicity’s sake, I never move the cells to the left or do a counterclockwise spin. Like a circular linked list, the element at the end becomes the first element of the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAAmvGf3ptIqDbSO9Olmwg.png" /><figcaption>Visual representation of the matrix after the outermost ring is shifted one space.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdc631c2938283e88b28046910149889/href">https://medium.com/media/bdc631c2938283e88b28046910149889/href</a></iframe><p>Shifting modifies the columns of the matrix. In the matrix representation, this means that columns 0 to 5 move downwards, but columns 6 to 11 actually move upwards. This is because each column from 0 to 5 is linked with a column 6 indices away from it. In the visual representation we are shifting slice #0 by 1 space. This causes slice #6 to shift upwards by 1 space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKEUsW8X-ntvH97oJ_IwWw.png" /><figcaption>Before and after for shifting slice #0. The red boxes are grouped together. Note that they are 6 columns apart.</figcaption></figure><p>The code for shifting is a little more involved. First, the matrix is transposed so that the columns become rows. Next, each row past index 5 is reversed and appended to a row 6 indices above it. The shifting operation is then performed similarly to the spin operation. Finally, all the transformations are undone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f513749600db4db5beac1c0ff3f50e11/href">https://medium.com/media/f513749600db4db5beac1c0ff3f50e11/href</a></iframe><h3>Checking Win State</h3><p>Recall that there are two types of win patterns to check for. The first pattern is when enemies are aligned in the same slice. I call this the <em>lineup </em>check. The second win pattern is when enemies occupy a 2x2 grid adjacent to the center of the board. I call this the <em>hammer</em> check because Mario can defeat enemies of this pattern using his hammer weapon.</p><p>For (almost) every enemy on the board, I check whether it belongs to a pattern of enemies that is winning. If the enemy does belong to a winning pattern, I clear that entire pattern of enemies from the board and keep iterating until I reach the position of another enemy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48855f7d07cf4d76f1210547fe70d410/href">https://medium.com/media/48855f7d07cf4d76f1210547fe70d410/href</a></iframe><p>The lineup check looks within a specific slice and adds all values of that column to a separate list. The list is then checked to see if it contains all 1’s, representing all enemies. If the list does only contain enemies, then those enemies are removed from the puzzle board and a value of True is returned. Otherwise, the puzzle fails the lineup check.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6617c75d1af734127cb3bee686cd7d25/href">https://medium.com/media/6617c75d1af734127cb3bee686cd7d25/href</a></iframe><p>The hammer check is much more involved than the lineup check. I perform the following procedure:</p><ol><li>Check if the input row is index 2. Enemies occupying indices less than two are too far, and enemies at index 3 should have been eliminated already if they passed a hammer check previously.</li><li>Check if the enemy on row 2 also have enemies positioned directly below them.</li><li>Check if enemies occupy the adjacent spaces on the same ring. This means that I check the left and right side of the current space. If an enemy does not exist to the left, then I verify that it must exist one space to the right, and one space to the right and below. The same logic applies mirrored if an enemy does not exist to the right.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ebac5d12345bb986faf39646d71a3db/href">https://medium.com/media/7ebac5d12345bb986faf39646d71a3db/href</a></iframe><h3>Generating Valid Moves</h3><p>For a given board state, I generate a list of relevant and valid moves. The procedure adheres these two philosophies: (1) I only need to spin rings with enemies on them and (2) I only need to slide the slices with enemies.</p><p>Rather than visiting each space an enemy occupies and generating moves each time, I can just check every ring or slice containing at least one enemy. This will reduce the number of moves generated by eliminating duplicate moves for enemies occupying the same ring or slice.</p><p>Each ring can be rotated anywhere between 1 to 11 times (inclusive). Spinning a ring 12 times results in full rotation and is therefore a useless move. Similarly, each slice can be shifted anywhere between 1 to 7 times (inclusive).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c10e667cb78ab971298ea94797d2e80e/href">https://medium.com/media/c10e667cb78ab971298ea94797d2e80e/href</a></iframe><h3>Tree/Node Class</h3><p>I created a simple Node class in Python that keeps track of its data, children, parent, and depth. If you’re unfamiliar with tree data structures, I’d recommend reading about them <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff16773827139308b3d8b611d9ac4f3d/href">https://medium.com/media/ff16773827139308b3d8b611d9ac4f3d/href</a></iframe><h3>Generating and Traversing the Tree</h3><p>Generating the tree is a recursive process that was already described in a previous section. In this section, I’ll provide the code because it contains slightly more detail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b1586f5eed008863f1d95873c68776d/href">https://medium.com/media/8b1586f5eed008863f1d95873c68776d/href</a></iframe><p>After generating the tree, I traverse the tree in post order, but only collect the Nodes that are at the proper depth. Then, I verify each Node to check if it contains a winning puzzle state. If it does, I’ll collect that Node’s ancestry and store their action strings into a list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40df6d731607f7bc33be469bdab9d2f3/href">https://medium.com/media/40df6d731607f7bc33be469bdab9d2f3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/652243591b1f4b5519f94e9a87b3e58f/href">https://medium.com/media/652243591b1f4b5519f94e9a87b3e58f/href</a></iframe><p>My annotations didn’t feel that helpful for this section, but it’s way easier to copy this repository and trace the logic through some debugger.</p><h3>Using this Script</h3><p>You can clone this GitHub repository <a href="https://github.com/richung99/ringpuzzle">here</a>.</p><p>After running <strong>ringsolver.py</strong>, you will be prompted with entering the total number of enemies, followed by the ring and slice of each enemy, and finally the number of ring moves. I didn’t program any validation on the user input, but the correct data type to enter is integers. You can follow the coordinate system outlined by the section ‘Matrix Representation’ for the position of each enemy.</p><p>The program outputs a list of the moves to take in order. Note that the direction the ring spins is always clockwise. For slice shifting, slices 0 to 5 shift towards the center and slices 6 to 11 shift away.</p><p>The figure and GIF below shows an example puzzle being solved. You can verify the solution yourself!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8lQ-XDCKjjn5eBP8hXgiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WQl90sbBf03unMbkS9y7wA.gif" /></figure><p>As a side note, inputting 0 for the number of enemies will pull up a preloaded puzzle board to solve as a demo.</p><h3>Concluding Remarks</h3><p>This was surprisingly one of the more fulfilling projects I’ve worked on. It was definitely more fun designing this than it was actually solving ring puzzles. It was also a fun blog post to write and I’m really happy with how the visuals I created turned out.</p><p>I haven’t taken many formal CS courses, so if there are any optimization techniques that anyone knows about, drop a hint in the comments and I’ll look into them! I came across some references to “pruning” while troubleshooting but I’m not entirely sure how relevant those would be for this project. I’ve only tested this algorithm for puzzles that go to depth 3, but I’m sure that puzzles at depth 4 (if they exist) would have an atrocious run time.</p><p>This also leads to a series of interesting questions. Does the number of rings and slices affect the required depth necessary for a puzzle? Is there a limit to the number of enemies you can have on the puzzle at once? Are there unsolvable puzzles? In any case, thanks Paper Mario for all the laughs, thoughts, and discoveries inside and outside of your game!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f34f5f3680ea" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/solving-paper-mario-ring-puzzles-with-tree-traversal-f34f5f3680ea">Solving Paper Mario Ring Puzzles with Tree Traversal in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Ecommerce Store from Scratch]]></title>
            <link>https://javascript.plainenglish.io/building-an-ecommerce-store-from-scratch-fe80c409eb67?source=rss-321ba8f10b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe80c409eb67</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[paypal]]></category>
            <dc:creator><![CDATA[Richard Chung]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 06:23:35 GMT</pubDate>
            <atom:updated>2021-01-18T17:10:22.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an eCommerce Store from Scratch</h3><p>This summer, I decided to build a web store to organize the sale of my custom printed sweatshirts. You can visit this project at <a href="https://shopblth.com/">https://shopblth.com</a>, but note that the checkout has been set in a developer sandbox mode so payments will be denied at this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2LG41kAnj8ggjXgkksQ9w.png" /></figure><p>The content of this blog post is technical in nature, so it may be a bit of a dry read. Hopefully, this serves as a proper reference guide or decent starting point for any developers undertaking similar projects!</p><h3>Overview</h3><p>This is a full stack Node.js project. A service called Okta is used for user authentication. The back end database is handled via MongoDB and the front end was designed with CodyHouse Framework components. PayPal smart buttons are used for checkout. All of these technologies are detailed in their own section to make it easier to skip around. I’ve also included key takeaways from designing this system from the ground up.</p><h3>Okta User Authentication</h3><p>Okta makes it simple to integrate logins into web applications and manage users from their graphical interface. I need user authentication in this project to save the items in a customer’s cart to their account and to organize order details by customer ID. I’ve included images of how I integrated Okta into my Node.js script and the routes I used to set up my web app. I mostly follow <a href="https://developer.okta.com/blog/2019/05/31/simple-auth-express-fifteen-minutes">this</a> guide as a reference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7088e8aaf9e31260a7cfb41a8d123585/href">https://medium.com/media/7088e8aaf9e31260a7cfb41a8d123585/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*CdM0kMrrv9TnCnE22oeTrQ.png" /><figcaption>You can attach several URLs to the login/logout redirects. As shown above, I still haven’t deleted my localhost and Amazon EC2 Instance URLs. The only important one to remember to change is the Initiate login URL.</figcaption></figure><h3>MongoDB Collections</h3><p>To understand this section, it is important to grasp the hierarchy of elements within MongoDB. Key-value pairs or <strong>fields </strong>can be grouped together into a single object called a <strong>document</strong>. Several <strong>documents </strong>form a <strong>collection</strong>. Several <strong>collections </strong>form a <strong>database</strong>. I have two collections in my database: one collection of Customers and one collection of Orders.</p><p>The Customer document contains the following fields: <em>oktaSub</em>, <em>oktaName</em>, and <em>oktaUsername</em>. ‘oktaSub’<em> </em>is a unique ID assigned to a user, ‘oktaName’<em> </em>is the full name of the registered user, and ‘oktaUsername’<em> </em>is the user’s email address. All three Customer fields have string values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*v2p2s2QmhMqN62J43HHqvw.png" /><figcaption>Example of Customer document.</figcaption></figure><p>When a new Order is generated, it contains the following fields: <em>oktaSub</em>, <em>S</em>, <em>M</em>, <em>L</em>, and <em>openOrder</em>. As before, ‘oktaSub’ is the user’s unique ID. ‘S’, ‘M’, and ‘L’<em> </em>take integer values that correspond to the quantity of each product size the user has added to their cart (S = small, M = medium, L = large). ‘openOrder’<em> </em>has a boolean value and corresponds to whether or not the order has been completed by determining if the final purchase order has been submitted through PayPal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*c3XhwtpQzA0okDMlzdN8cQ.png" /><figcaption>Example of an open Order document. The value of ‘S’ is 3, which means that the user currently has 3 small sweatshirts saved in his/her cart. The value of ‘openOrder’ is true, which means that the user is still shopping and has not checked out yet.</figcaption></figure><p>When a user successfully submits a payment, three additional fields are added to the Order document. These fields are <em>paypalAddress</em>, <em>paypalArea</em>, and <em>paypalName</em>. ‘paypalAddress’ and ‘paypalArea’ are two strings that form the full shipping address when combined. As the name suggests, ‘paypalName’ refers to the name registered to the PayPal account. I included this field in case it differed from the ‘oktaName’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*xKc4Ww2otmILs_XtDalDEw.png" /><figcaption>Example of a closed Order document. The value of ‘M’ is 1, which means that the user currently has 1 medium sweatshirt saved in his/her cart. The value of ‘openOrder’ is false, which means that the user has successfully checked out. Therefore, the three additional ‘paypal’ fields have been appended.</figcaption></figure><p>New Customer and Order documents are generated after a user logs in for the first time. New Order documents can also be generated after a successful checkout. Recall that this is categorized by the ‘openOrder’ field swapping values to ‘false’ and the addition of three ‘paypal’ fields.</p><h3>CodyHouse Framework Components</h3><p>Frameworks are software ‘canvases’ that more complex applications can be developed from. The CodyHouse Framework contains pre-built eCommerce components with all the necessary HTML, SCSS, and JavaScript already attached. In this project, I use the following components that you can find on their website: <a href="https://codyhouse.co/ds/components/app/product">Product</a>, <a href="https://codyhouse.co/ds/components/app/cart-drawer">Cart Drawer</a>, <a href="https://codyhouse.co/ds/components/app/dialog">Dialog</a>, <a href="https://codyhouse.co/ds/components/app/fill-loader">Fill Loader</a>, <a href="https://codyhouse.co/ds/components/app/hero">Hero</a>, <a href="https://codyhouse.co/ds/components/app/alert">Alert</a>.</p><p>For setting up the work environment, I follow <a href="https://codyhouse.co/ds/docs/framework">this</a> guide.</p><h3>PayPal Smart Buttons</h3><p>PayPal has an extensive developer API, but the simplest way to integrate payment is through JavaScript provided on the PayPal developer site. I follow their formal guide linked <a href="https://developer.paypal.com/docs/checkout/">here</a>.</p><p>Two operations are attached to the PayPal button render function. The first is ‘createOrder’, which creates a purchase order containing the amount of the transaction. The second is ‘onApprove’, which is triggered after a successful payment. Custom operations can be written and performed at this stage. In my project, I create an invisible form and attach hidden input fields containing the PayPal user’s name, address, and area. I also create a hidden submit button and click it using JavaScript to handle it in an AJAX request. The code is provided below for more clarity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb5914e44a3e3dca57aa3af22442aa71/href">https://medium.com/media/fb5914e44a3e3dca57aa3af22442aa71/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3da22d548f0b64fb53459cad943374e8/href">https://medium.com/media/3da22d548f0b64fb53459cad943374e8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65130208821c82dbcada5f40d9f55528/href">https://medium.com/media/65130208821c82dbcada5f40d9f55528/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e0f38d3b9b6e504405979e647e2a013/href">https://medium.com/media/4e0f38d3b9b6e504405979e647e2a013/href</a></iframe><h3>Key Takeaway #1: PayPal Smart Buttons are intended for non-variable purchases</h3><p>Although this is specifically outlined by PayPal, it’s a warning I decided to ignore. Originally, I chose to use smart buttons because the code was already provided and it seemed easy to integrate. As shown in a previous image in the PayPal section, a transaction value must be specified when a purchase order is created. For a set price, assigning this value is straightforward. There are some security considerations, however, for setting dynamic prices.</p><p>One of the big issues is that the transaction total cannot be obtained from the HTML DOM. DOM elements can be edited from the user side and manipulated to affect the final subtotal. Ad Blockers like uOrigin use this technique as one of their primary functions, so the intent is not always malicious but could still cause issues during checkout. My workaround was to update a global ‘subtotal’ variable after each AJAX request (more on this in Takeaway #2 if you’re interested).</p><p>I’ve purposefully held off publishing this article until after I took down live payments as I still don’t know how “hackable” this solution is. I know it’s much better than pulling the subtotal from DOM elements, but thinking about it still makes me uncomfortable. I imagine that the correct solution is to handle this mess in a Node.js route and using the PayPal developer API.</p><h3>Key Takeaway #2: Updating ‘subtotal’ from button presses instead of from an HTML &lt;div&gt;</h3><p>I alluded to this in Takeaway #1, but an overall lesson I learned is that updating information based on DOM elements is really stupid. Again, DOM elements can be manipulated from the user side. Sensitive fields should never have their value updated from an HTML element. The workaround I employed was sending an AJAX request during every button press that would affect the backend. A list of all relevant buttons is provided in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2LG41kAnj8ggjXgkksQ9w.png" /><figcaption>All AJAX buttons. (1) Obtains size selected from radio buttons. Searches Orders Collection for user and increases the quantity of the selected size. (2) Searches Order Collection for user and increases the quantity of the item size. (3) Searches Order Collection for user and decreases the quantity of the item size. (4) Searches the Order Collection for user and sets the quantity of the item size to 0. (5) Updates global ‘subtotal’ variable one last time.</figcaption></figure><h3>Key Takeaway #3: Don’t update the backend from browser cookies</h3><p>All of these takeaways follow a similar theme of <em>don’t update sensitive information from things that can be manipulated by the user</em>. Using browser cookies has the benefit of not requiring users to sign up in order to save their cart. Unfortunately, cookies can be deleted rather unintentionally when a user decides to reset their browser history. My workaround was to require users to sign in in order to save their cart. I used buttons to update a user’s cart via AJAX requests as shown in the figure in Takeaway #2. Although it’s an extra hassle for a user to register via Okta, I deemed it as a necessary inconvenience.</p><h3>Unresolved issues</h3><p>In this section, I want to provide a brief overview of some unresolved issues in this project that I’m putting on the back burner. I plan on retiring this project, but this blog wouldn’t be complete without a report of some lingering issues and improvements that could be made to help other developers.</p><p>Firstly, one issue that I struggled with and ultimately gave up on is handling failed PayPal payments. If a card is declined or the user inputs their information incorrectly, the user needs to refresh their page instead of just re-entering the information. Simply putting in their information again wouldn’t cause an error, but would “soft lock” the user from accessing the rest of the checkout process. From doing some research online, it seems that PayPal isn’t able to remember the previously opened order request session after a user fails to checkout correctly.</p><p>Another area of improvement could be replacing the “OIDC” middleware I used for setting up Okta. I haven’t done much research in this area, but I believe a more common practice is to use Passport.js instead. This would allow developers more flexibility, including the ability to send customized confirmation emails after registration.</p><h3>Concluding Remarks</h3><p>I’ve probably learned the most about each component of a full stack application in the undertaking of this project than all of my previous project and internship experience combined. Still, every summer I attempt one of these projects, it always feels like I’m barely scratching the surface. I’m looking forward to leveraging all that I’ve learned and building upon it in my next adventure. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe80c409eb67" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-an-ecommerce-store-from-scratch-fe80c409eb67">Building an Ecommerce Store from Scratch</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Generated Pugh Chart Populated from Airtable]]></title>
            <link>https://richardchung.medium.com/python-generated-pugh-chart-populated-from-airtable-978d2ecb6f19?source=rss-321ba8f10b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/978d2ecb6f19</guid>
            <category><![CDATA[airtable]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ideation]]></category>
            <dc:creator><![CDATA[Richard Chung]]></dc:creator>
            <pubDate>Tue, 16 Jul 2019 18:31:07 GMT</pubDate>
            <atom:updated>2021-01-18T17:11:54.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUcjn_sKSFH-KnzyhkSNnw.png" /></figure><p>For those that have ever started their own personal projects, I’m sure you’ve shared the familiar overwhelming feeling of having lots of unfiltered ideas about how to approach the beginning, but ambiguity regarding the most optimal path to the solution. The idea of selecting one idea among several potential ones is known to engineers as <strong>concept selection. </strong>Whether the initial collection of ideas came from mind mapping or brainstorming, we need some way to narrow down which solutions we think are most viable. One method of testing viability could be running small scale prototypes of each solution we envision and collect data on their performance. In school, one of the organizational techniques I’ve learned to analyze the collected data is the Pugh Chart (more on exactly what this is later).</p><p>I was motivated to complete this project because of how tedious I found making Pugh Charts was, especially for projects with more than 5 viable solutions. By combining Airtable, a spreadsheet-database-hybrid, with a Python script, I can easily generate neat Pugh Charts without all the hassle of performing the same monotonous calculations on my own.</p><h3>On Pugh Charts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*AhWVnOsIU2ndrAD79bjW4w.png" /><figcaption>Sample Pugh Chart for robot that lifts and transports cubes. In this, Design 1 has the highest score which represents the most viable solution.</figcaption></figure><p>Pugh charts are a visual way to organize and compare multiple designs against their functional requirements early in the design process to select one concept to proceed with. The design with the highest total represents the most viable solution. Weights can be assigned to each requirement as determined by importance. One arbitrary design is chosen to be the ‘control’ and is given a score of 0 for each requirement. Each subsequent design is compared to the control between each category and is assigned a score of +1 if it performs better than the control, -1 if it performs worse, or 0 if it performs equally well. The total is calculated by multiplying each individual cell by the weight in its row, and summing the column.</p><h3>On Airtable</h3><p>Airtable is an amazingly powerful organizational tool that packs the power of a database within an intuitive user interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUcjn_sKSFH-KnzyhkSNnw.png" /><figcaption>Sample Airtable for my student organization BLUElab Thailand.</figcaption></figure><p>Although it appears as a spreadsheet, the integration of a database allows users to return queries beyond simple strings and integers — notice in the sample how the last column includes file attachments, which is crazy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ak-MznCY5s54KLIzhaYRjA.png" /><figcaption>Sample form for my student organization BLUElab Thailand. Responses to this form will automatically populate the spreadsheet.</figcaption></figure><p>Users can easily populate the database through the format of a form. This is especially handy when out on the field, as the form fits snugly on mobile devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*6kBxkXWdVwfQ4eK6TqXGDw.png" /></figure><p>Lastly for developers, Airtable provides a remarkably well documented API.</p><p>Airtable offers so much more, and I highly encourage <a href="https://airtable.com/product">reading </a>about it yourself to make it part of your own project.</p><h3>The Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCi_FLFM5vq75Y1Zan9Xgg.gif" /></figure><p>The program prompts the user for 4 things: (1) the name of the table; (2) the names of the columns to be used as requirements; (3) the name of the solution column; and (4) the weights of each requirement.</p><p>(1) is included in this program so that users with multiple tables can generate Pugh charts for each of them.</p><p>(2) is required for filtering out each column of the table — users that have columns for ‘Attachments’ or for ‘Comments/Notes’ will most likely not need those columns for the Pugh chart.</p><p>(3) is required to access the column with each of the designs to be compared with one another.</p><p>(4) gives the user the option to add weights to each requirement. Positive values means that the user wants to maximize the requirement, while negative values means that the user wants to minimize the requirement. In the sample above, both of the weights are positive, which means that designs with higher values of ‘Times til explosion (s)’ and ‘% Barrel Filled’ are favored.</p><h4>Airtable Integration</h4><p>I used the Python wrapper found <a href="https://airtable-python-wrapper.readthedocs.io/en/master/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*B8-s1vWAC9FbVtcYP4XV4A.png" /></figure><p>For some reason, the import statement needed to be written as above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*OCI9Cv6LUl2wr5m15hkQ1w.png" /></figure><p>You can generate your own base key and API key for your workspace through Airtable’s <a href="https://airtable.com/api">app</a>. Obtaining the ‘tablename’ through user input allows for configuration across multiple tables.</p><h4>Comparison Algorithm</h4><p>TL;DR storing data as key-value pairs in a dictionary where keys are solutions and values are data for each requirement. Averages are taken for keys with more than one entry in Airtable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*yrcY0l6Ejo3Kk_JK16SHbg.png" /></figure><p>Line 112 creates the dictionary I use to store all my data. The keys represent the solutions, and the values represent the data recorded in each requirement.</p><p>Lines 114 and 116 receive user input. One is for filtering out each column of the table, and is stored in ‘accept’. The other is for obtaining solution names, which is stored in ‘solncol’.</p><p>Line 126 creates a list called ‘acceptlist’ based off of user input of columns to take as functional requirements.</p><p>Lines 128–129 appends each entry into a list called ‘categories’ that will be used in part of the display.</p><p>Line 131 begins the iteration through the Airtable. The call <em>airtable.get_all() </em>returns all the records, including their IDs and fields.</p><p>Lines 132–134 create a new list called ‘newdata’, to which we append relevant query results. 133 begins iterating through each entry in ‘acceptlist’ to query the data from Airtable. In the sample at the beginning of this section, we take the columns “Time til explosion (s)” and “% Barrel Filled”. The call <em>row[‘fields’][‘Time til explosion (s)’]</em> on 134 returns the specific data entry of the solution and appends it to ‘newdata’.</p><p>Line 135 creates a list called ‘soln’ which is a list of the solutions (obviously) which will become the keys of our dictionary.</p><p>Lines 137 and 144 are the comparison algorithm. For each new solution the program reads, we create a key-value pair with solutions as the key and a list of the data recorded in each category as the value. This is shown in lines 143–144. If the program reads a solution that we have already come across, we want to average the data in every category. This is shown in lines 138–142.</p><p>The lines above might be easier to explain using a practical example. As in the sample at the beginning of this section, the two functional requirements are “Time til explosion (s)” and “% Barrel Filled”. Let us assume that we have two solutions in our Airtable whose names are: Solution A and Solution B. We conduct two trials each of Solution A and Solution B, for a total of four trials.</p><p><strong>Trial 1, Solution A:</strong><br>Time til explosion (s) = 5; % Barrel Filled = 100<br><strong>Trial 2, Solution A:</strong><br>Time til explosion (s) = 7; % Barrel Filled = 95<br><strong>Trial 3, Solution B:<br></strong>Time til explosion (s) = 10; % Barrel Filled = 100<br><strong>Trial 4, Solution B:<br></strong>Time til explosion (s) = 8; % Barrel Filled = 90</p><p>In our dictionary, we will only have 2 key-value pairs. The keys will be Solution A and Solution B. The values will be lists of the averages of the data in each category. Visually, this can be represented as:<br>{‘Solution A’: [6, 97], ‘Solution B’: [9, 95]}</p><h4>PrettyTable</h4><blockquote><a href="https://pypi.org/project/PrettyTable/">PrettyTable </a>is a simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables.</blockquote><p>I use PrettyTable to display the Pugh Chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfmQ0qH8BkDCRVuwJO44GQ.png" /></figure><p>The leftmost column displays all the functional requirements. The upper row displays all the solutions. The bottom row displays the scores for each solution. As with a normal Pugh chart, scores are counted based off of multiplying the score in each cell with the weight of the requirement and summing the column. + signs in cells represent +1, — signs in cells represent -1, and * represent 0. In the example above, all weights are 1.</p><h3>Next Steps and Takeaways</h3><p>Parts of this code could definitely be optimized, as some Big O times are n². I also want to make this more user friendly —as of now, the program is extremely unforgiving when the user makes a typo. I should have implemented try-catch statements to alleviate this issue. I could also display all possible table names, column names, etc. before prompting the user.</p><p>I’ve always taken interest in emerging technologies, so working on a project with Airtable piqued my curiosity. I’m impressed at what Airtable has to offer for development, and I’m most certainly going to be working more closely with this tool in the future. Although this post had an extended section dedicated to explaining code, I hoped that I’ve maintained your interest enough to inspire some ideas on how you can integrate Airtable into your next project! You can find everything about this project on my <a href="https://github.com/richung99/PughPython">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=978d2ecb6f19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visual Tracker of 11 Critical Drainage Junctions in Mae Chan, Thailand]]></title>
            <link>https://richardchung.medium.com/visual-tracker-of-11-critical-drainage-junctions-in-mae-chan-thailand-729c82b040f2?source=rss-321ba8f10b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/729c82b040f2</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[google-maps-api]]></category>
            <category><![CDATA[thailand]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Richard Chung]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 20:49:20 GMT</pubDate>
            <atom:updated>2021-01-18T17:06:01.410Z</atom:updated>
            <content:encoded><![CDATA[<p>This summer, I built a web app that helps a municipality in Thailand keep track of the status of their assets while on the field. It was my first introduction to Full stack development so the code isn’t too complicated, but I wanted to share the impact that it has/could have on the community and hopefully inspire others (with or without background in CS) to go out and build something! You can find the web-app here: <a href="http://ec2-3-85-9-60.compute-1.amazonaws.com:3000/">http://ec2-3-85-9-60.compute-1.amazonaws.com:3000/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rzrz8KMpKYgEpQkrJnlp2A.gif" /></figure><h3>Introduction</h3><p>Thailand is a southeast Asian country that undergoes a monsoon season, which is categorized by perceivable changes in precipitation and wind due to asymmetric heating of the land and sea. The Mae Chan municipality, located in Northern Thailand, has identified flooding as one of the major threats towards their community due to outdated sewage infrastructure and urbanization. The effects of flooding are especially exemplified during the monsoon season, causing catastrophic consequences to property and inhibiting access to the marketplace, one source of major commerce in Mae Chan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*-KD2EpWAp2lxMyuN" /><figcaption>While the water level is low during the dry season, during monsoon season the water can quickly exceed the height of the barrier and flood onto the street.</figcaption></figure><p>While the fundamental infrastructure may not be renovated due to cost constraints, the municipality has made great strides in protecting their community. By conducting their own internal research and partnering with other universities/organizations like BLUElab Thailand, Mae Chan has managed to develop custom solutions based off of needs statements that work within their own constraints. Needs statements are statements that justify the “need” for conducting the project, and my student organization BLUElab Thailand has identified “the ability to open and close 11 critical drainage junctions” as one of these statements. The ability to open and close drainage junctions will grant the municipality the ability to control where the water within storm drains will flow by shutting off entry to certain areas, such as the market place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*PbGkwrUYEQWRMsyz" /><figcaption>One of the eleven critical drainage junctions. Solutions would be placed inside of the catch basin.</figcaption></figure><p>The purpose of this web application is to provide a visual platform on Google Maps for users to monitor the status of the 11 critical drainage junctions. Each drainage junction can be toggled on or off, and changes to a junction’s current state are immediately saved to a database. Furthermore, the application operates in real time, meaning that all users concurrently on the app can see edits made from one another instantly.</p><h3>Background</h3><p>One of the technologies implemented in this app is the Google Maps API: <a href="https://developers.google.com/maps/documentation/">https://developers.google.com/maps/documentation/</a></p><p>I use the API to display pin markers at the latitude and longitude of the 11 critical drainage points. The color of the pin marker also changes when the user clicks a button (more on the implementation of these two things in the following section).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUySioxDyQooHpGbz3R7qQ.png" /><figcaption>Using Google Maps to display red and green markers.</figcaption></figure><p>I also chose to use MongoDB as my database to store the information about latitude and longitude for each junction, as well as the state of each junction (open or closed).</p><p>This app was developed using Node.js, which according to their website is:</p><blockquote>a Javascript runtime built on Chrome’s V8 Javascript engine. As an asynchronous event driven JavaScript runtime, Node is designed to build scalable network applications.</blockquote><p>One implication of using Node.js is that the app can independently make data requests for every user, rather than having to queue up requests.</p><p>Finally, I also use Socket.io to notify all users when a change has been made to the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rzrz8KMpKYgEpQkrJnlp2A.gif" /><figcaption>Clicking ‘Save States’ will enable a (somewhat) non-intrusive popup on all devices.</figcaption></figure><p>Some Bootstrap and CSS were also used to change button styles.</p><h3>Changing Marker Colors</h3><p>Markers can switch between red and green color through button press.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BozvkYcKt_DpuiOGfWQ9OA.gif" /><figcaption>Clicking a button changes the marker with the same number to the opposite color.</figcaption></figure><p>This is done by deleting the old marker and replacing it with the opposite color. Doing so also updates the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*IyHng5cXU0cAfIEqL7Pbvg.png" /><figcaption>Placed each button in a form that runs the deleteMarker onclick. Is there a way to dynamically generate all the buttons depending on how many records are in the database? Probably; but for another time.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*z71oSxqAcl0p4P8GIgXJdw.png" /><figcaption>deleteMarker takes an integer argument which is used to identify the particular marker in the array. Afterwards, the marker is replaced depending on it’s color by calling addMarker.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHPoC2qKb_fz4mfXbhpaJA.png" /><figcaption>addMarker takes a string argument which is used to identify the color to create the marker. Blue markers on the map do not change color and represent landmarks. Red markers represent closed junctions; green markers represent open junctions. Mixed jQuery and Javascript which I think is gross (?) but works.</figcaption></figure><h3>MongoDB</h3><p>This was my first time using a database that wasn’t SQLite, which I first learned in high school (yikes). For those interested, my setup is below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAJksaFaeZAm5uohp2XAUA.png" /><figcaption>Image taken from Compass, the GUI for MongoDB. I have one collection LatLong, with 2 Documents inside.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*7-1Vo0VR9qixMGC5sRlBGw.png" /><figcaption>Separate arrays for latitude and longitude. Blurred items just in case.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*ccey50_xqZrOLYXtQT9Beg.png" /><figcaption>Array for the state of each junction: false = closed; true = open.</figcaption></figure><h3>Node.js</h3><p>This project was also my first introduction to Node.js — before this, I was still coding in PHP and HTML forms so I was really excited to try new things. Some of the highlights are featured below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNl0WXVfXWxCOl3pAtXGQg.png" /><figcaption>get and post handled in node.js; perhaps a little messy in places but a decent first try I would say.</figcaption></figure><p>From lines 50–62 (get), I’m storing the latitude, longitude, and initial states in local variables to be accessed throughout the code.</p><p>From lines 64–101 (post), I’m changing the states in my local copy of the initial states before uploading to MongoDB. Recall from two sections ago that each toggle button was placed in an HTML form with type ‘submit’. This triggers lines 64–101 to run. Line 109 refreshes the page.</p><h3>Socket.io</h3><p>Socket.io was implemented to alert all users currently residing on the app of potential changes created by another user. Currently, clicking the ‘Save States’ button will trigger a (somewhat) non-intrusive popup that lasts for 5 seconds. This lightly colored pop-up informs users of the exact time of the change, and advises the user to refresh the page to apply updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nxyf99th5yuAJGl2AYpW_Q.gif" /></figure><p>Ideally, when a user makes a change, the change should automatically be rolled out to every device connected without the user having to press the ‘Save States’ button, or refreshing the page. This is definitely an improvement that I look forward to experimenting with in the future.</p><h3>Reception and What’s Next?</h3><p>This summer, I also had the opportunity to present the project to the city council at Mae Chan. Overall, I would say that the project was received well and I look forward to continue our collaboration to improve the functionality of this application. Eventually, the municipality wants to incorporate this app in the realization of their “Smart City” — a city that is increasingly integrated with technology — so I am excited for the potential prospects of this project.</p><p>As we move into the future, I plan to reorganize my code to: (1) operate more efficiently, (2) revise oversights that may have occurred from rushing to meet deadlines, or (3) for clarity. I also want to explore combining a mechatronic component to the project; specifically, I want to try incorporating a Raspberry Pi that controls the opening/closing of the junction.</p><h3>Takeaways</h3><p>From undertaking this project, I took my first step into Full stack development. When I took a web development class for the first time during my Junior year of high school, Full stack development was already emerging yet we still learned antiquated techniques. I’ve also incorporated using a non-SQL database like MongoDB into my inventory. I’m so glad to have immersed myself into learning the basics and I anticipate learning more as time progresses.</p><p>I will say how surprised I was at how much I was able to do with so little. Starting the project felt intimidating, but I’m impressed with the range of capabilities I achieved with just surface level knowledge. This project can be so much more than it already is, and I feel motivated to continue its expansion.</p><p>I hope this project has been an interesting read or inspired you to take up your own Full stack project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=729c82b040f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>