<?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 Hitesh Sahu on Medium]]></title>
        <description><![CDATA[Stories by Hitesh Sahu on Medium]]></description>
        <link>https://medium.com/@hiteshkrsahu?source=rss-b3d604f0c461------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-YmtextrxgO1xDIV3y2j5Q.jpeg</url>
            <title>Stories by Hitesh Sahu on Medium</title>
            <link>https://medium.com/@hiteshkrsahu?source=rss-b3d604f0c461------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:33:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hiteshkrsahu/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[Installing Go on Windows: The 5-Minute Guide (and the Gotchas Nobody Mentions)]]></title>
            <link>https://hiteshkrsahu.medium.com/installing-go-on-windows-the-5-minute-guide-and-the-gotchas-nobody-mentions-878eb3ea2277?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/878eb3ea2277</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[installation]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 12:30:01 GMT</pubDate>
            <atom:updated>2026-06-26T12:30:01.030Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up Go on Windows is genuinely easy; the official installer does almost all the work. But “almost” is where people lose twenty minutes wondering why go version returns <em>&quot;command not found&quot;</em> in the terminal they already had open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vS9YSdYrDOSmfTWYp2JS3Q.png" /></figure><p>This guide gets you from zero to a working toolchain, then covers the handful of things that actually trip developers up.</p><p>As of this writing, the current stable release is <strong>Go 1.26.4</strong>.</p><h3>📟 Prefer the command line? Use a package manager</h3><p>If you’d rather not click through an installer — or you want repeatable setup across machines — any of these work:</p><pre># winget (built into modern Windows)<br>winget install GoLang.Go</pre><pre># Chocolatey<br>choco install golang</pre><pre># Scoop<br>scoop install go</pre><p>All three put go on your PATH.</p><p>Since Go 1.11+, you don’t need to set it GOPATH manually — modules work out of any directory with a go.mod. By default GOPATH is%USERPROFILE%\go, and go install</p><p><strong>Close the current terminal and open a fresh one.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Lj42PuHzkgvHi2T2QUqFQ.png" /><figcaption>Installing Go with GUI &amp; Terminal</figcaption></figure><h3>👨‍💻 Use the Installer: the MSI installer</h3><p>This is the route I’d recommend for those who are not comfortable with Terminal.</p><p>It handles PATH for you, and it is the same installer that the Go team ships.</p><ol><li>Download Installer from <a href="https://go.dev/dl/">go.dev/dl</a></li></ol><ul><li>Windows MSI version, like go1.26.4.windows-amd64.msi.</li><li>On a Windows-on-ARM machine (Surface Pro X, some Copilot+ PCs), pick the arm64 build instead.</li></ul><p>2. Run the Installer</p><p>By default, Go installs toC:\Program Files\Go, and the installer adds C:\Program Files\Go\bin to your system PATH.</p><p><strong>3. Open a new terminal</strong> and verify:</p><pre>go version</pre><p>You should see:</p><pre>go version go1.26.4 windows/amd64</pre><p>That’s it. You have a working Go toolchain.</p><h3>⚠️Gotcha #1: “I installed it, but the terminal says it’s not found”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49gAWwTw4l1qz9dK_HhIUQ.png" /></figure><p>This is the single most common stumble, and it’s not a broken install. Environment variables PATH are read when a shell starts.</p><p>If you had PowerShell or Command Prompt open <em>during</em> installation, that window never saw the new PATH.</p><blockquote><strong>Close it and open a fresh one.</strong> Ninety percent of “it didn’t work” reports are exactly this.</blockquote><h3>⚠️Gotcha #2: GOPATH is not what you think anymore</h3><p>If you learned Go years ago, you might remember a fussy ritual of setting GOPATH and keeping all your code under one sacred directory. <strong>You don&#39;t need to do that anymore.</strong></p><blockquote>Since Go 1.11, modules are the standard. You can create a project anywhere:</blockquote><pre>mkdir hello &amp;&amp; cd hello<br>go mod init example.com/hello</pre><p>…and Go figures out dependencies from the resulting go.mod. So no GOPATH gymnastics is required.</p><p>There’s still <em>one</em> place that GOPATH matters: installed tools. By default GOPATH is %USERPROFILE%\go, and go install some/tool@latest drops the binary into %USERPROFILE%\go\bin. If you want those tools available as commands, add that folder to your PATH:</p><pre># Check where they land<br>go env GOPATH</pre><pre># Add %USERPROFILE%\go\bin to your user PATH (one-time, persists)<br>[Environment]::SetEnvironmentVariable(<br>  &quot;PATH&quot;,<br>  $env:PATH + &quot;;$env:USERPROFILE\go\bin&quot;,<br>  &quot;User&quot;<br>)</pre><p>Reopen the terminal and your go install-ed tools are on tap.</p><h3>⚠️Gotcha #3: your terminal matters more than you’d expect</h3><p>Plenty of modern Go tooling, especially TUIs built with libraries like Bubble Tea and Lip Gloss, relies on truecolor and Unicode rendering that the legacy Windows console (conhost) handles poorly. Borders look broken, colors wash out, glyphs turn into boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5zbO_S4LmTmATfkYyy2Mg.png" /><figcaption>Windows Terminal rendering Terminal UI</figcaption></figure><blockquote>The fix is free: use <strong>Windows Terminal</strong>. It ships with current Windows and renders modern CLI output correctly.</blockquote><p>If you’re building or running anything with a styled terminal interface, this one change saves a lot of “why does my UI look mangled” confusion.</p><p>Example: UI for <a href="https://github.com/hiteshsahu/Squint">squint </a>showing squatting GPU with color code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9F1Ijnnm6uwu2TWB07rQA.jpeg" /></figure><h3>▶️ Bonus: running multiple Go versions side by side</h3><p>If you maintain projects pinned to different releases, you don’t have to uninstall and reinstall.</p><p>The official golang.org/dl wrappers let versions coexist:</p><pre>go install golang.org/dl/go1.25.11@latest<br>go1.25.11 download<br>go1.25.11 version</pre><p>Now go is your default and go1.25.11 is available whenever a specific project needs it.</p><h3>🔎A quick sanity check</h3><p>Confirm everything works end-to-end with the obligatory Hello World:</p><pre>mkdir hello &amp;&amp; cd hello<br>go mod init example.com/hello</pre><p>Create main.go:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>	fmt.Println(&quot;Hello from Go on Windows&quot;)<br>}</pre><p>Then:</p><pre>go run .</pre><p>If you see your message print, you’re fully set up — toolchain, modules, and run loop all working.</p><h3>📌 The 10 commands you’ll use most often</h3><blockquote>go version<br>go env<br>go get &lt;package&gt;</blockquote><blockquote>// install / tidy module dependencies<br>go mod init myapp <br>go mod tidy</blockquote><blockquote>// build &amp; run<br>go build<br>go run .</blockquote><blockquote>// test, format, lint<br>go test ./…<br>go fmt ./…<br>go vet ./…</blockquote><h3>Wrapping up</h3><p>The Go installer on Windows is about as painless as language setup gets. The real friction isn’t the install itself — it’s the stale terminal, the outdated GOPATH muscle memory, and the legacy console mangling modern output. Sidestep those three, and you&#39;ll spend your time writing Go instead of configuring it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufQykJNFiH9qm6rjNMbFSg.png" /></figure><p>Happy building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=878eb3ea2277" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up CUDA on Windows 10/11 with WSL2]]></title>
            <link>https://hiteshkrsahu.medium.com/setting-up-cuda-on-windows-10-11-with-wsl2-3f7f036c3899?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f7f036c3899</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[nvidia-cuda]]></category>
            <category><![CDATA[nvidia-driver]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 07:21:51 GMT</pubDate>
            <atom:updated>2026-06-13T07:25:31.296Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setting Up CUDA on Windows 10/11 with WSL2 — The Right Way</h3><p><em>Run GPU-accelerated workloads natively inside Linux on your Windows machine — no dual-boot required.</em></p><p>If you’ve ever wanted to run CUDA workloads, train deep learning models, or experiment with GPU computing without leaving Windows — WSL2 (Windows Subsystem for Linux 2) is your answer. As of 2021, NVIDIA made CUDA officially supported inside WSL2. That means you get a real Linux environment, real GPU access, and none of the friction of dual-booting.</p><p>This guide walks you through everything: from enabling WSL2 to running your first CUDA program inside Ubuntu on Windows.</p><p>The full code and setup scripts from this article live here: <a href="https://github.com/hiteshsahu/unparallel-parallelism">github.com/hiteshsahu/unparallel-parallelism</a> — clone it, run the setup script, and you’re compiling CUDA in under 10 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXYOynSwobBQO658Q8HiIg.png" /></figure><h3>💻What You’ll Need</h3><p>Windows or Linux machine with NVIDIA GPU. Below instruction are meant for Windows machine but you can do the same in Linux machine.</p><ul><li>Windows 10 (version 21H2 or later) or Windows 11</li><li>An NVIDIA GPU (Maxwell architecture or newer — GTX 900 series and up)</li><li>At least 8 GB RAM (16 GB recommended for ML workloads)</li><li>~15 GB free disk space</li><li>⛔ MacOS not supported by CUDA</li></ul><blockquote><strong><em>Note:</em></strong><em> CUDA via WSL2 does </em><strong><em>not</em></strong><em> support AMD or Intel GPUs. This guide is NVIDIA-only.</em></blockquote><h3>🐧 Step 1 — Enable WSL2 on Windows</h3><p>Open <strong>PowerShell as Administrator</strong> and run below command. Give username pass when asked eg: (hitesh/root)</p><pre># Install default Ubuntu<br>wsl --install<br><br># Install specific Ubuntu Destro:<br># Ubuntu 22.04 LTS, Ubuntu 24.04 LTS<br>wsl --install -d Ubuntu-22.04<br><br><br># Check available Installed Destro<br>wsl --list --verbose</pre><p>This single command installs WSL2 and Ubuntu (the default distro) in one shot on Windows 10 21H2+ and Windows 11. Restart your machine when prompted.</p><p>Lets understand a bit more abouzt WSL before going further</p><h3><strong>WSL</strong> stands for <strong>Windows Subsystem for Linux</strong>.</h3><p>It is a compatibility layer developed by <a href="https://www.microsoft.com/?utm_source=chatgpt.com">Microsoft</a> that allows you to run a Linux environment directly on Windows without dual-booting or using a traditional virtual machine.</p><p>There are two major versions:</p><ul><li><strong>WSL 1</strong>: Translates Linux system calls into Windows system calls.</li><li><strong>WSL 2</strong>: Runs a real Linux kernel inside a lightweight virtual machine, providing much better compatibility and performance.</li></ul><p>With <strong>WSL 2</strong>, you can:</p><ul><li>Run Ubuntu, Debian, Fedora, and other Linux distributions.</li><li>Use Linux tools such as bash, ssh, grep, docker, and kubectl.</li><li>Access NVIDIA GPUs for CUDA workloads.</li><li>Develop and test applications in a Linux environment while staying on Windows.</li></ul><p>Architecture (simplified):</p><pre>Windows 11<br>│<br>├── Windows Apps<br>│<br>├── WSL2<br>│   ├── Ubuntu<br>│   ├── Linux Kernel<br>│   └── Docker / CUDA / Kubernetes Tools<br>│<br>└── Hardware (CPU, GPU, Memory)</pre><p>For developers, WSL2 is often the easiest way to get a near-native Linux development environment on Windows without rebooting into a separate operating system.</p><p>Make sure WSL2 is used because WSL1 have no GPU support</p><ul><li>🐧 VERSION 2 → WSL2 (required for GPU support).</li><li>⛔ VERSION 1 → WSL1 (no GPU support).</li></ul><p>You need to make WSL &amp; installed Linux Destro point to WSL2</p><pre>wsl --set-default-version 2<br>wsl --set-version Ubuntu 2</pre><p>Verify WSL2 is active:</p><pre>wsl -l -v</pre><p>You should see VERSION 2 next to your distro. If not, repeat the --set-version command.</p><h3>🎮Step 2 — Install the NVIDIA Windows Driver (Host Side)</h3><p>This is the step most guides get wrong: <strong>you install the GPU driver on Windows, not inside WSL.</strong></p><p>WSL2 shares the Windows GPU driver through a translation layer. Installing a Linux driver inside WSL will break things.</p><ol><li>Go to <a href="https://www.nvidia.com/Download/index.aspx">https://www.nvidia.com/Download/index.aspx</a></li><li>Select your GPU model, Windows 10/11, and the latest Game Ready or Studio driver</li><li>Install it on Windows as you normally would</li></ol><p>After installation, verify the driver is visible:</p><pre>nvidia-smi</pre><p>You should see your GPU listed with the driver version. <strong>If </strong><strong>nvidia-smi works on Windows, you&#39;re ready to move inside WSL.</strong></p><pre>nvidia-smi<br><br>    // Output should look like this<br><br>    +-----------------------------------------------------------------------------------------+<br>    | NVIDIA-SMI 560.35.02              Driver Version: 560.94         CUDA Version: 12.6     |<br>    |-----------------------------------------+------------------------+----------------------+<br>    | GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |<br>    | Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |<br>    |                                         |                        |               MIG M. |<br>    |=========================================+========================+======================|<br>    Segmentation fault (core dumped)</pre><h3>Step 3 — Open Your WSL2 Ubuntu Environment</h3><p>Launch Ubuntu from the Start menu, or run:</p><pre>wsl</pre><p>You’re now inside a real Linux shell on Windows. Update the package list first:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y</pre><h3>📟Step 4 — Install the CUDA Toolkit Inside WSL</h3><p>The key here is to use NVIDIA’s <strong>WSL-Ubuntu</strong> specific CUDA packages — not the standard Linux ones. These are purpose-built for the WSL2 environment and skip installing the GPU driver (since that lives on the Windows side).</p><pre># Add the WSL-Ubuntu CUDA keyring<br>wget https://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/cuda-keyring_1.1-1_all.deb<br>sudo dpkg -i cuda-keyring_1.1-1_all.deb</pre><pre># Update and install CUDA toolkit<br>sudo apt update<br>sudo apt install -y cuda-toolkit-12-4</pre><blockquote><strong><em>Why cuda-toolkit and not cuda?</em></strong><em> The </em><em>cuda meta-package includes the driver. The </em><em>cuda-toolkit package is driver-free — exactly what we need inside WSL.</em></blockquote><p>This will take a few minutes. Once done, add CUDA to your PATH:</p><pre>echo &#39;export PATH=/usr/local/cuda/bin:$PATH&#39; &gt;&gt; ~/.bashrc<br>echo &#39;export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH&#39; &gt;&gt; ~/.bashrc<br>source ~/.bashrc</pre><h3>🔍Step 5 — Verify the Installation</h3><p>Check that nvcc (the NVIDIA CUDA compiler) is available:</p><pre>nvcc --version</pre><p>Expected output:</p><pre>nvcc: NVIDIA (R) Cuda compiler driver<br>Copyright (c) 2005-2024 NVIDIA Corporation<br>Built on ...<br>Cuda compilation tools, release 12.4, V12.4.xx</pre><p>Now verify GPU access from inside WSL:</p><pre>nvidia-smi</pre><p>You should see the <strong>same GPU</strong> listed here as you saw from Windows PowerShell. If this works, your CUDA setup is complete.</p><h3>▶️ Step 6 — Run Your First CUDA Program</h3><p>Let’s compile and run a simple CUDA Hello World to confirm end-to-end GPU compute is working.</p><p>Create a file called hello.cu:</p><pre>cat &gt; hello.cu &lt;&lt; &#39;EOF&#39;<br>#include &lt;stdio.h&gt;</pre><pre>__global__ void helloFromGPU() {<br>    printf(&quot;Hello from GPU thread %d, block %d!\n&quot;, threadIdx.x, blockIdx.x);<br>}</pre><pre>int main() {<br>    printf(&quot;Launching kernel...\n&quot;);<br>    helloFromGPU&lt;&lt;&lt;2, 4&gt;&gt;&gt;();<br>    cudaDeviceSynchronize();<br>    printf(&quot;Done.\n&quot;);<br>    return 0;<br>}<br>EOF</pre><p>Compile with nvcc:</p><pre>nvcc hello.cu -o hello<br>./hello</pre><p>Expected output:</p><pre>Launching kernel...<br>Hello from GPU thread 0, block 0!<br>Hello from GPU thread 1, block 0!<br>...<br>Done.</pre><p>If you see output from multiple threads — your GPU is fully operational inside WSL2. 🎉</p><h3>🧠 Bonus: Install cuDNN (for Deep Learning)</h3><p>If you’re planning to use PyTorch, TensorFlow, or JAX, you’ll want cuDNN — NVIDIA’s deep neural network library.</p><blockquote><em>Install the cuDNN package matching your CUDA release.</em></blockquote><pre>sudo apt install -y libcudnn9-cuda-12</pre><p>Verify it installed:</p><pre>dpkg -l | grep cudnn</pre><h3>🐍 Bonus: Install PyTorch with CUDA Support</h3><p>With the toolkit in place, installing GPU-enabled PyTorch is straightforward:</p><pre>pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124</pre><p>Quick sanity check in Python:</p><pre>import torch<br>print(torch.cuda.is_available())       # True<br>print(torch.cuda.get_device_name(0))   # Your GPU name</pre><h3>Common Issues and Fixes</h3><p><strong>nvidia-smi not found inside WSL</strong> Your Windows NVIDIA driver is too old. Update it to the latest version from NVIDIA&#39;s site. Drivers released before May 2021 don&#39;t support WSL2 GPU passthrough.</p><p><strong>nvcc not found after installation</strong> You likely skipped the PATH export step. Re-run:</p><pre>echo &#39;export PATH=/usr/local/cuda/bin:$PATH&#39; &gt;&gt; ~/.bashrc &amp;&amp; source ~/.bashrc</pre><p><strong>CUDA version mismatch errors</strong> The CUDA Toolkit version inside WSL must be <strong>equal to or lower than</strong> the CUDA version supported by your Windows driver. Check the driver’s max CUDA version with nvidia-smi on Windows (top-right corner of the output). Install a matching toolkit version if needed.</p><p><strong>WSL2 shows as VERSION 1</strong></p><pre>wsl --set-default-version 2<br>wsl --set-version &lt;DistroName&gt; 2</pre><h3>What’s Happening Under the Hood</h3><p>WSL2 runs a lightweight Linux VM using Microsoft’s hypervisor (Hyper-V). NVIDIA’s GPU-PV (GPU Paravirtualization) technology allows this VM to talk directly to the physical GPU through a special user-mode driver (libdxcore.dll on Windows ↔ libdxcore.so inside WSL). The CUDA toolkit inside WSL routes compute calls through this bridge, giving near-native GPU performance — typically within 5% of bare metal.</p><p>This is fundamentally different from older GPU virtualization approaches. You’re not sharing GPU resources through a software emulator. The GPU is there, fully available, running real CUDA code.</p><h3>Wrapping Up</h3><p>WSL2 + CUDA is genuinely one of the best developer ergonomics stories in recent years. You get the GPU power of Linux compute with the familiarity of Windows for everything else — your browser, your design tools, your email. No rebooting between environments.</p><p>From here, the path forward is wide open: Kubernetes GPU workloads, multi-GPU training with NCCL, Triton Inference Server, or containerized ML pipelines with Docker and the NVIDIA Container Toolkit (yes, Docker with GPU support works inside WSL2 too).</p><p>The hardest part is the setup. And now you’ve done it.</p><p><em>Next up: running CUDA containers, GPU-enabled Kubernetes workloads, and distributed training inside WSL2.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f7f036c3899" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insertion Sort]]></title>
            <link>https://hiteshkrsahu.medium.com/insertion-sort-7463c31f966e?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/7463c31f966e</guid>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Sun, 01 May 2022 13:24:36 GMT</pubDate>
            <atom:updated>2022-05-01T13:24:36.392Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Imagine inserting a card into its correct position in a deck of cards</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRygUHhdU3xH7D_1Huan7w.jpeg" /></figure><ul><li>Algorithmic Paradigm: Incremental Approach</li><li>Time Complexity: <strong>O(n²) </strong>because it uses 2 nested loops</li><li>Sorting In Place: Yes, no extra space is needed except for Auxiliary Space</li><li>Auxiliary Space: <strong>O(1)</strong>, 1 extra space used for swapping elements</li><li>Stable: Yes</li><li>Online: Yes</li><li>Boundary Cases: Takes maximum time to sort if elements are sorted in reverse order<br> Takes minimum time(Order of n) when elements are already sorted.</li></ul><p><strong>Uses</strong>: Insertion sort is used when the number of elements is small.<br> It can also be useful when the input array is almost sorted, eg<br> only a few elements are misplaced incomplete big array.</p><h4><em>Insertion soft make use of Swap function</em></h4><p>Just remember swapping B to C in order of A&lt;-B, B&lt;-C, C&lt;-A where A is the temp variable</p><pre>// Swap nth element to n-1 element<br>const swap = (input, n) =&gt; {<br>    // put n in temp<br>    let temp = input[n]<br>    // put n -1 in n<br>    input[n] = input[n - 1];<br>    //put temp in n-1<br>    input[n - 1] = temp;<br>}</pre><p>Simplified algorithm for insertion sort</p><pre>const insertionSort = (input) =&gt; {<br><br>    // start from bottom of deck<br>    for (let i = 1; i &lt; input.length; i++) {<br><br>    <strong> // going top to bottom in sub deck of cards below <br>      for (let j = i; j &gt; 0; j--) {<br><br>      //Arrange deck by swaping and moving bigger card to the top<br>            if (input[j - 1] &gt; input[j]) {<br>                swap( input, j);<br>            }<br>        }</strong><br>    }<br>    <strong><em>console</em></strong>.log(&quot;InsertionSort Output &quot; + input);<br>};</pre><p>Optimied Insetion sort</p><pre>const insertionSortOptimize = (input) =&gt; {</pre><pre>    // start from bottom of deck<br>    for (let i = 1; i &lt; input.length; i++) {</pre><pre>   <strong>  // going top to bottom in sub deck of cards below<br>        for (let j = i; j &gt; 0 &amp;&amp; input[j - 1] &gt; input[j]; j--) {</strong></pre><pre><strong>        //Swap card with current card if it&#39;s bigger         <br>         swap(input, j);<br>        }</strong><br>    }<br>    <em>console</em>.log(&quot;insertionSortOptimize Output &quot; + input);<br>};</pre><p>Same can be achieved using a While loop</p><pre>const insertionSort2 = (input) =&gt; {<br>    for (let i = 1; i &lt; input.length; i++) {<br>        let curr = input[i];</pre><pre>       <strong> let j = i - 1;<br>        /* Move elements of arr[0..i-1], that are<br>          greater than curr, to one position ahead<br>          of their current position */</strong><br>     <strong>   while (j &gt;= 0 &amp;&amp; input[j] &gt; curr) {<br>            input[j + 1] = input[j];<br>            j -= 1;<br>        }</strong><br>        input[j + 1] = curr;<br>    }<br>    <em>console</em>.log(&quot;InsertionSort2 Output &quot; + input);<br>};</pre><p>Last but not least Testing</p><pre>describe(&#39;Insertion Sort&#39;, () =&gt; {<br>    it(&quot;insertionSort&quot;, () =&gt; {<br>        let input = [2, -1, 1, 1, -3, 5, 4];<br>        let output = [-3, -1, 1, 1, 2, 4, 5]<br>        Performance.<em>start</em>();<br>        insertionSort(input)<br>        expect(input).toStrictEqual(output)<br>        Performance.<em>stop</em>(&quot;insertionSortTest&quot;);<br>    })<br><br>    it(&quot;insertionSort Optimize&quot;, () =&gt; {<br>        let input = [2, -1, 1, 1, -3, 5, 4];<br>        let output = [-3, -1, 1, 1, 2, 4, 5]<br>        Performance.<em>start</em>();<br>        insertionSortOptimize(input)<br>        expect(input).toStrictEqual(output)<br>        Performance.<em>stop</em>(&quot;insertionSortOptimize&quot;);<br>    })<br><br>    it(&quot;insertionSort While Loop&quot;, () =&gt; {<br>        let input = [2, -1, 1, 1, -3, 5, 4];<br>        let output = [-3, -1, 1, 1, 2, 4, 5]<br>        Performance.<em>start</em>();<br>        insertionSort2(input)<br>        expect(input).toStrictEqual(output)<br>        Performance.<em>stop</em>(&quot;insertionSort2 &quot;);<br>    })<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7463c31f966e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Ways to Animate Translation of View]]></title>
            <link>https://hiteshkrsahu.medium.com/3-ways-to-animate-translation-of-view-4ebc208c3d12?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ebc208c3d12</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Wed, 15 Sep 2021 19:17:46 GMT</pubDate>
            <atom:updated>2021-09-15T19:17:46.065Z</atom:updated>
            <content:encoded><![CDATA[<p>Sharing a class for showcasing the ways one can animate Translation of View</p><pre>class AnimationCreator {<br><br>    private val defaultAnimationInterpolator: Interpolator = EaseOutExpInterpolator()<br><br>    fun translateView(viewToAnimate: View, finalState: ViewBound) {<br><br>        // Animate View directly<br>        viewToAnimate.animate()<br>            .x(finalState.positionX)<br>            .setDuration(600L)<br>            .setInterpolator(defaultAnimationInterpolator)<br>            .start()<br><br>        // Object Animator<br>        ObjectAnimator.ofFloat(<br>            viewToAnimate,<br>            View.<em>X</em>,<br>            finalState.positionX<br>        ).<em>apply </em><strong>{<br>            </strong><em>duration </em>= 600<br>            <em>interpolator </em>= defaultAnimationInterpolator<br>        <strong>}</strong>.start()<br><br>        <br>        // Value Animator<br>        ValueAnimator.ofFloat(viewToAnimate.<em>x</em>, finalState.positionX).<em>apply </em><strong>{<br>            </strong><em>duration </em>= 2000<br>            <em>interpolator </em>= defaultAnimationInterpolator<br>            addUpdateListener <strong>{<br>                </strong>viewToAnimate.<em>x </em>= <strong>it</strong>.<em>animatedValue </em>as Float<br>            <strong>}<br>            </strong>start()<br>        <strong>}<br>    </strong>}<br><br>    fun resizeView(viewToAnimate: View, finalState: ViewBound) {<br>        ValueAnimator.ofInt(viewToAnimate.<em>width</em>, finalState.size.width).<em>apply </em><strong>{<br>            </strong><em>duration </em>= 2000L<br>            <em>startDelay </em>= 0<br>            <em>interpolator </em>= defaultAnimationInterpolator<br>            addUpdateListener <strong>{<br>                </strong>val animatedValue = <strong>it</strong>.<em>animatedValue </em>as Int<br>                val layoutParams = viewToAnimate.<em>layoutParams<br>                </em>layoutParams.width = animatedValue<br>                viewToAnimate.<em>layoutParams </em>= layoutParams<br>            <strong>}<br>            </strong>start()<br>        <strong>}<br>    </strong>}<br><br><br>    private fun animateWidthTo(view: View, width: Int) {<br>        val currentWidth = view.<em>width<br>        </em>val animator = ObjectAnimator.ofInt(view, WidthProperty(), currentWidth, width)<br>        animator.<em>duration </em>= 1000<br>        animator.<em>interpolator </em>= DecelerateInterpolator()<br>        animator.start()<br>    }<br><br>    class EaseOutExpInterpolator : Interpolator {<br>        override fun getInterpolation(x: Float): Float {<br>            return if (x == 1f) 1f else (1 - Math.pow(2.0, -10 * x.toDouble())).toFloat()<br>        }<br>    }<br><br>    internal class WidthProperty :<br>        Property&lt;View, Int&gt;(Int::class.<em>java</em>, &quot;width&quot;) {<br>        override fun get(view: View): Int {<br>            return view.<em>height<br>        </em>}<br><br>        override fun set(view: View, value: Int) {<br>            view.<em>layoutParams</em>.width = value<br>            view.<em>layoutParams </em>= view.<em>layoutParams<br>        </em>}<br>    }<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ebc208c3d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Many time we want to Test  if a Icon or Image in a ImageView is same as we want to show using…]]></title>
            <link>https://hiteshkrsahu.medium.com/many-time-we-want-to-test-if-a-icon-or-image-in-a-imageview-is-same-as-we-want-to-show-using-4b5676595aee?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b5676595aee</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[espresso]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Thu, 22 Apr 2021 08:37:11 GMT</pubDate>
            <atom:updated>2021-04-22T08:37:37.674Z</atom:updated>
            <content:encoded><![CDATA[<h4>Many time we want to check if a Icon or Image is in a ImageView is same as we want to show using Espresso</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*tNNkpjVao80DG3bm17XOHA.gif" /></figure><p>You can do so with the help of a custom Matcher.</p><p>In your test class case:</p><pre><em><br>// Checks View with Correct Icon is Visible<br></em>private fun checkIconIsShown(imageIcon: Int) {<br>    onView(<br>            Matchers.allOf(<br>                    isDescendantOfA(withId(R.id.user_<em>profile</em>)),<br>                    withId(R.id.<em>user_avatar</em>),<br>                    DrawableMatcher(imageIcon))<br>    ).check(ViewAssertions.matches(isDisplayed()))<br>}</pre><p>In Matcher Class you basically compare Bitmap for the drawable you want to test with the Bitmap from Drawable from ImageView you want to test. So basically we compare Images BitMap generated from 2 sources and expect them to be same</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*GPuW5Xw0Kb4bS-PzQmL1SQ.gif" /></figure><pre><em><br>/**<br> * Matches Drawable in ImageView is Same as expectedImageResource Image Resource Provided<br> */<br></em>class DrawableMatcher(private val expectedImageResource: Int) : TypeSafeMatcher&lt;View&gt;(View::class.<em>java</em>) {<br>    override fun matchesSafely(targetImageView: View): Boolean {<br>        if (targetImageView !is ImageView) {<br>            return false<br>        }<br>        if (expectedImageResource &lt; 0) {<br>            return targetImageView.<em>drawable </em>== null<br>        }<br>        val expectedDrawable = ContextCompat<br>                .getDrawable(targetImageView.getContext(),<br>                        expectedImageResource)<br>                ?: return false<br>        val bitmap = getBitmap(targetImageView.<em>drawable</em>)<br>        val otherBitmap = getBitmap(expectedDrawable)<br>        return compareBitMap(bitmap, otherBitmap)<br>    }<br><br>    private fun compareBitMap(bitmap: Bitmap, otherBitmap: Bitmap): Boolean {<br>        val bitMapAreSame = bitmap.sameAs(otherBitmap) &amp;&amp;<br>                (bitmap.<em>width </em>== otherBitmap.<em>width </em>&amp;&amp;<br>                        bitmap.<em>width </em>== otherBitmap.<em>width </em>&amp;&amp;<br>                        bitmap.<em>height </em>== otherBitmap.<em>height </em>&amp;&amp;<br>                        bitmap.<em>byteCount </em>== otherBitmap.<em>byteCount </em>&amp;&amp;<br>                        bitmap.<em>density </em>== otherBitmap.<em>density</em>)<br>        bitmap.recycle()<br>        otherBitmap.recycle()<br>        return bitMapAreSame<br>    }<br><br>    private fun getBitmap(drawable: Drawable): Bitmap {<br>        val bitmap = Bitmap.createBitmap(drawable.<em>intrinsicWidth</em>,<br>                drawable.<em>intrinsicHeight</em>, Bitmap.Config.<em>ARGB_8888</em>)<br>        val canvas = Canvas(bitmap)<br>        drawable.setBounds(0, 0, canvas.<em>width</em>, canvas.<em>height</em>)<br>        drawable.setTint(Color.<em>TRANSPARENT</em>)<br>        drawable.draw(canvas)<br>        return bitmap<br>    }<br><br>    override fun describeTo(description: Description) {}<br>}</pre><p>That’s all folks Happy Testing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*loMH_6zMtJ7m9lw--3D_yA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b5676595aee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Repeating Task Using Coroutine]]></title>
            <link>https://hiteshkrsahu.medium.com/create-a-repeating-task-using-coroutine-e494ebae65c2?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/e494ebae65c2</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[coroutinescope]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 08:24:47 GMT</pubDate>
            <atom:updated>2021-03-10T08:24:47.057Z</atom:updated>
            <content:encoded><![CDATA[<h3>Example of how to create repeating Task using Kotlin Coroutine</h3><p>add Coroutine in Build.gradle</p><blockquote><strong>implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2’</strong></blockquote><h4>To create a repeating Job</h4><pre><em>/**<br> * start Job<br> * val job = startRepeatingJob()<br> * cancels the job and waits for its completion<br> * job.cancelAndJoin()<br> * Params<br> * timeInterval: time milliSeconds between next Tick<br> */<br></em>private fun startRepeatingJob(timeInterval: Long): Job {<br>    return <em>CoroutineScope</em>(Dispatchers.Default).<em>launch </em><strong>{<br>        </strong>while (NonCancellable.isActive) {<br>            <br>            //repeate Task Here</pre><pre>            delay(timeInterval)<br>        }<br>    <strong>}<br></strong>}</pre><p>To start Job:</p><pre>Job repeatJob = startRepeatingJob(1000L)</pre><p>To Stop Job:</p><pre>secondTickJob.cancel()</pre><h3>Same approach using Handlers</h3><pre>repeateTaskkHandler = Handler()<br>taskRunnable= <em>Runnable </em><strong>{<br>   </strong>//repeate Task Here</pre><pre>repeateTaskkHandler?.postAtTime(taskRunnable, interval)<br><strong>}<br></strong>taskRunnable.run()</pre><p>Stop:</p><pre>if (secondClockHandler != null) {<br>    repeateTaskkHandler?.removeCallbacks(taskRunnable)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e494ebae65c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programmatically Change Brightness In Android Devices]]></title>
            <link>https://hiteshkrsahu.medium.com/programmatically-change-brightness-in-android-devices-126b31c58939?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/126b31c58939</guid>
            <category><![CDATA[settings]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[brightness]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 20:10:15 GMT</pubDate>
            <atom:updated>2021-06-11T09:12:57.051Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to change brightness level in UI as well as reflect it on System level.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8OTdxCCiK0z8xX9a63UcJg.jpeg" /></figure><p><strong>Add Write setting permission in Android Manifest</strong></p><pre>&lt;uses-permission android:name=&quot;android.permission.WRITE_SETTINGS&quot;<br>        tools:ignore=&quot;ProtectedPermissions&quot;/&gt;</pre><p><strong>Write Settings is a Protected settings so request user to allow Writing System settings:</strong></p><pre>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {<br>            if (!Settings.System.canWrite(this)) {<br>                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);<br>                intent.setData(Uri.parse(&quot;package:&quot; + getPackageName()));<br>                startActivity(intent);<br>            }<br>        }</pre><p>If your app is signed with system certificates than your app will have this permissions by default.</p><p><strong>Now you can set Brightness easily</strong></p><pre>Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);</pre><p>brighness value should be in range of 0-255 so if you have a slider with range (0-max) than you can normalize the value in range of (0-255)</p><pre>private float normalize(float x, float inMin, float inMax, float outMin, float outMax) {<br>    float outRange = outMax - outMin;<br>    float inRange  = inMax - inMin;<br>  return (x - inMin) *outRange / inRange + outMin;<br>}</pre><p>Finally you can now change range of 0–100% slider to 0–255 like this</p><pre>float brightness = normalize(progress, 0, 100, 0.0f, 255.0f);</pre><p>Hope it will save someone’s time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=126b31c58939" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using ES6 in Node JS Server]]></title>
            <link>https://hiteshkrsahu.medium.com/using-es6-in-node-js-server-eba548f013b3?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/eba548f013b3</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 10:01:34 GMT</pubDate>
            <atom:updated>2020-10-20T10:01:34.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to setup Node JS Server with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">ES6</a>, <a href="https://babeljs.io/docs/en/">Babel</a>, &amp; <a href="https://www.npmjs.com/package/nodemon">Nodemon</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXsbsNEpdLnU8zL0T-gWiA.png" /></figure><p>At the end of this tutorial you will be able to use ES6 syntax to write your Node Server</p><pre>    import NodeServer from &quot;./server/NodeServer&quot;<br>    import ExpressServer from &quot;./server/ExpressServer&quot;<br>    import dotenv from &quot;dotenv&quot;<br>    dotenv.config()</pre><pre>    // Start Node Server<br>    const WebServer = new NodeServer();</pre><pre>    //Start Express JS Server<br>    const expressServer = new ExpressServer();</pre><h3>TLDR; See the final project</h3><h4>Fork the Project : <a href="https://github.com/hiteshsahu/Node-JS-ES6">https://github.com/hiteshsahu/Node-JS-ES6</a></h4><h3>Build Steps</h3><p>Install Node js and validate if <a href="https://nodejs.org/en/download/">Node JS</a> is installed properly<br><em>node -v</em></p><p>Create project directory and initialize Node package<br><em>mkdir nodeapp &amp;&amp; cd nodeapp &amp;&amp; npm init -y</em></p><p>Create a src folder in your project&#39;s root directory to keep server code.<br><em>mkdir src</em></p><p>Create Index.js in src folder as starting point for Server</p><h3>Set up Babel for precompiling ES6 into JavaScript</h3><blockquote>Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.</blockquote><p>Install <a href="https://babeljs.io/setup#installation">Babel</a></p><p><em>npm install --save-dev @babel/core @babel/cli</em></p><p>Install <a href="https://babeljs.io/docs/en/presets">Babel Preset</a> &amp; <a href="https://babeljs.io/docs/en/babel-plugin-proposal-class-properties">Class Properties Plugin</a></p><p><em>npm install @babel/preset-env --save-dev<br></em><em>npm install --save-dev @babel/plugin-proposal-class-properties</em></p><blockquote><strong>@babel/preset-env</strong> Allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!</blockquote><blockquote><strong>@babel/plugin-proposal-class-properties</strong> transform ES6 class synthecic sugar into JavaScript __Prototype__</blockquote><p>Create .babelrc file in your project&#39;s root directory &amp; add the following code in .babelrc</p><p>{ <br> &quot;presets&quot;: [&quot;@babel/preset-env&quot;], <br> &quot;plugins&quot;: [&quot;@babel/plugin-proposal-class-properties&quot;] <br> }</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*7fF0JYC0jvmhsktfhwb6XQ.jpeg" /></figure><h3>Watch File change with Node Monitor</h3><p>Install <a href="https://www.npmjs.com/package/nodemon">Nodemon</a><br><em>npm i -d nodemon<br></em><em>npm install rimraf --save-dev</em></p><p><em>Nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.</em></p><p>Update package.json by adding following line for precompiling ES6 and allowing nodemon to restart server when file changes</p><pre>&quot;scripts&quot;: {<br>+ &quot;build&quot;: &quot;babel src -d dist&quot;<br>+ &quot;start&quot;: &quot;npm run build &amp;&amp; node dist&quot;,<br>+ &quot;restart&quot;: &quot;rimraf dist &amp;&amp; npm run start&quot;,<br>+ &quot;dev&quot;: &quot;nodemon --exec npm run restart&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*Psux0IpMEynXbzVnqP_gTw.png" /></figure><p>Create nodemon.json file in your project&#39;s root directory. <br>Add src folder in watchlist by adding following code in nodemon.json<br>{&quot;watch&quot;: [&quot;src&quot;]}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*sP3KCfO6zkbdoGsQ4srFqA.png" /></figure><h3>Now You Can write Your Server in ES6 Syntax</h3><p>Here are examples of writing Node Server using Express JS and plain Node JS</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff55ddd3c27aa90ace5365e8acc32ad/href">https://medium.com/media/0ff55ddd3c27aa90ace5365e8acc32ad/href</a></iframe><h3>Finally Run the project</h3><blockquote><em>npm run dev</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eba548f013b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Vertical SeekBar in Android Without External Library(Kotin+AndroidX)]]></title>
            <link>https://hiteshkrsahu.medium.com/how-to-create-vertical-seekbar-in-android-without-external-library-kotin-androidx-2ed84788e3e1?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ed84788e3e1</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ux-design]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Fri, 07 Aug 2020 13:37:45 GMT</pubDate>
            <atom:updated>2020-08-07T13:37:45.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IaHFM6aXFLu8h3nKFdMnA.jpeg" /></figure><p>Many times we want to show a vertical progress bar for example when you are creating a Audio Equalizer or you want to show Volume Bars like One Plus 8</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASWbrhyr5dXt-IqUNWUvrA.jpeg" /></figure><h3>Add this class in your project:</h3><ul><li>First trick it does is it rotates the canvas of Android SeekBar anticlockwise -90 degrees.</li><li>Second trick it does is it set progress based on touch position.</li></ul><blockquote>Progress = MaxProgress-(TouchY/Height)*MaxProgress</blockquote><pre><strong>import </strong>android.annotation.SuppressLint<br><strong>import </strong>android.content.Context<br><strong>import </strong>android.graphics.Canvas<br><strong>import </strong>android.util.AttributeSet<br><strong>import </strong>android.view.MotionEvent<br><strong>import </strong>androidx.appcompat.widget.AppCompatSeekBar<br><strong>import </strong>androidx.core.content.ContextCompat<br><br><em>/**<br> * Vertical Progress Bar For Android Apps<br> */<br></em><strong>class </strong>VerticalSeekBar : AppCompatSeekBar {<br>    <br>    <strong>constructor</strong>(context: Context) : <strong>super</strong>(context) {<br>        initView(context)<br>    }<br>    <strong>constructor</strong>(<br>        context: Context,<br>        attrs: AttributeSet?,<br>        defStyle: Int) : <strong>super</strong>(context, attrs, defStyle) {<br>        initView(context)<br>    }<br>    <strong>constructor</strong>(<br>        context: Context,<br>        attrs: AttributeSet?) : <strong>super</strong>(context, attrs) {<br>        initView(context)<br>    }<br><br>    <strong>private fun </strong>initView(context: Context) {<br>        <em>// Set Custom Progress Bar Drawable<br>        progressDrawable </em>= ContextCompat.getDrawable(context, R.drawable.<em>vertical_progress_selector</em>)<br>        <em>// Set Custom Thumb<br>        thumb </em>= ContextCompat.getDrawable(context, R.drawable.<em>vertical_progress_thumb</em>)<br>    }<br><br>    <strong>override fun </strong>onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int{<br>        <strong>super</strong>.onSizeChanged(h, w, oldh, oldw)<br>    }<br><br>    @Synchronized<br>    <strong>override fun </strong>onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {<br>        <strong>super</strong>.onMeasure(heightMeasureSpec, widthMeasureSpec)<br>        setMeasuredDimension(<em>measuredHeight</em>, <em>measuredWidth</em>)<br>    }<br><br>    <strong>override fun </strong>onDraw(c: Canvas) {<br>        c.rotate(-90f)<br>        c.translate(-<em>height</em>.toFloat(), 0f)<br>        <strong>super</strong>.onDraw(c)<br>    }<br><br>    @SuppressLint(<strong>&quot;ClickableViewAccessibility&quot;</strong>)<br>    <strong>override fun </strong>onTouchEvent(event: MotionEvent): Boolean {<br>        <strong>if </strong>(!<em>isEnabled</em>) {<br>            <strong>return false<br>        </strong>}<br>        <strong>when </strong>(event.<em>action</em>) {<br>            MotionEvent.<em>ACTION_DOWN</em>, MotionEvent.<em>ACTION_MOVE</em>, MotionEvent.<em>ACTION_UP </em>-&gt; {<br>                <em>progress </em>= <em>max </em>- (<em>max </em>* event.<em>y </em>/ <em>height</em>).toInt()<br>                onSizeChanged(<em>width</em>, <em>height</em>, 0, 0)<br>            }<br>            MotionEvent.<em>ACTION_CANCEL </em>-&gt; {<br>            }<br>        }<br>        <strong>return true<br>    </strong>}<br>}</pre><h3>Create Custom Thumb &amp; Progress for SeekBar</h3><p>Add this <strong><em>vertical_progress_thumb.xml </em></strong>in drawable-nodpi<br>This will draw a white(#ffffff) rectangle which we will use as Thumb for SeekBar. You can customize it as you like.</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</strong>&gt;<br>    &lt;<strong>item</strong>&gt;<br>        &lt;<strong>shape android:shape=&quot;rectangle&quot;</strong>&gt;<br>            &lt;<strong>solid android:color=&quot;@color/white&quot;</strong>/&gt;<br>            &lt;<strong>size<br>                android:width=&quot;50dp&quot;<br>                android:height=&quot;52dp&quot;</strong>/&gt;<br>        &lt;/<strong>shape</strong>&gt;<br>    &lt;/<strong>item</strong>&gt;<br>&lt;/<strong>layer-list</strong>&gt;</pre><p>Next add <strong><em>vertical_progress_selector.xml </em></strong>in drawable-nodpi</p><p>This drawable define how the background and Progress of Seek Bar should look like.</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; </strong>&gt;<br>    &lt;<strong>item<br>        android:id=&quot;@android:id/background&quot;<br>        android:drawable=&quot;@drawable/background_fill&quot;</strong>/&gt;</pre><pre>    &lt;<strong>item android:id=&quot;@android:id/progress&quot;</strong>&gt;<br>        &lt;<strong>clip android:drawable=&quot;@drawable/progress_fill&quot; </strong>/&gt;<br>    &lt;/<strong>item</strong>&gt;<br><br>&lt;/<strong>layer-list</strong>&gt;</pre><p>Add <strong><em>background_fill.xml. </em></strong>This drawable define for SeekBar background. Here it is another simple Rectangle but with grey color(#<strong>888888)</strong></p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</strong>&gt;<br>    &lt;<strong>item<br>        android:bottom=&quot;6dp&quot;<br>        android:left=&quot;-6dp&quot;<br>        android:right=&quot;-6dp&quot;<br>        android:top=&quot;6dp&quot;</strong>&gt;<br><br>        &lt;<strong>shape android:shape=&quot;rectangle&quot;</strong>&gt;<br>            &lt;<strong>solid android:color=&quot;#888888&quot; </strong>/&gt;<br>            &lt;<strong>stroke<br>                android:width=&quot;5dp&quot;<br>                android:color=&quot;@android:color/transparent&quot; </strong>/&gt;<br>        &lt;/<strong>shape</strong>&gt;<br>    &lt;/<strong>item</strong>&gt;<br>&lt;/<strong>layer-list</strong>&gt;</pre><p><strong><em>progress_fill.xml </em></strong>defines how progress will look like. This is another Rectangle but with Linear Gradient Filled.</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</strong>&gt;<br>    &lt;<strong>item<br>        android:bottom=&quot;6dp&quot;<br>        android:left=&quot;-6dp&quot;<br>        android:right=&quot;-6dp&quot;<br>        android:top=&quot;6dp&quot;</strong>&gt;<br><br>        &lt;<strong>shape android:shape=&quot;rectangle&quot;</strong>&gt;<br>            &lt;<strong>solid android:color=&quot;@color/white&quot; </strong>/&gt;<br>            &lt;<strong>stroke<br>                android:width=&quot;1dp&quot;<br>                android:color=&quot;@android:color/transparent&quot; </strong>/&gt;<br><br>            &lt;<strong>gradient<br>                android:angle=&quot;90&quot;<br>                android:endColor=&quot;#ffffff&quot;<br>                android:startColor=&quot;#aeaeae&quot;<br>                android:type=&quot;linear&quot; </strong>/&gt;<br>        &lt;/<strong>shape</strong>&gt;<br>    &lt;/<strong>item</strong>&gt;<br>&lt;/<strong>layer-list</strong>&gt;</pre><h3>Usage</h3><p>After this simply add Verical Seekbar just like any normal SeekBar this</p><pre>&lt;<strong>com.example.demo.VerticalSeekBar<br>   android:id=&quot;@+id/audioSeekBar&quot;<br>   android:layout_width=&quot;120dp&quot;<br>   android:layout_gravity=&quot;center&quot;<br>   android:layout_height=&quot;698dp&quot;<br>   android:progress=&quot;30&quot;<br>   android:max=&quot;100&quot;<br>  </strong>/&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/69/1*S9081r2N262QatHuk2tu-Q.png" /></figure><p>Now you can modify it as you see it fits. Please hit the clap button. That help me keep motivated to share my knowledge and write new Story</p><p>With that my friend. Hopefully, I have covered everything that is needed for you to create a vertical seek bar. Feel free to drop in comments if you still have some questions, I will be happy to help.</p><p>Also, if you find any grammatical mistakes in the post, please point it out so I can improvise. It will be highly appreciated. You can see my work in my web links:</p><p>Lab: <a href="https://hiteshsahu.com/">https://hiteshsahu.com/</a><br>Tweeter: <a href="https://twitter.com/HiteshSahu_">https://twitter.com/HiteshSahu_</a><br>GitHub: <a href="https://github.com/hiteshsahu">https://github.com/hiteshsahu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ed84788e3e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Address of Android Device Using Kotlin Coroutine]]></title>
            <link>https://hiteshkrsahu.medium.com/get-address-of-android-device-using-kotlin-coroutine-14ec19b67a97?source=rss-b3d604f0c461------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ec19b67a97</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[automotive]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Hitesh Sahu]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 11:11:20 GMT</pubDate>
            <atom:updated>2021-03-17T19:05:51.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPYB6xMsghXbdc4cpvRUmQ.jpeg" /></figure><h3>Using Kotlin Coroutine to get Lat, lang &amp; Address of the Device</h3><p>This is an old question and most answers are outdated. This is how you do it now:</p><p><strong>This class help to track the device location and return list of Address of device using Geocoding. Put it in some util package</strong></p><pre>import android.Manifest<br>import android.app.AlertDialog<br>import android.content.Context<br>import android.content.Intent<br>import android.content.pm.PackageManager<br>import android.location.*<br>import android.os.Bundle<br>import android.provider.Settings<br>import android.util.Log<br>import androidx.core.app.ActivityCompat<br>import kotlinx.coroutines.*<br>import java.io.IOException<br>import java.lang.ref.WeakReference<br>import java.util.*<br>import kotlin.coroutines.CoroutineContext</pre><pre>/**<br> * Use GPS or Network Provider to get device Location<br> */<br>class DeviceLocationTracker(context: Context, deviceLocationListener: DeviceLocationListener) : LocationListener, CoroutineScope {<br>    private var deviceLocation: Location? = null<br>    private val context: WeakReference&lt;Context&gt;<br>    private var locationManager: LocationManager? = null<br>    private var deviceLocationListener: DeviceLocationListener<br>    private val job = Job()<br>    override val coroutineContext: CoroutineContext<br>        get() = job + Dispatchers.Main</pre><pre>    init {<br>        this.context = WeakReference(context)<br>        this.deviceLocationListener = deviceLocationListener<br>        initializeLocationProviders()<br>    }</pre><pre>    private fun initializeLocationProviders() {<br>        //Init Location Manger if not already initialized<br>        if (null == locationManager) {<br>            locationManager = context.get()<br>                    ?.getSystemService(Context.LOCATION_SERVICE) as LocationManager<br>        }<br>        locationManager?.apply {<br>            // flag for GPS status<br>            val isGPSEnabled = isProviderEnabled(LocationManager.GPS_PROVIDER)</pre><pre>            // flag for network status<br>            val isNetworkEnabled = isProviderEnabled(LocationManager.PASSIVE_PROVIDER)</pre><pre>            //If we have permission<br>            if (ActivityCompat.checkSelfPermission(context.get()!!, Manifest.permission.ACCESS_FINE_LOCATION)<br>                    == PackageManager.PERMISSION_GRANTED &amp;&amp;<br>                    ActivityCompat.checkSelfPermission(context.get()!!, Manifest.permission.ACCESS_COARSE_LOCATION)<br>                    == PackageManager.PERMISSION_GRANTED) {</pre><pre>                //First Try GPS<br>                if (isGPSEnabled) {<br>                    requestLocationUpdates(<br>                            LocationManager.GPS_PROVIDER,<br>                            UPDATE_FREQUENCY_TIME,<br>                            UPDATE_FREQUENCY_DISTANCE.toFloat(), this@DeviceLocationTracker)<br>                    deviceLocation = locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)<br>                } else {<br>                    // Show alert to open GPS<br>                    context.get()?.apply {<br>                        AlertDialog.Builder(this)<br>                                .setTitle(getString(R.string.title_enable_gps))<br>                                .setMessage(getString(R.string.desc_enable_gps))<br>                                .setPositiveButton(getString(R.string.btn_settings)<br>                                ) { dialog, which -&gt;<br>                                    val intent = Intent(<br>                                            Settings.ACTION_LOCATION_SOURCE_SETTINGS)<br>                                    startActivity(intent)<br>                                }.setNegativeButton(getString(R.string.btn_cancel))<br>                                { dialog, which -&gt; dialog.cancel() }.show()<br>                    }<br>                }</pre><pre>                //If failed try using NetworkManger<br>                if(null==deviceLocation &amp;&amp; isNetworkEnabled) {<br>                    requestLocationUpdates(<br>                            LocationManager.PASSIVE_PROVIDER,<br>                            0, 0f,<br>                            this@DeviceLocationTracker)<br>                    deviceLocation = locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)<br>                }<br>            }<br>        }<br>    }</pre><pre>    /**<br>     * Stop using GPS listener<br>     * Must call this function to stop using GPS<br>     */<br>    fun stopUpdate() {<br>        if (locationManager != null) {<br>            locationManager!!.removeUpdates(this@DeviceLocationTracker)<br>        }<br>    }</pre><pre>override fun onLocationChanged(newDeviceLocation: Location) {<br>        deviceLocation = newDeviceLocation<br>        launch(Dispatchers.Main) {<br>            withContext(Dispatchers.IO) {<br>                var addressList: List&lt;Address?&gt;? = null<br>                try {<br>                    addressList = Geocoder(context.get(),<br>                            Locale.ENGLISH).getFromLocation(<br>                            newDeviceLocation.latitude,<br>                            newDeviceLocation.longitude,<br>                            1)<br>                    deviceLocationListener.onDeviceLocationChanged(addressList)<br>                    Log.i(TAG, &quot;Fetch address list&quot;+addressList)</pre><pre>                } catch (e: IOException) {<br>                    Log.e(TAG, &quot;Failed Fetched Address List&quot;)<br>                }<br>            }<br>        }<br>    }</pre><pre>    override fun onProviderDisabled(provider: String) {}<br>    override fun onProviderEnabled(provider: String) {}<br>    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}<br>    interface DeviceLocationListener {<br>        fun onDeviceLocationChanged(results: List&lt;Address&gt;?)<br>    }</pre><pre>    companion object {<br>        // The minimum distance to change Updates in meters<br>        private const val UPDATE_FREQUENCY_DISTANCE: Long = 1 // 10 meters</pre><pre>        // The minimum time between updates in milliseconds<br>        private const val UPDATE_FREQUENCY_TIME: Long = 1 // 1 minute<br>        private val TAG = DeviceLocationTracker::class.java.simpleName<br>    }<br>}</pre><p>Next, add Strings for the Alert dialog to enable GPS if GPS is disable</p><pre>   &lt;string name=&quot;title_enable_gps&quot;&gt;Enable GPS&lt;/string&gt;<br>   &lt;string name=&quot;desc_enable_gps&quot;&gt;GPS is not enabled. Do you want to go to settings menu?&lt;/string&gt;<br>    &lt;string name=&quot;btn_settings&quot;&gt;Open Settings&lt;/string&gt;<br>    &lt;string name=&quot;btn_cancel&quot;&gt;Cancel&lt;/string&gt;</pre><p>Add these Permission in your Android manifest and request them in app start</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_GPS&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_LOCATION&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt;</pre><p><strong>Usage</strong></p><p>Implement DeviceLocationListener in your Activity/Fragment class</p><pre>class MainActivity : AppCompatActivity, DeviceLocationTracker.DeviceLocationListener {</pre><p>Override onDeviceLocationChanged callback. You will get current location in onDeviceLocationChanged</p><pre>override fun onDeviceLocationChanged(results: List&lt;Address&gt;?) {<br>        val currntLocation = results?.get(0);<br>        currntLocation?.apply {<br>             currentlLat = latitude<br>             currentLng = longitude<br>             Country = countryCode<br>             cityName = getAddressLine(0)<br>          <br>        }</pre><pre>    }</pre><p>To start tracking create a DeviceLocationTracker object in onCreate method of your. Pass the Activity as Context &amp; this as DeviceLocationListener.</p><pre>private lateinit var deviceLocationTracker: DeviceLocationTracker</pre><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        ...<br>        deviceLocationTracker= DeviceLocationTracker(this, this)</pre><p>That is it, now you will start to get location update in onDeviceLocationChanged.</p><p>Please clap if it helped you. Your response motivates me on keep sharing new ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ec19b67a97" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>